In PHP, superglobals are special predefined variables that are available in all scopes throughout a PHP script. They are called “superglobals” because they can be accessed from any part of the script without the need to explicitly declare or import them.
There are several superglobal variables in PHP, each serving a specific purpose. Here are the most commonly used PHP superglobals:
- $_GET: This superglobal variable is an associative array that contains the values of variables passed to the current script via the URL parameters (i.e., the query string). For example, if the URL is
http://example.com/script.php?name=John&age=25, you can access the values of name and age using
- $_POST: It is also an associative array that holds the values of variables sent to the current script via an HTTP POST request. When you submit an HTML form with the method attribute set to “post,” the form data will be available through this superglobal. You can access the values using the corresponding form field names. For example,
- $_SERVER: This superglobal contains information about the server and the execution environment. It is an associative array that includes details such as request headers, script filenames, server addresses, and more. For example,
$_SERVER['REQUEST_METHOD']will contain the HTTP request method (e.g., GET, POST), and
$_SERVER['REMOTE_ADDR']will provide the IP address of the client.
- $_SESSION: It is an associative array that stores session data for the current user. Session data persists across multiple pages or requests within the same session. To use this superglobal, you need to start a session using the
session_start()function. Once the session is started, you can store and retrieve data from
- $_COOKIE: This superglobal holds the values of cookies sent by the client browser to the server. Cookies are small pieces of data stored on the client’s machine. In PHP, you can access the cookie values using
- $_FILES: When you upload files using an HTML form with the
enctypeattribute set to “multipart/form-data,” the uploaded files’ details will be available in this superglobal. It is an associative array containing information such as the file name, file type, temporary file location, etc.
These are the primary superglobals in PHP that provide a convenient way to access and manipulate data that is commonly used in web applications. Remember to handle superglobal data with caution and sanitize/validate it as necessary to prevent security vulnerabilities like SQL injection or cross-site scripting (XSS) attacks.