I'm using curl with PHP for getting the header response of an API call.
This is my code:
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'http://localapi.com/v1/users');
curl_setopt($curl, CURLOPT_HEADER, true);
curl_setopt($curl, CURLOPT_NOBODY, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_TIMEOUT, 10);
curl_setopt($curl, CURLOPT_HTTPHEADER, array("authorization: Basic dmt5MVVTeXg3ZXpKYXVEZGtta2phZThfQ0tXa2tTQkY6"));
$response = curl_exec($curl);
The $response returna the header:
HTTP/1.1 200 OK Date: Wed, 15 Jun 2016 13:48:43 GMT Server:
Apache/2.4.18 (Unix) PHP/5.5.31 X-Powered-By: PHP/5.5.31
X-Rate-Limit-Limit: 1 X-Rate-Limit-Remaining: 0 X-Rate-Limit-Reset: 0
X-Pagination-Total-Count: 1 X-Pagination-Page-Count: 1
X-Pagination-Current-Page: 1 X-Pagination-Per-Page: 20 Link: ;
rel=self Content-Type: application/json; charset=UTF-8 1
Is there a method for access to the single header variables like an array?
Thanks in advance for the help.
You can assign a callback for Curl to process the headers in the response using CURLOPT_HEADERFUNCTION. By providing the $headers variable for the callback to assign the results, you can access them as an array after curl_exec has finished.
$headers = [];
curl_setopt($curl, CURLOPT_HEADERFUNCTION, function ($ch, $header) use (&$headers) {
$matches = array();
if ( preg_match('/^([^:]+)\s*:\s*([^\x0D\x0A]*)\x0D?\x0A?$/', $header, $matches) )
{
$headers[$matches[1]][] = $matches[2];
}
return strlen($header);
});
curl_exec($curl);
$headers will now contain an associative array of the response headers
Related
I'm trying to build a custom accounting report using the PayPal NVP API that will get all transactions for a specific date range.
My code:
$headers = array(
'USER' => $production_user,
'PWD' => $production_pass,
'SIGNATURE' => $production_sig
);
$nvp = array(
'METHOD' => 'TransactionSearch',
'TRANSACTIONCLASS' => 'RECEIVED',
'STARTDATE' => '2016-12-01T00:00:00Z',
'ENDDATE' => '2016-12-31T00:00:00Z'
);
$request_url = "https://api-3t.paypal.com/nvp?".http_build_query($nvp);
$curl = curl_init($request_url);
curl_setopt($curl, CURLOPT_FAILONERROR, true);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_HEADER, $headers);
curl_setopt($curl, CURLOPT_POST, 1);
$result = curl_exec($curl);
$result = explode("&", $result);
foreach($result as $f=>$v){
$t = explode("=", $v);
echo $t[0]." => ".urldecode($t[1]);
echo "<br>";
}
Here is what gets printed:
HTTP/1.1 200 OK Date: Fri, 10 Feb 2017 19:51:20 GMT Server: Apache X-PAYPAL-OPERATION-NAME: X-PAYPAL-API-RC: 10001 Connection: close Cache-Control: max-age => 0, no-cache, no-store, must-revalidate Pragma: no-cache HTTP_X_PP_AZ_LOCATOR: slcb.slc Paypal-Debug-Id: 484a759b46e4a Set-Cookie: X-PP-SILOVER
CORRELATIONID => some_random_characters
ACK => Failure
L_ERRORCODE0 => 10001
L_SHORTMESSAGE0 => Internal Error
L_LONGMESSAGE0 => Timeout processing request
Any assistance with this issue would be greatly appreciated!
You are using a post request and have not post data.
I do not know what PayPal wants to see but I'm guessing it's not what you are sending.
Some things to try:
If you need to pass the USER, PWD, and SIGNATURE in the Request Header do it like this:
$request = array();
$request[] = "USER: $production_user";
$request[] = "PWD: $production_pass";
$request[] = "SIGNATURE: $production_sig";
curl_setopt($ch, CURLOPT_HTTPHEADER, $request);
If the $nvp parameters need to be post data, try this:
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $nvp);
The $nvp can be passed as a query string in the post data also.
$query = http_build_query($nvp);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $query);
The difference is the Content-Type.
The first method:
Content-Type: application/x-www-form-urlencoded
The second method:
Content-Type: multipart/form-data
To help in trouble shooting it would be good to see both the request and response header.
Use these options to get the headers:
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
The Request Header will be in the 'curl_getinfo()'
curl_setopt($ch, CURLOPT_HEADER, true);
$result = curl_exec($ch);
$info = curl_getinfo($ch);
var_export($info);
The above gives lots of other details of the request. If you only want to see the header:
$request = curl_getinfo($ch, CURLINFO_HEADER_OUT);
To get the response header:
$result = curl_exec($ch);
$skip = intval(curl_getinfo($ch, CURLINFO_HEADER_SIZE));
$response = substr($result ,0,$skip);
$result = substr($result ,$skip);
I write a php script to upload a media file but when I use it the response occurs:
Missing Content-Length header.
The php code is:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://raz-ul.domenka.com/v1/AUTH_8a619275-f933-4da1-b289-0ca1a2a3a4a5/bcd/drop1.avi");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
$headers = array();
$headers[] = "X-Auth-Token: AUTH_tkd78bedda5bec4613b80becb1b2b3b4b5";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
$header_size = $info['header_size'];
$header = substr($response, 0, $header_size);
var_dump($header);
On the other hand When I do something like that in cli I succeed:
kinduser#43915-1-c1c2c3-01:~/public_html/adam$ curl -i -X PUT -H "X-Auth-Token: AUTH_tkd78bedda5bec4613b80bec0123456789" -T drop.avi https://raz-ul.domenka.com/v1/AUTH_8a619275-f933-4da1-b289-0ca1a2a3a4a5/bcd/drop.avi
HTTP/1.1 100 Continue
HTTP/1.1 201 Created
Last-Modified: Thu, 16 Feb 2017 10:12:54 GMT
Content-Length: 0
Etag: fa60ba1b78299bfae5ac61d1d2d3d4d5
Content-Type: text/html; charset=UTF-8
X-Trans-Id: tx114b22027223415c850db-e1e2e3e4e5
Date: Thu, 16 Feb 2017 10:12:53 GMT
kinduser#43915-1-c1c2c3-01:~/public_html/adam$
But I would like to do this in php. How to fix my php code?
Update
I added some code to tell curl which file to send. It sent the file but the file changed on the server. It got a bigger weight from 660kB to 660.31kB. After downloading to my pc it got impossible to open via video player.
That code is like this now:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://raz-ul.domenka.com/v1/AUTH_8a619275-f933-4da1-b289-0ca1a2a3a4a5/bcd/drop7.avi");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
$headers = array();
$headers[] = "X-Auth-Token: AUTH_tkd78bedda5bec4613b80becb1b2b3b4b5";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$curlFile = curl_file_create ('./drop.avi');
$post = array (
'extra_info' => '123456',
'file_contents' => $curlFile
);
curl_setopt ($ch, CURLOPT_POSTFIELDS, $post);
$response = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
$header_size = $info['header_size'];
$header = substr($response, 0, $header_size);
var_dump($header);
Any idea how to fix it?
I am trying to send a PATCH request through cURL and i get this response:
HTTP/1.1 400 Bad Request Server: nginx Date: Fri, 01 Apr 2016 09:16:03 GMT Content-Type: application/problem+json Content-Length: 198 Connection: keep-alive X-Powered-By: PHP/5.6.19 {"type":"http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html","title":"Internal Server Error","status":500,"detail":"setValidationGroup() expects a list of valid input names; \"\" was not found"}
My code:
sendData("2016-10-01", "2016-10-02", "1234");
function sendData($from, $to, $property){
$data = array(
"from" => $from,
"to" => $to,
"booking_id" => 3
);
$data = json_encode($data);
echo $data . "<br>";
$url = "https://api.urlhost.com/property/".$property."/avail";
echo $url. "<br>";
$headers = array('Authorization: Basic dGVhQGJsdW1lbnJpdmllcmEuOIT6Qmx1bQVucm17aAKyzTtyfw==','Content-Type: application/json-patch+json');
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PATCH');
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_HEADER, true);
$response = curl_exec($curl);
echo ($response) . PHP_EOL;
//print_r(curl_getinfo($ch));
curl_close($curl);
}
When i echo the data and url i get these:
{"from":"2016-10-01","to":"2016-10-02","booking_id":3}
https://api.urlhost.com/property/1234/avail
But still is giving me this error. Any suggestions why this might happen?
I am trying to POST JSON in my code.Though I set the header Content_Type:application/json the receiving server gets as Content-Type: application/x-www-form-urlencoded
$Content_Type = "application/json";
$header_info = "X_RESTBUS_MESSAGE_ID:".$X_RESTBUS_MESSAGE_ID.","."X_BU_ID:".$X_BU_ID.","."Content_Type:".$Content_Type;
$url = $server_url;
$content = json_encode($body_data);
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER,
array($header_info));
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $content);
$json_response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
but the server receiving the POST call gets as
13 > X_RESTBUS_MESSAGE_ID: <aaaaa>,X_BU_ID:<xxxx>,Content_Type:application/json
13 > Accept: */*
13 > Content-Type: application/x-www-form-urlencoded
13 > Content-Length: 641
13 > Host: localhost:49111
13 >
You've CURLOPT_HTTPHEADER to be an array with a single item in it, which is a string or comma separated headers.
You should set it to be an associative array where each key/value pair is a single header.
You also need to spell the header name correctly. Content-Type has a hyphen in the middle, not an underscore.
$headers = array(
"X_RESTBUS_MESSAGE_ID" => $X_RESTBUS_MESSAGE_ID,
"X_BU_ID" => $X_BU_ID,
"Content-Type" => $Content_Type
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
Please help me to decode this below output, which I got when I run cURL.
Here is my code:
$headers = array(
'Accept:application/json',
'X-TB-PARTNER-AUTH: 45504852:abcdksalkrjwejkrjr'
);
$process = curl_init();
curl_setopt($process, CURLOPT_URL,"https://api.opentok.com/session/create");
curl_setopt($process, CURLOPT_HTTPHEADER, $headers);
curl_setopt($process, CURLOPT_HEADER, 1);
curl_setopt($process, CURLOPT_POST, 1);
curl_setopt($process, CURLOPT_POSTFIELDS, 'p2p.preference=disabled');
curl_setopt($process, CURLOPT_RETURNTRANSFER, 1);
$server_output = curl_exec($process);
print_r($server_output);
And my output is:
HTTP/1.1 200 OK
Server: nginx
Date: Mon, 14 Mar 2016 10:10:19 GMT
Content-Type: application/json
Connection: keep-alive
Access-Control-Allow-Origin: *
Content-Length: 180
Strict-Transport-Security: max-age=31536000; includeSubdomains
[{"session_id":"2_MX40NTUwNDg1Mn5-MTQ1Nzk1MDIxOTVNGZmUwS1N3bFF2LzhvREZORVN-fg","partner_id":"404852","create_dt":"Mon Mar 12 03:10:19 PDT 2016","media_server_url":""}]
Are you confused by the fact HTTP headers are included in the output?
If so - drop this line: curl_setopt($process, CURLOPT_HEADER, 1);
That is responsible for including the HTTP headers in the output. (See http://php.net/manual/en/function.curl-setopt.php )
Use json_decode function to parse it as an object or array:
$result = '[{"session_id":"2_MX40NTUwNDg1Mn5-MTQ1Nzk1MDIxOTVNGZmUwS1N3bFF2LzhvREZORVN-fg","partner_id":"404852","create_dt":"Mon Mar 12 03:10:19 PDT 2016","media_server_url":""}]';
echo "<pre>";
$json = json_decode($result,true);
print_r($json);// You may access print_r($json{0}->create_dt); etc
References:
json_decode - PHP Manual