简体   繁体   English

如何从http请求获取URI参数

[英]How to get to URI parameters from an http request

I am new to restful architecture and i want to create an simple api for my application from scratch.....without any frameworks. 我是静态架构的新手,我想从头开始为我的应用程序创建一个简单的API .....没有任何框架。 At the moment i'm trying to understand how to get the "users" parameter in my URI so that i can route action to a controller that handles user login and registration. 目前,我正试图了解如何在URI中获取“ users”参数,以便可以将操作路由至处理用户登录和注册的控制器。 so far i have being able to view my URI with "$_SERVER['REQUEST_URI']" and the post method with "$_SERVER['REQUEST_METHOD']" but i'm unable to get the "users" parameter of the request ) when i add the "usesr" it return 404 error. 到目前为止,我已经能够使用“ $ _SERVER ['REQUEST_URI']”查看我的URI和使用“ $ _SERVER ['REQUEST_METHOD']”进行发布的方法,但是我无法获取请求的“ users”参数)当我添加“ usesr”时,它返回404错误。 Please can one enlighten me about....how this works and what i am doing wrong, thanks in advance. 请提前给我一个启发。...工作原理以及我做错了什么。

Here is my code 这是我的代码

$method =  $_SERVER['REQUEST_METHOD'];
$path = $_SERVER['REQUEST_URI'];

$resource = array_shift($path);

if($resource == 'users'){
   $name = array_shift($path);

   if(empty($name)){
       echo $method;
   }else{
       echo $method ."  ".$name;
   }
}else{
   header('HTTP/1.1 404 Not Found');
}

When you go to the /users url, the server tries to access that specific page, and there isn't anything there. 当您转到/users URL时,服务器尝试访问该特定页面,并且那里没有任何内容。 You need to pass in whatever route you want using a query string. 您需要使用查询字符串传递想要的任何路由。
So do /calendar_app_api?route=users or /calendar_app_api?user_id=1 /calendar_app_api?route=users/calendar_app_api?user_id=1
and then get the information through the $_GET array. 然后通过$_GET数组获取信息。

Or what you can do is configure the server to route all requests to one index file and force anything after that to be passed as a query. 或者您可以做的是将服务器配置为将所有请求路由到一个索引文件,然后强制将所有请求作为查询传递。 check this resource out 签出此资源

$_SERVER['REQUEST_URI'] doesn't return an array, so I don't think array_shift is going to return what you have in mind. $_SERVER['REQUEST_URI']不返回数组,因此我不认为array_shift将返回您所想的内容。 You can use pathinfo to get an array of all of the path components, including the filename, which would be the part of the path following the last slash in the URL: 您可以使用pathinfo获取所有路径组件的数组,包括文件名,该文件名将是URL中最后一个斜杠之后的路径的一部分:

$pathinfo = pathinfo($_SERVER['REQUEST_URI']);

$resource = $pathinfo['filename'];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM