我无法掌握处理 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/