在 PHP 中使用 data-urlencode 获取请求

GET request with data-urlencode in PHP

我正在尝试从 PHP 程序对 Influx 数据库进行 API 调用。要发出的 curl 请求是 -

curl -G 'http://localhost:8086/query?pretty=true' --data-urlencode "q=SHOW MEASUREMENTS"

PHP 中我坚持使用的代码是 -

$curl = curl_init();
curl_setopt_array($curl, array(
    CURLOPT_URL => "http://localhost:8086/query?pretty=true",
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "GET",
    CURLOPT_HTTPHEADER => array(
        "cache-control: no-cache"
    ),
));

我不确定我应该在哪个 curl_setopt_array 发送 q=SHOW MEASUREMENTS

$query = urlencode("SHOW MEASUREMENTS");

$curl = curl_init();
curl_setopt_array($curl, array(
    CURLOPT_URL => "http://localhost:8086/query?pretty=true&q=" . $query,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "GET",
    CURLOPT_HTTPHEADER => array(
        "cache-control: no-cache"
    ),
));

简单回答:这是错误的!您应该转义 url 字符串中的空格。

$curl = curl_init();
$q =  curl_escape($curl ,'SHOW MEASUREMENTS With spaces');
$url = "http://localhost:8086/query?pretty=true&q={$q}";

curl_setopt_array($curl, array(
   CURLOPT_RETURNTRANSFER => 1,
   CURLOPT_URL => $url ,
   CURLOPT_SSL_VERIFYPEER => false, // If You have https://
   CURLOPT_SSL_VERIFYHOST => false,
   CURLOPT_CUSTOMREQUEST => "GET",
));
// Send the request & save response to $resp
$resp = curl_exec($curl);
if( !$resp ){
   // log this Curl ERROR: 
   echo curl_error($curl) ;
}

curl_close($curl);