HomePHPWhat are superglobals in PHP? List some examples.

What are superglobals in PHP? List some examples.

In PHP, superglobals are built-in variables that are always accessible, regardless of scope—meaning you can access them inside functions, classes, or even without explicitly declaring them as global. They are automatically available in all parts of your script.

Superglobals are mainly used to access data from forms, sessions, server information, cookies, etc.

Here’s a list of some commonly used superglobals:

SuperglobalPurpose
$_GETRetrieves data sent via the URL (query string) using the GET method.
$_POSTRetrieves data sent via a form using the POST method.
$_REQUESTRetrieves data sent via GET, POST, or COOKIE.
$_SESSIONStores and retrieves session variables.
$_COOKIEStores and retrieves cookie data.
$_SERVERContains server and execution environment information (like headers, paths, and script locations).
$_FILESRetrieves information about uploaded files via forms.
$_ENVRetrieves environment variables.
$_GLOBALSReferences all global variables available in the script.

Example usage:

// Using $_GET
echo "Hello, " . $_GET['name'];

// Using $_POST
echo "Your email is " . $_POST['email'];

// Using $_SESSION
session_start();
$_SESSION['user'] = 'Himanshu';
echo $_SESSION['user'];

// Using $_SERVER
echo $_SERVER['HTTP_USER_AGENT'];

Superglobals are always available, but you need to start a session (session_start()) before using $_SESSION.

Share: 

No comments yet! You be the first to comment.

Leave a Reply

Your email address will not be published. Required fields are marked *