start learning
Image 1

Superglobals in PHP

In PHP, In PHP, superglobals are special global arrays that are accessible from anywhere in a script. They are predefined by the PHP language and provide information about various aspects of the server, the client's request, and the application's environment. Superglobals are often used to collect data from HTML forms, manage sessions, and access server-related information.

The primary PHP superglobals are as follows :

  1. $GLOBALS: This superglobal is used to access global variables from within a function or method. It's an associative array that contains all global variables.
  2. $_SERVER: This superglobal contains information about the server and the execution environment. It includes details such as server name, request method, query string, and more.
  3. $_GET: It is used to collect data from the query string (URL parameters) in a GET request. It is an associative array.
  4. $_POST: This superglobal is used to collect data sent via an HTTP POST request, typically from an HTML form. It is also an associative array.
  5. $_REQUEST: It is a combination of the $_GET and $_POST superglobals. It can be used to access data from both GET and POST requests, but you should be cautious with it to avoid security issues.
  6. $_SESSION: This superglobal is used for managing session variables. It allows you to store data that can persist across multiple page requests as long as the user's session is active.
  7. $_COOKIE: $_COOKIE contains all the HTTP cookies sent to the script. Cookies are often used to store small pieces of data on the client's side.
  8. $_FILES: When dealing with file uploads through HTML forms, you can use this superglobal to access information about the uploaded files and their properties.
  9. $_ENV: This superglobal provides access to environment variables that are set in the server's environment.

Superglobals are automatically populated by PHP, and you can access their values as you would with any other associative array. For example, to access a value in the $_POST superglobal, you can use $_POST['key'] to retrieve the data associated with the 'key' field in a POST request.

It's important to note that superglobals can be easily manipulated by user input, so they should be sanitized and validated to prevent security vulnerabilities, such as injection attacks and cross-site scripting (XSS).