In PHP, global variables refer to variables that are accessible from anywhere in the script, including inside functions, classes, and methods. PHP also provides a set of predefined global variables known as superglobals, which are accessible from any scope and contain information about the server, request, and environment. Here are some commonly used superglobals:
Contains information about the server and the current request.
Example:
echo $_SERVER['HTTP_HOST']; // Outputs the host name
echo $_SERVER['REQUEST_METHOD']; // Outputs the request method (GET, POST, etc.)
Contain data submitted to the script via GET and POST methods, respectively.
Example:
echo $_GET['param']; // Outputs the value of 'param' sent via GET
echo $_POST['param']; // Outputs the value of 'param' sent via POST
Stores session variables that are available to the current session.
Example:
session_start(); // Start the session
$_SESSION['user_id'] = 123;
// Assign value to session variable
echo $_SESSION['user_id']; // Outputs the value of session variable
Contains variables passed to the current script via HTTP Cookies.
Example:
echo $_COOKIE['cookie_name']; // Outputs the value of the cookie 'cookie_name'
Contains information about uploaded files via HTTP POST.
Example:
echo $_FILES['file']['name']; // Outputs the name of the uploaded file
Contains environment variables.
Example:
echo $_ENV['PATH']; // Outputs the value of the PATH environment variable
Contains data submitted to the script via HTTP request.
Example:
echo $_REQUEST['param']; // Outputs the value of 'param' sent via request (GET, POST, etc.)
These superglobals provide a convenient way to access various aspects of the PHP environment and the incoming request data. However, it's important to handle them carefully, especially when dealing with user input, to prevent security vulnerabilities like SQL injection and cross-site scripting (XSS).