-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path03demo-response-headers.php
More file actions
64 lines (50 loc) · 1.88 KB
/
03demo-response-headers.php
File metadata and controls
64 lines (50 loc) · 1.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
<?php
/***
* Reading response headers from an API call using cURL
* * This script demonstrates how to make an API call using cURL in PHP,
* * and how to read the response headers and body.
*
* */
//using curl for api call
$ch = curl_init();
// curl_setopt($ch, CURLOPT_URL, );
// curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//set headers
$headers = [
"Authorization: Client-ID A1XKO9j45wVD3gjxvLicqMyiIfOx1ekm9UMMIUsjrbQ"
];
$responseHeaders = [];
// Define a callback function to handle the headers
$header_callback = function($ch, $header) use (&$responseHeaders) {
// Parse the header line
$len = strlen($header);
$header = explode(':', $header, 2);
if (count($header) < 2) {
// Invalid header line
return $len;
}
// Store the header name and value
$responseHeaders[trim($header[0])] = trim($header[1]);
return $len;
};
curl_setopt_array($ch, [
// CURLOPT_URL => 'http://api.weatherapi.com/v1/current.json?key=e81d26fea2c54855b4d153248251506&q=Bhubaneswar&aqi=yes',
CURLOPT_URL => 'https://api.unsplash.com/photos/random',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => $headers,
// CURLOPT_HEADER => true, // Include the header in the output for checking response headers
CURLOPT_HEADERFUNCTION => $header_callback
]);
// Execute the cURL request and get the response
// This will return the response as a string instead of outputting it directly
$response = curl_exec($ch);
//get the http status code
$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
//checking the content type and content length from the response headers
$contentType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
$contentLength = curl_getinfo($ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD);
curl_close($ch);
// Output the response and status code
echo "HTTP Status Code: " . $statusCode . "<br/>";
print_r($responseHeaders);
echo $response . "<br/>";