简体   繁体   English

如何使用Curl同时进行GET和POST?

[英]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 keyHMAC 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. 好的,有两种方法可以处理这种情况。

  • Instead of submitting the authentication info via POST , create custom headers with CURLOPT_HTTPHEADER' 无需通过POST提交身份验证信息,而是使用CURLOPT_HTTPHEADER'创建自定义标头
  • Trick cURL, submitting POST data but defining CURLOPT_CUSTOMREQUEST to GET . 欺骗cURL,提交POST数据,但为GET定义CURLOPT_CUSTOMREQUEST

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

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