php - 处理 RESTful url 的 PHP

标签 php url rest mod-rewrite query-string

我无法掌握处理 RESTful url 的最合适方法。

我有这样的 url:

http://localhost/products 
http://localhost/products/123
http://localhost/products/123/color 

最初:

http://localhost/index.php?handler=products&productID=123&additional=color

至于现在我正在使用 mod_rewrite:

RewriteRule ^([^/]*)([/])?([^/]*)?([/])?(.*)$ /index.php?handler=$1&productID=$3&additional=$5 [L,QSA]

然后我将 index.php 中的请求拼凑在一起,类似于:

if ($_GET['handler'] == 'products' && isset($_GET['productID'])) {
   // get product by its id.
}

我见过一些人将 GET 查询创建为一个字符串,例如:

if ($_GET['handler'] == 'products/123/color')

那么,例如,您是否使用正则表达式从查询字符串中获取值?

这是处理这些 url 的更好方法吗? 这些不同方法的优缺点是什么? 有没有更好的方法?

最佳答案

此 .htaccess 条目会将除现有文件之外的所有内容发送到 index.php:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php

然后你可以做这样的事情来将 url 转换成一个数组:

$url_array = explode('/', $_SERVER['REQUEST_URI']);
array_shift($url_array); // remove first value as it's empty
array_pop($url_array); // remove last value as it's empty

然后就可以这样使用switch了:

switch ($url_array[0]) {

    case 'products' :
        // further products switch on url_array[1] if applicable
        break;

    case 'foo' :
        // whatever
        break;

    default :
        // home/login/etc
        break;

}

这就是我通常做的事情。

关于php - 处理 RESTful url 的 PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13654990/

相关文章:

iOS:是否有更好的方法以 POST 方式将数据传输到服务器?

javascript - 在 MediaWiki 站点上通过 JS 更改 URL 字符串

javascript - Angular 6 : HttpHeaders Cannot read property 'length' of null in Chrome and IE11 (and not in Firefox)

rest - 你如何删除一个 GitHub 拉取请求请求审查?

php - 在 Sublime text 2 中,php 自动完成功能不起作用

php - 如何展示多个分类以及每个分类下的产品?

algorithm - 如何创建 URL 缩短器?

php - 全局与定义

php - 一个查询中有两个 mysql 选择 - 一个接一个

python - 我应该在 Django Rest Framework 中使用 JWT 还是 Basic Token 身份验证?