Rewriting URLs in PHP instead of server config

拥有回忆 提交于 2019-12-04 06:17:55

问题


I'm looking for a very lightweight routing framework (to go with php-skel).

The first thing I'd like to investigate is specifying rewrite rules in a php file ("not found" handler) in a similar way to how this is specified in the server configs.

Here's a potential example (but I'm wanting to know what frameworks provide something this lightweight):

File route.php:

route('application/api', '/api/index.php');
route('application', '/application/index.php');

File appplication/index.php:

route(':module/:action', function($module, $action) {
    include(__DIR__ . '/' . $module . '/' . $action . '.php');
});

What are the lightweight routing frameworks / functions or techniques?


回答1:


The php way:

http://example.com/index.php/controller/action/variables

$routing = explode("/" ,$_SERVER['PATH_INFO']);
$controller = $routing[1];
$action = $routing[2];
$variables = $routing[3];



回答2:


PHP has a parse url function that could be easily used to route. You can then call explode() on the path portion that is returned to get an array of the url components.




回答3:


PHP can't rewrite URLs the way mod_rewrite can, it can only redirect to other pages, which'd basically double the number of hits on your server (1 hit on php script, 2nd hit on redirect target).

However, you can have the PHP script dynamically load up the "redirect" pages' contents:

switch($_GET['page']) {
    case 1:
        include('page1.php');
        break;
    case 2:
        include('page2.php');
        break;
    default:
        include('page1.php');
}

this'd be pretty much transparent to the user, and you get basically the same effect as mod_rewrite. With appropriate query and path_info parameters, you can duplicate a mod_write "pretty" url fairly well.



来源:https://stackoverflow.com/questions/7196698/rewriting-urls-in-php-instead-of-server-config

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!