Super global variables

 Super global variables

In PHP, superglobal variables are special predefined variables that are always accessible, regardless of scope. These variables are provided by the PHP language and are used to store different types of data. Super globals are often used in functions, classes, and scripts to access global data without having to declare them as global within the function or method.


Here are some commonly used superglobal variables in PHP:


1. `$_GLOBALS`: An associative array containing all global variables. It can be used to access variables defined in the global scope.


   ```php

   $x = 10;

   function test() {

       echo $GLOBALS['x']; // Output: 10

   }

   test();

   ```


2. `$_SERVER`: An array containing information about the server environment and the current request.


   ```php

   echo $_SERVER['PHP_SELF']; // Current script filename

   echo $_SERVER['SERVER_NAME']; // Server name

   ```


3. `$_GET`: An associative array containing data sent to the script via URL query parameters.


   ```php

   echo $_GET['parameter_name']; // Access query parameter value

   ```


4. `$_POST`: An associative array containing data sent to the script via HTTP POST method.


   ```php

   echo $_POST['input_field_name']; // Access form input value submitted via POST

   ```


5. `$_SESSION`: An associative array used to store session variables across multiple pages.


   ```php

   session_start(); // Start session

   $_SESSION['user_id'] = 1; // Set session variable

   ```


6. `$_COOKIE`: An associative array containing all cookies sent by the client's browser to the server.


   ```php

   echo $_COOKIE['cookie_name']; // Access cookie value

   ```


7. `$_FILES`: An associative array containing information about file uploads via HTTP POST.


   ```php

   echo $_FILES['file_input']['name']; // Access uploaded file name

   ```


8. `$_REQUEST`: An associative array containing data from `$_GET`, `$_POST`, and `$_COOKIE`. It is used to collect form data after submitting an HTML form.


   ```php

   echo $_REQUEST['input_name']; // Access form input value (from GET, POST, or COOKIE)

   ```


Remember that these variables are always accessible and can be used within functions, classes, or any part of the PHP script. However, it's important to validate and sanitize user input when using superglobals to prevent security vulnerabilities such as SQL injection and cross-site scripting (XSS) attacks.


Comments

Popular posts from this blog

Programming in PHP