I am trying to parse an API request with cURL, however I've just discovered (with curl_getinfo
) after hours of debugging that my URL is being formatted - specifically special characters such as /
and ?
.
This is being caused by the fact that I am causing urlencode($apiQuery)
which formats the url to remove whitespaces, but incidentally causes issues for the entire url.
I am trying to write this in PHP, and have set my cURL request as follows:
$apiQuery = 'api.server.com/v0/Accounts/USER/INSTRUMENT?channels=all&start=2022-10-30 21:00:00';
$headers = array(
'Accept: application/json',
'Content-Type: application/json',
);
$c = curl_init();
curl_setopt($c, CURLOPT_URL, urlencode($apiQuery));
curl_setopt($c, CURLOPT_HTTPHEADER, $headers);
curl_setopt($c, CURLOPT_HEADER, 0);
curl_setopt( $c , CURLOPT_RETURNTRANSFER, true);
curl_setopt( $c , CURLOPT_SSL_VERIFYPEER, false);
curl_setopt( $c , CURLOPT_SSL_VERIFYHOST, false);
curl_setopt( $c , CURLOPT_TIMEOUT, 50000); // 50 sec
$resultA = curl_exec($c);
print_r(curl_getinfo($c));
where $resultA
returns nothing, and curl_getinfo($c)
returns:
Array
(
[url] => HTTP://api.server.com/v0/Accounts/USER/INSTRUMENT?channels=all&start=2022-10-30 21:00:00/
[content_type] =>
[http_code] => 0
[header_size] => 0
[request_size] => 0
[filetime] => -1
[ssl_verify_result] => 0
[redirect_count] => 0
[total_time] => 0
[namelookup_time] => 0
[connect_time] => 0
[pretransfer_time] => 0
[size_upload] => 0
[size_download] => 0
[speed_download] => 0
[speed_upload] => 0
[download_content_length] => -1
[upload_content_length] => -1
[starttransfer_time] => 0
[redirect_time] => 0
[redirect_url] =>
[primary_ip] =>
[certinfo] => Array
(
)
[primary_port] => 0
[local_ip] =>
[local_port] => 0
)
CodePudding user response:
I would suggest to split the $apiQuery string:
$apiQuery = 'http://api.server.com/v0/Accounts';
$apiQuery .= '/' . urlencode($user);
$apiQuery .= '/' . urlencode($instrument);
$apiQuery .= '?';
$apiQuery .= http_build_query([
'channels' => 'all',
'start' => '2022-10-30 21:00:00',
]);
http_build_query
also url escapes your params.