【问题标题】:Explanation how to use a simple routing system in PHP解释如何在 PHP 中使用简单的路由系统
【发布时间】:2019-05-20 10:17:52
【问题描述】:

大家好,我是 PHP 中路由系统的新手。在网上搜索我发现了这个简短的代码来解释路由应该如何工作但是......我不明白它以哪种方式将我的请求路由到所需的页面:

<?php

// Get the requested path with $_SERVER['REDIRECT_URL'],
// and require the page you want to display. I have '' and '/' for both url.com/ and url.com.

// REDIRECT_URL returns normal url e.g. /review,
// in the other hand REQUEST_URI returns including query string e.g. /review?page=4

$request = $_SERVER['REDIRECT_URL'];

switch ($request) {
    case '/' :
        require __DIR__ . '/views/index.php';
        break;

    case '' :
        require __DIR__ . '/views/index.php';
        break;

    case '/about' :
        require __DIR__ . '/views/about.php';
        break;

    default:
        require __DIR__ . '/views/404.php';
        break;
}

当我第一次打开它时,它会将我重定向到 index.php:

<h1>main</h1>

另外一个页面是about.php:

<h1>about</h1>

我的问题是:如何使用路由系统切换到about.php?

因为如果我在 url localhost/simpleRouter/views/about.php 中写入,看起来我正在绕过路由系统....所以我无法弄清楚如何正确使用它在页面之间切换。 Morover,index.php 页面向我显示 MAIN,这很好,但我收到以下内容:

注意:未定义的索引:REDIRECT_URL 在 D:\App\xAMPP\htdocs\studio\Php\SviluppareInPHP7\CAP7\simpleRouter\index.php 在第 9 行

感谢您回答我的问题并帮助我提高在该领域的知识。

【问题讨论】:

    标签: php routing


    【解决方案1】:

    您正在寻找 URL 重写。您可以配置您的 Web 服务器(Apache、NGinx、...)以重定向所有或部分请求,例如到你的 router.php。

    Apache URL Rewriting
    NGinx URL Rewriting

    在您的 router.php 中,您可以提取最初请求的 URL,例如about.php。请注意,这与views/about.php 不同。 然后“路由器”包含指定的文件。这允许您使用任意 URL 而不是文件名。

    还可以查看 REDIRECT_URL 和 REQUEST_URL here 之间的区别。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-05
      • 2017-06-14
      • 2013-12-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多