drl47263 2019-05-20 02:17
浏览 35
已采纳

解释如何在PHP中使用简单的路由系统

Hello everybody I am new with Routing systems in Php. Searching on the web I have found this short code for explain how routing should work but... I cannot understand in which way It routes my request to the desired page:

<?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;
}

When I open it the first time it redirect me to index.php:

<h1>main</h1>

and the other page is about.php:

<h1>about</h1>

My question is: how can I switch to about.php using the routing system?

Because If I write inside the url localhost/simpleRouter/views/about.php it looks like I am bypassing the routing system.... so I cannot figure out how can I use it properly to switch between pages. Morover, the index.php page shows me MAIN and this is good, but i receive a the following:

Notice: Undefined index: REDIRECT_URL in D:\App\xAMPP\htdocs\studio\Php\SviluppareInPHP7\CAP7\simpleRouter\index.php on line 9

Thank you for answering my questions and helping me to improve my knowledge on this field.

展开全部

  • 写回答

1条回答 默认 最新

  • doufu6130 2019-05-20 02:47
    关注

    You are looking for URL Rewriting. You can configure your Webserver (Apache, NGinx, ...) to redirect all or some requests, e.g. to your router.php.

    Apache URL Rewriting
    NGinx URL Rewriting

    In your router.php, you can then extract the originally requested URL, e.g. about.php. Note that this is different to the views/about.php. The "Router" then includes the specified file. This allows you to use arbitrary URLs instead of filenames.

    Also check out the difference between REDIRECT_URL and REQUEST_URL here.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部