pradyotghate
pradyotghate

Reputation: 487

GET request with data-urlencode in PHP

I am trying to make an API call to Influx db from PHP program. The curl request to be made is -

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

The code in PHP that I am stuck with is -

$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"
    ),
));

I am not sure in which curl_setopt_array should I send the q=SHOW MEASUREMENTS

Upvotes: 5

Views: 17177

Answers (2)

dHajnal
dHajnal

Reputation: 41

Simple answer : This is wrong! You should escape spaces in url string.

$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);

Upvotes: 0

pradyotghate
pradyotghate

Reputation: 487

$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"
    ),
));

Upvotes: 7

Related Questions