Sign in Registration
ArticlesDownloadServicesAudioContacts
ruen

How to send or receive HTTP request headers (browser or other client) in PHP

HTTP headers are almost always sent on every request for any web page. They allow you to tell the browser or another client information about the displayed content, they can contain a number of settings. It is known that there are two types of headings:

This article discusses the first type of headers, the request headers.

send-receive-delete-http-request-headers-php

How to send HTTP request headers

This can be done if you are using your client to query the server. For example, this could be a simple query using the CURL library:

  if ($ curl = curl_init ('https://example.com')) {
$ headers = array (
'Content-type: application / json',
'Content-length: 0',
);

curl_setopt ($ curl, CURLOPT_HTTPHEADER, $ headers);
curl_setopt ($ curl, CURLOPT_RETURNTRANSFER, true);
$ response = curl_exec ($ curl);
curl_close ($ curl);

return $ response;
}  

I must also say that the CURL library has its own predefined constants, which are read by the server as headers. For example, you can send an HTTP header User-Agent or others using similar code:

  curl_setopt ($ curl, CURLOPT_USERAGENT, 'User-Agent: Mozilla / 4.0 (compatible; MSIE 5.01; Widows NT)');  

How to get HTTP request headers

You may need to get headers for different purposes; for this, special features of programming languages ​​are used. There are several functions for getting headers in PHP. Here are the functions for getting headers in PHP :

Any function can be used to get headers. The getallheaders function is often used:

  foreach (getallheaders () as $ name => $ value) {
    echo "$ name: $ value \ n";
}  

However, it does not always work, for example, the error "Call to undefined function getallheaders ()" may occur. This means that the function is not defined and you need to use other functions or update PHP. Before using this function, you can check if it exists using the function_exists function. If no function works, you can select all headers from the $ _SERVER array, they are marked with the "HTTP_" prefix.

As you can see from the article, working with HTTP headers is quite simple, for this it is enough to use special tools PHP programming language .

Comments (0)
For commenting sign in or register.

Latest articles

Popular sections

Communication

Login to the web version
Android app:
Available on Google Play

Share this

Subscribe to