cURL PHP新手需要一只手

时间:2017-08-29 23:41:27

标签: php curl

我对PHP中的cURL请求完全不熟悉。

我有一个API,它给我以下信息,并希望我通过cURL发送POST请求。我已经尝试了一些基本的cURL示例,但不知道应该如何发送附加数据。

API文档包含以下内容:

curl https://api.23andme.com/token/
         -d client_id=xxx \
         -d client_secret=yyy \
         -d grant_type=authorization_code \
         -d code=zzz \
         -d "redirect_uri=https://localhost:5000/receive_code/"
         -d "scope=basic%20rs3094315"

这是我的示例代码:

    $data = array(
        "client_id" => $client_id, 
        "client_secret" => $client_secret,
        "grant_type" => "authorization_code",
        "code" => $code,
        "redirect_uri" => "http://localhost/23andme/",
        "scope" => "basic"
        ); 



$ch = curl_init($url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);


    $response = curl_exec($ch); //Uncomment to make it live again

    if (!$response) 
    {
        return false;
    }

    echo json_decode($response);

2 个答案:

答案 0 :(得分:1)

你可以尝试

curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));

您的数据阵列会将其作为POST数据发送,因为您已经拥有curl_setopt($ch, CURLOPT_POST, true);

http://php.net/manual/en/function.curl-setopt.php

所以

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

干杯

答案 1 :(得分:-1)

您在代码中遗漏了两件事,这是一个使用您的代码作为基础的完整示例:

<?php

    /* you must define an URL to POST to */
    $url = "";

    $data = array(
                  "client_id" => $client_id, 
                  "client_secret" => $client_secret,
                  "grant_type" => "authorization_code",
                  "code" => $code,
                  "redirect_uri" => "http://localhost:8080/nope",
                  "scope" => "basic"
                 ); 

    $ch = curl_init($url);
          curl_setopt($ch, CURLOPT_POST, true);
          curl_setopt($ch, CURLOPT_HTTPHEADER, $data);
          curl_setopt($ch, CURLOPT_RETURNTRANSFER, true)

          /* this line below was missing in your code */;
          curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));        

    $response = curl_exec($ch);

    if (!$response) 
    {
        echo 'A error has occurred ' . curl_error($ch);
        return false;
    }

    echo json_decode($response);

?>

尝试并根据您的需求进行调整。