drl47263 2019-05-20 10: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 10: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.

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

报告相同问题?

悬赏问题

  • ¥170 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥15 键盘指令混乱情况下的启动盘系统重装