How do I add a header to a cURL request? [PHP Code]
To add a header to a cURL request, you need to use the -H command-line option and pass the name and value of the HTTP header in enclosed quotation marks. Headers without values must be followed by a semicolon. The number of cURL request headers is not limited. You can add as many cURL headers as you like. In this cURL header example, we are sending the X-Custom-Header and Content-Type request headers to the ReqBin echo URL. The PHP code was automatically generated for the Curl Add Header example.
cURL (stands for Client URL) is a popular command-line tool that you can use to transfer data to/from a server using a range of network protocols including HTTP, HTTPS and FTP. Developers can use the cURL project library (libcurl) to make HTTP requests directly from their applications.
Can I send custom HTTP headers using cURL?
Yes, you can add any custom HTTP header to your cURL request using the -H command-line option and send it to the server. Note that prior to 2011, it is recommended that custom HTTP headers be named with the X- prefix to emphasize that this is a non-standard HTTP header. However, this recommendation was deprecated in June 2012, and RFC 6648 now specifies that creators of new header parameters SHOULD NOT prefix their parameter names with “X-” or similar prefixes.
-H "Accept: application/json"
Can I send cURL headers with HTTP POST request?
Yes, you can send any number of additional HTTP headers with a POST request. For example, when sending JSON to the server, you can specify the data type in the request body using the Content-Type: application/json header, and tell the server that the cURL client is expecting JSON using Accept: application/json". If you do not pass these additional headers with cURL POST request, the server may misinterpret the request data or return a response in a different format.
Can I only get HTTP headers using cURL?
Yes, the -I or --head cURL command-line option allows you to fetch HTTP headers only from the server by sending a HEAD request. The HTTP HEAD request method is identical to the GET method, except that the server does not return the HTTP message body.
curl -I https://reqbin.com/echo
Custom cURL Headers Example
An example of sending JSON data to a server with additional Accept and Content-Type HTTP headers.