【问题标题】:url routing with PHP and .htaccess使用 PHP 和 .htaccess 进行 url 路由
【发布时间】:2016-05-01 01:55:37
【问题描述】:

我想使用 MVC 模式来划分我的逻辑,从表示和数据。

嗯,我一直在寻找我。但事实是,我什至不知道要搜索什么。

我正在尝试在 php 中设置 MVC 框架。我正在关注 youtube 上的教程,但我被困在路由点。

我读过很多指南,每一个都以不同的方式教授东西,只会造成更多的混乱。

重点是:

我有一个 .htaccess 文件,其中包含一些指令(但问题是我不知道所有这些指令的含义。我从不理解 htaccess 逻辑)

Options -MultiViews
RewriteEngine On

#I think this sets the base url of the site?
RewriteBase /~caiuscitiriga/mvc/public

#What does this mean??
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f

#AND THIS?!
RewriteRule ^(.+)$ index.php?url=$1 [QSA,L]

然后我有这些 php 脚本:

索引.php

<?php

require_once '../app/init.php';

$app = new App();

init.php

<?php

require_once 'core/App.php';
require_once 'core/Controller.php';

App.php

不要问我为什么使用 filter_var 和 rtrim。因为这正是我想弄清楚的。正如我之前所说,这段代码不是我的。我确定它的技巧正是在 .htacess 和 App.php 中,但我不明白其中的逻辑

class App{


    protected $controller = 'home';
    protected $method = 'index';
    protected $params = [];


    public function __construct()
    {
        print_r($this->parseUrl());
    }

    public function parseUrl()
    {
        if(isset($_GET['url']))
        {
            return $url = explode('/', filter_var(rtrim($_GET['url'], '/'), FILTER_SANITIZE_URL));
        }
    }
}

Controller.php

<?php

class Controller{

}

home.php

<?php

class Home extends Controller{

    public function index()
    {
        echo 'home/index';
    }
}

如果我通过此网址:localhost/~caiuscitiriga/mvc/public/home/index/maxine
我得到这个:数组([0] => home [1] => index [2] => maxine)

为什么?!!?我的意思是,它是正确的。但是为什么呢??

【问题讨论】:

  • 为什么我要以这种特定方式获取该数组? url的htacess是什么?在那之后,在返回 url 之前 php 到底做了什么?
  • 引用:“我从来没有理解过 htaccess 逻辑”...然后我建议你开始阅读文档而不是“大量指南”。

标签: php apache .htaccess apache2


【解决方案1】:
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+)$ index.php?url=$1 [QSA,L]

我将上面的内容读为,如果请求不是目录,而不是文件,则获取路径并将其传递给内部 index.php,并使用 url 属性作为路径。

那么现在

//example.com/big/bad/mamma

映射到

 //example.com/index.php?url=big/bad/mamma

如果你愿意,你可以像上面那样调用脚本。

然后您的解析 url 采用 url ('big/bad/mamma') 的值,如果有斜杠,则删除尾随斜杠。然后在遇到正斜杠的地方拆分字符串。所以你最终得到了三个部分。这就是您的数组中的内容。

来自manual:

FILTER_SANITIZE_URL 过滤器将删除除字母、数字和 $-_.+!*'(),{}|\^~[]`#%";/?:@&= 之外的所有字符。

但如果你想了解这些部分,请将其分解:

$url = $_GET['url'];
var_dump($url);
$url = rtrim($url, '/');
var_dump($url);
$url = filter_var($url, FILTER_SANITIZE_URL);
var_dump($url);
$url = explode('/', $url);
var_dump($url);

【讨论】:

  • 嗨!谢谢!这正是我一直在寻找的答案!现在我有一个有点好奇的问题。 filter_var 真的有必要吗?我尝试通过注释 $url = filter_var(...) 行来传递带有和不带有斜杠的 url,并且事情仍然运行良好......
  • 我想支持你的回答,但我只有 3 分 D:
猜你喜欢
  • 2016-01-09
  • 2013-12-08
  • 1970-01-01
  • 2017-12-04
  • 2018-11-19
  • 2014-04-16
  • 2014-06-28
  • 1970-01-01
  • 2021-05-08
相关资源
最近更新 更多