Server variables in php with syntax and examples

Server variables in PHP provide information about the server environment, request headers, and other relevant data. These variables are stored in the $_SERVER superglobal array.

Syntax:

$_SERVER['variable_name']


Examples:

1. $_SERVER['HTTP_HOST']: Returns the hostname of the server.

Example:

echo $_SERVER['HTTP_HOST']; // outputs "(link unavailable)"


1. $_SERVER['REQUEST_METHOD']: Returns the request method (GET, POST, PUT, DELETE, etc.).

Example:

echo $_SERVER['REQUEST_METHOD']; // outputs "GET"


1. $_SERVER['REQUEST_URI']: Returns the URI of the current request.

Example:

echo $_SERVER['REQUEST_URI']; // outputs "/path/to/resource"


1. $_SERVER['QUERY_STRING']: Returns the query string of the current request.

Example:

echo $_SERVER['QUERY_STRING']; // outputs "param1=value1&param2=value2"


1. $_SERVER['HTTP_REFERER']: Returns the referrer URL of the current request.

Example:

echo $_SERVER['HTTP_REFERER']; // outputs "(link unavailable)"


1. $_SERVER['HTTP_USER_AGENT']: Returns the user agent string of the client.

Example:

echo $_SERVER['HTTP_USER_AGENT']; // outputs "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3"


1. $_SERVER['REMOTE_ADDR']: Returns the IP address of the client.

Example:

echo $_SERVER['REMOTE_ADDR']; // outputs "192.168.1.100"


1. $_SERVER['SERVER_NAME']: Returns the name of the server.

Example:

echo $_SERVER['SERVER_NAME']; // outputs "(link unavailable)"


1. $_SERVER['SERVER_PORT']: Returns the port number of the server.

Example:

echo $_SERVER['SERVER_PORT']; // outputs "80"


1. $_SERVER['SCRIPT_NAME']: Returns the name of the current script.

Example:

echo $_SERVER['SCRIPT_NAME']; // outputs "/path/to/script.php"


Best Practices:

1. Use server variables to access server environment and request data.
2. Validate and sanitize user input data.
3. Use isset() to check if a variable is set before accessing it.
4. Use empty() to check if a variable is empty before accessing it.
5. Avoid using $_SERVER variables for sensitive data storage.

By understanding server variables in PHP, you can access valuable information about the server environment and request data, enabling you to create more dynamic and secure applications.

Leave a Reply

Shopping cart0
There are no products in the cart!
Continue shopping
0