0
0
PHPprogramming~5 mins

$_SERVER information in PHP

Choose your learning style9 modes available
Introduction

The $_SERVER variable holds information about headers, paths, and script locations. It helps you learn about the current request and server environment.

To find out the user's IP address visiting your website.
To get the current page URL or script name.
To check which browser or device the visitor is using.
To know the server software or version running your site.
To handle redirects or links based on the current domain.
Syntax
PHP
$_SERVER['KEY_NAME'];

Replace KEY_NAME with the specific information you want, like REMOTE_ADDR for IP address.

$_SERVER is a superglobal array, so you can access it anywhere in your PHP script.

Examples
Prints the visitor's IP address.
PHP
echo $_SERVER['REMOTE_ADDR'];
Shows the browser or device details of the visitor.
PHP
echo $_SERVER['HTTP_USER_AGENT'];
Displays the path of the current script.
PHP
echo $_SERVER['SCRIPT_NAME'];
Sample Program

This program prints the visitor's IP, the current script path, and browser details using $_SERVER.

PHP
<?php
// Show some server info
echo "Your IP address is: " . $_SERVER['REMOTE_ADDR'] . "\n";
echo "You are visiting: " . $_SERVER['SCRIPT_NAME'] . "\n";
echo "Your browser info: " . $_SERVER['HTTP_USER_AGENT'] . "\n";
?>
OutputSuccess
Important Notes

Some $_SERVER keys may not be available depending on the server or request type.

Never trust $_SERVER data blindly; it can be spoofed by users.

Summary

$_SERVER holds useful info about the visitor and server.

You access it like an array with keys for different details.

It helps customize responses based on who visits and how.