You have already know that generally you send external API request, you also need to send Content-Type in header. Some API only accepts request if you sent proper headers. When the API call succeed, the server also send headers in response.
Headers are the additional data which are send with the request and response. Generally the header data contains information about data-type, request source and authentication credentials etc.
You may want to get information about headers and validate request. PHP gives you several ways to get headers from request and response.
In this article, we will discuss few ways how to get headers from request and response sent by server.
The first and widely used to get headers from request is using PHP curl. This method also used to get headers from all type of request.
Here is the below example how you can get headers array:
<?php
$url = 'https://laravelcode.com';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, true); // this will include headers in request
curl_setopt($ch, CURLOPT_NOBODY, true); // this option will remove body from response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
$headers = explode(PHP_EOL, $response);
print_r($headers);
This will return header array in response:
You can convert headers in key:value format using below loop.
$data = [];
foreach ($headers as $value) {
$parts = explode(':', $value);
if (count($parts) === 2) {
$data[trim($parts[0])] = trim($parts[1]);
}
}
print_r($data);
apache_request_headers() function returns all headers for current request. The function returns associative array of all the HTTP headers in the current request. It returns false on failure.
<?php
$headers = apache_request_headers();
print_r($headers);
This will return response for my localhost web request:
get_headers() function returns all response headers sent by the server.
Below example shows the response headers for Google homepage:
<?php
$headers = get_headers('https://www.google.com');
print_r($headers);
It will return the array of headers sent by Google server:
I hope you liked the article and help in your web development.
Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]
Laravel Telescope Installation and Configuration Tutorial
Laravel provide some official packages w...Angular and Laravel CORS Access-Control-Allow-Origin Issues
I was woking on a Laravel API applicatio...How to Check for an Empty String in JavaScript
Use the === Operator You can use the...How to set default application to open files in FileZilla
FileZilla is a open-source multi-platfor...Install Android Studio in Windows 10
Android Studio is Google's official...