【问题标题】:PHP 8 - Routing can't find requested URLPHP 8 - 路由找不到请求的 URL
【发布时间】:2021-04-15 14:24:58
【问题描述】:

我遇到了 PHP 8 路由问题。我正在创建我的 MVC“框架”以了解有关 OOP 的更多信息。我做了路由、控制器和视图——它有效,我很高兴。但我发现我会测试我的创作。这就是问题开始的地方,即如果路径为空(“”),则返回路由中询问的“主页”视图,但如果我在 URL 中输入“/test”,例如,我有一个返回消息“404 Not Found - 在此服务器上找不到请求的 URL。”即使给定的路由已添加到表中。怎么了?

.htaccess 文件

RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^(.+)$ index.php [QSA,L]

带有路由的index.php

<?php

/*
 * Require Composer
 */
require dirname(__DIR__) . '/vendor/autoload.php'; 

/*
 * Routing
 */

$routes = new Core\Router();

$routes->new('', ['controller' => 'HomeController', 'method' => 'index']);
$routes->new('/test', ['controller' => 'HomeController', 'method' => 'test']);

$routes->redirectToController($_SERVER['QUERY_STRING']);

Router.php 文件

<?php

namespace Core;

class Router
{

    /*
     * Routes and parameters array
     */
    protected $routes = [];
    protected $params = [];


    /*
     * Add a route to the route board
     */
    public function new($route, $params = [])
    {
        /* 
         * Converting routes strings to regular expressions 
         */
        $route = preg_replace('/\//', '\\/', $route);
        $route = preg_replace('/\{([a-z]+)\}/', '(?P<\1>[a-z-]+)', $route);
        $route = '/^' . $route . '$/i';

        $this->routes[$route] = $params;
    }


    /*
     * Get all routes from table
     */
    public function getRoutesTable() {
        return $this->routes;
    }


    /*
     * Checking if the specified path exists in the route table
     * and completing the parameters table
     */
    public function match($url)
    {

        foreach($this->routes as $route => $params) {
            
            if(preg_match($route, $url, $matches)) {
                foreach($matches as $key => $match) {
                    if(is_string($key)) {
                        $params[$key] = $match;
                    }
                }

                $this->params = $params;
                return true;
            }
        }

        return false;
    }

    
    /*
     * Get all params from table
     */
    public function getParamsTable() {
        return $this->params;
    }


    /*
     * Redirection to the appropriate controller action
     */
    public function redirectToController($requestUrl) {
        $requestUrl = explode('?', $requestUrl);
        $url = $requestUrl[0];
        
        if ($this->match($url)) {
            $controller = $this->params['controller'];
            $controller = "App\\Controllers\\$controller";

            if(class_exists($controller)) {
                $controller_obj = new $controller($this->params);
                $method = $this->params['method'];

                if(method_exists($controller, $method)) {
                    $controller_obj->$method();
                } else {
                    echo "Method $method() in controller $controller does not exists!";
                }

            } else {
                echo "Controller $controller not found!";
            }

        } else {
            echo "No routes matched!";
        }
    }
}

查看.php文件

<?php

namespace Core;

class View {
    public static function view($file) {
        $filename = "../App/Views/$file.php";
        
        if(file_exists($filename)) {
            require_once $filename;
        } else {
            echo "View $file is not exist!";
        }
    }
}

HomeController 文件

<?php

namespace App\Controllers;

use Core\Controller;
use Core\View;

class HomeController extends Controller {
    public function index() {
        return View::view('Home');
    }

    public function test() {
        return View::view('Test');
    }
}

文件夹结构

网络浏览器中的路由

我在 PHP 8.0 和 Windows 10 中使用 XAMPP。

【问题讨论】:

  • "如果我输入 "/test" " - 你的问题中的“/test” 中的空格是偶然的吗?否则它与“/test”不匹配是有道理的,因为这两个字符串是不同的。
  • 是的,我的问题有误。 “/test”是正确的
  • 我根本不明白这是如何工作的? $_SERVER['QUERY_STRING'] 不是 URL/路径,它只是 URL 中 ? 之后的内容。例如:https://example.com/test/?this-is-the-part-your-router-gets
  • 当我使用`'REQUEST_URL'`时,我也遇到了同样的问题。
  • REQUEST_URL 不是标准参数 afaik。你的意思可能是REQUEST_URI

标签: php web model-view-controller routes


【解决方案1】:

首先,选择以下两个选项之一继续。

选项 1:

如果 document root 设置为与 project root 相同,例如path/to/htdocs,在web服务器的配置文件中(可能是httpd.conf),类似这样:

DocumentRoot "/path/to/htdocs"   
<Directory "/path/to/htdocs">
    AllowOverride All
    Require all granted
</Directory>

然后在项目根目录中创建以下.htaccess,从path/to/htdocs/Public目录中删除任何.htaccess文件并重新启动Web服务器:

<IfModule dir_module>
    DirectoryIndex /Public/index.php /Public/index.html
</IfModule>

Options FollowSymLinks

RewriteEngine On
RewriteBase /Public/

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^(.*)$ index.php [QSA,L]

选项 2:

如果文档根设置为web服务器配置文件中的目录path/to/htdocs/Public(可能是httpd.conf),类似这样:

DocumentRoot "/path/to/htdocs/Public"   
<Directory "/path/to/htdocs/Public">
    AllowOverride All
    Require all granted
</Directory>

然后在目录path/to/htdocs/Public 中创建以下.htaccess,从项目根目录中删除任何其他.htaccess 文件(除非它可能包含一些相关设置,而不是@987654334 @) 并重启网络服务器::

Options FollowSymLinks

RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^(.*)$ index.php [QSA,L]

在您决定并继续使用上述选项之一后,编辑页面index.php,如下所示:

<?php

//...

/*
 * NOTE: A route pattern can not be an empty string.
 * If only the host is given as URL address, the slash 
 * character (e.g. "/") will be set as value of the
 * URI path, e.g. of $_SERVER['REQUEST_URI']. Therefore, 
 * the route pattern should be set to "/" as well.
 */
$routes->new('/', [
    'controller' => 'HomeController',
    'method' => 'index',
]);

//...

/*
 * In order to get the URI path, you must use the server 
 * parameter "REQUEST_URI" instead of "QUERY_STRING".
 */
$routes->redirectToController(
    $_SERVER['REQUEST_URI']
);

注意事项:

  • 关于将$_SERVER['QUERY_STRING'] 更改为$_SERVER['REQUEST_URI'],当然要感谢@MagnusEriksson。
  • 不可能有“MVC 框架”,而是“用于基于 MVC 的应用程序的 Web 框架”。这是因为框架只是库的集合(与 MVC 完全不相关),而这些库又被一个或多个实现 MVC 模式的应用程序使用。

如有任何其他问题,请随时向我们提问。

【讨论】:

  • 感谢您的帮助、cmets 和建议。我一定会问的!该问题可以通过第 3 种方式解决,即在 Apache httpd.conf 文件中搜索“404”,删除短语“ErrorDocument 404”旁边的注释并提供“index.php”文件所在文件夹的路径或.htaccess 文件位于参考索引
  • @FilipKrzyżanowski 欢迎您。哦,这似乎是编程世界中最漂亮的技巧之一 :-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-09-11
  • 2011-07-23
  • 2015-11-20
  • 2017-02-19
  • 2017-03-13
  • 2017-02-21
  • 1970-01-01
相关资源
最近更新 更多