使用 PHP 和 .htaccess 进行 url 路由


url routing with PHP and .htaccess

我想使用 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();

初始化.php

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

应用.php

不要问我为什么使用 filter_varrtrim。因为这正是我想要弄清楚的。正如我之前所说,这段代码不是我的。我确定它的诀窍正是在 .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));
        }
    }
}

控制器.php

<?php
class Controller{
}

首页.php

<?php
class Home extends Controller{
    public function index()
    {
        echo 'home/index';
    }
}

如果我传递这个网址:localhost/~caiuscitiriga/mvc/public/home/index/maxine
我得到这个: 数组 ( [0] => 主页 [1] => 索引 [2] => 马克辛 )

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

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+)$ index.php?url=$1 [QSA,L]

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

所以现在

//example.com/big/bad/mamma

映射到

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

如果需要,可以按上述方式调用脚本。

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

从手册:

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);