Superglobal arrays

 Superglobal arrays

In PHP, superglobal arrays are special arrays that are built-in and are always accessible, regardless of the scope of your code. They are automatically populated by PHP and provide essential information about the server, client, and the environment. Here are the most commonly used superglobal arrays in PHP:


1. `$_GLOBALS`: An associative array containing all global variables. It can be used to access variables defined in the global scope, similar to the `$GLOBALS` variable I mentioned in the previous section.


   ```php

   $x = 10;

   function test() {

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

   }

   test();

   ```


2. `$_SERVER`: An associative array containing information about the server environment and the current request. It provides details such as headers, paths, and script locations.


   ```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, usually from HTML forms.


   ```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)

   ```


These superglobal arrays can be accessed and manipulated throughout your PHP script, making them essential for web development tasks.


Comments

Popular posts from this blog

Programming in PHP