了解一个PHP REST的API [英] Understanding a PHP RESTful API
问题描述
我有以下的XAMPP项目结构
I have the following XAMPP project structure
XAMPP的/ htdocs中/项目
XAMPP的/ htdocs中/项目/ index.php文件
XAMPP的/ htdocs中/项目/ API / index.php文件
xampp/htdocs/project
xampp/htdocs/project/index.php
xampp/htdocs/project/api/index.php
我还使用了如下因素的.htaccess:
I also use the folowing .htaccess :
RewriteEngine on
RewriteCond %{REQUEST_URI} !^/api/index\.php(/|$)
RewriteRule ^/api/(.*)$ /api/index.php/$1 [QSA,L]
当我做一个Ajax请求API /,我从API / index.php的结果 但是,如果我想要得到什么的API /用户的例子/?或者API /用户/ 5,其中5是ID。
When I make an Ajax request to api/, I get the results from api/index.php But what if I want to get the examples for api/users/? or api/users/5 where 5 is the ID.
推荐答案
通过你做的时候,你就会有相当多的重写条目。但这里有一个应该做你想要什么就用户:
By the time you are done, you'll have quite a lot of rewrite entries. But here's one that should do what you want with respect to users:
# /users/{id}
RewriteRule ^users/([0-9A-Za-z_\.-\@]+)$ users.php?id=$1 [QSA]
或者,如果你想要的一切,通过指数:
or, if you want everything to pass through index:
# /users/{id}
RewriteRule ^users/([0-9A-Za-z_\.-\@]+)$ index.php?userid=$1 [QSA]
和,如果你需要通过请求类型来区分(POST,GET,PUT等):
and, if you need to differentiate by request type (POST, GET, PUT, etc):
RewriteCond %{REQUEST_METHOD} ="post" [NC]
RewriteRule ^users/([0-9]+)$ index.php?id=$1&method=add_user [QSA]
这篇关于了解一个PHP REST的API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!