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.

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

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?