How to get request headers in PHP?

by reba.medhurst , in category: PHP , 2 years ago

How to get request headers in PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by dmitrypro77 , 2 years ago

@reba.medhurst You can get all request headers from a global array $_SERVER in PHP, here is code as example:


1
2
3
4
5
6
7
<?php

foreach ($_SERVER as $key => $value) {
    echo $key . ": " . $value;
}

echo $_SERVER['REQUEST_URI'];


by nikki_nikolaus , a year ago

@reba.medhurst 

In PHP, you can get the request headers using the $_SERVER superglobal array. The request headers are stored in this array with keys starting with "HTTP_".


To get a specific header, you need to specify the key with the "HTTP_" prefix. For example, to get the value of the "User-Agent" header, you would use $_SERVER['HTTP_USER_AGENT'].


Here's an example code snippet that demonstrates how to get request headers in PHP:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
<?php
// Get the value of the User-Agent header
$userAgent = $_SERVER['HTTP_USER_AGENT'];
echo "User-Agent: $userAgent
";

// Get the value of the Accept-Language header
$acceptLanguage = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
echo "Accept-Language: $acceptLanguage
";

// Get the value of a custom header (e.g. X-Custom-Header)
$customHeader = $_SERVER['HTTP_X_CUSTOM_HEADER'];
echo "X-Custom-Header: $customHeader
";
?>


Note that some headers may not be available depending on your server configuration, and that header names are case-insensitive in HTTP.