[英]How do I GET and POST at the same time with Curl?
I have a working "API" but noticed it's not REST because I was just using POST
requests passing a mode
variable for determining which action to do. 我有一个正常工作的“ API”,但注意到它不是REST,因为我只是在使用
POST
请求传递一个mode
变量来确定要执行的操作。 So now I'm changing the conditions that matched the mode
variable so that they match instead the HTTP Method
. 所以现在我要更改与
mode
变量匹配的条件,以使它们与HTTP Method
匹配。 But here comes my problem. 但是我的问题来了。
In every request I submit by POST a user
and a HMAC
of the data + user private key
. 在每个请求中,我通过POST提交了一个
user
和一个data + user private key
的HMAC
。 So in the case I wanted to get the data of a determined id
, I used curl
for creating a request with those variables and POST it to the URL api/id
. 因此,在我想要获取确定的
id
的数据的情况下,我使用curl
来创建带有这些变量的请求,并将其发布到URL api/id
。 Then there is a RewriteRule for changing that to api.php?id=$1
, so in my api.php
I had both data, the id
via GET
and the auth info via POST
. 然后有一个RewriteRule,将其更改为
api.php?id=$1
,所以在我的api.php
我同时拥有两个数据,即通过GET
获得的id
和通过POST
获得的身份验证信息。
So... if for getting a user's data I need to use the GET
method now, how can I submit (POST) the auth info as well? 所以...如果要获取用户的数据,我现在需要使用
GET
方法,那么如何也可以提交(POST)身份验证信息?
How was before (working but not as a REST API should work) 以前的样子(可以工作但不能作为REST API来工作)
api.php api.php
if ($_SERVER["REQUEST_METHOD"] === "POST"){
if ($_POST['mode'] === "get"){
get_data($_GET["id"]);
}
}
client.php client.php
$params = array('user' => 'qwerty', 'hash' => 'jFJKSAFhskafa');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://localhost/api/123";
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, count($params));
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
$output = curl_exec($ch);
curl_close($ch);
$data = json_decode($output, true);
}
How it should be: 应该如何:
api.php api.php
if ($_SERVER["REQUEST_METHOD"] === "GET"){
get_data($_GET["id"]);
}
client.php client.php
$params = array('user' => 'qwerty', 'hash' => 'jFJKSAFhskafa');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://localhost/api/123";
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//-------->>>> How do I send the params now?
$output = curl_exec($ch);
curl_close($ch);
$data = json_decode($output, true);
}
Ok, there are two ways of handling this situation. 好的,有两种方法可以处理这种情况。
POST
, create custom headers with CURLOPT_HTTPHEADER'
POST
提交身份验证信息,而是使用CURLOPT_HTTPHEADER'
创建自定义标头 POST
data but defining CURLOPT_CUSTOMREQUEST
to GET
. POST
数据,但为GET
定义CURLOPT_CUSTOMREQUEST
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.