soraraso42 / learning-journal

0 stars 0 forks source link

superglobal arrays and associative arrays in php #44

Open soraraso42 opened 1 month ago

soraraso42 commented 1 month ago

overview of superglobals

In PHP, $_GET, $_POST, and $_REQUEST aren't exactly verbs or actions; they are superglobal arrays that store data sent to the server from the client. They represent different methods of sending data in HTTP requests:

These arrays themselves don't perform actions but store and allow access to the data from the client.


To Summarize:

Yes, superglobal arrays like $_GET, $_POST, $_REQUEST, $_FILES, and others are predefined by PHP and automatically generated at runtime. They are part of PHP's core functionality and are available in every script without needing to declare or initialize them. This feature is built into PHP’s environment, so they are bootstrapped and ready to use once the PHP interpreter starts processing a request.

How Superglobals Work:

  1. Automatically Available: Superglobals are automatically populated when a PHP script is run. The data in these arrays comes from different sources such as user input (forms, URLs), server settings, cookies, and file uploads.

  2. Request Lifecycle: When a client (usually a web browser) makes a request to a PHP server (via GET, POST, etc.), PHP processes the request and creates the relevant superglobal arrays based on the data sent by the client.

    For example:

    • When a user sends data through a form (POST method), PHP creates and fills the $_POST array with the form data.
    • When a file is uploaded, PHP fills the $_FILES array with information about the uploaded file.
  3. Bootstrapped in Every Script: These arrays are part of the PHP runtime environment. You don't need to define or generate them yourself—they are automatically available in every script, no matter the scope (even inside functions or classes).

Example of How PHP Generates Superglobals:

$_GET Superglobal:

$_POST Superglobal:

$_FILES Superglobal:

Predefined Superglobals in PHP:

Here’s a list of the most common predefined superglobals:

How PHP Bootstraps These Arrays:

  1. During Request Handling: When a client sends a request (GET, POST, etc.), PHP automatically extracts relevant data from the request (like query parameters, form data, and file uploads).

  2. Populates Arrays: PHP then creates and fills these superglobal arrays with the extracted data before executing the script.

  3. Global Availability: Since these arrays are global in scope, they can be accessed directly in any part of your script (whether inside a function, class, or any other scope).

Are They Initialized by the User?

No, you do not need to initialize or define these arrays. PHP handles everything under the hood. They are always available for you to use as soon as a script starts executing.

Why Are Superglobals Useful?

Superglobals save you the hassle of manually handling input from different sources. They provide a convenient and reliable way to access data across your PHP applications with minimal effort.

Superglobal arrays like $_GET, $_POST, $_FILES, and others in PHP are implemented as associative arrays. An associative array is a collection of key-value pairs, where each key is associated with a specific value. In PHP, these superglobals map incoming data (e.g., form submissions, query parameters) to specific keys.

Here are simple examples of the underlying data structure for various superglobal arrays:

1. $_GET Superglobal

When you send data via URL query parameters (e.g., example.com/?name=John&age=30), PHP generates the $_GET array.

Example:

URL: example.com/?name=John&age=30

$_GET = [
    'name' => 'John',
    'age'  => '30'
];

2. $_POST Superglobal

When data is submitted via a form using the POST method, PHP generates the $_POST array.

Example:

HTML Form:

<form method="POST" action="submit.php">
    <input type="text" name="username" value="JaneDoe">
    <input type="email" name="email" value="jane@example.com">
    <input type="submit">
</form>

PHP Code (submit.php):

$_POST = [
    'username' => 'JaneDoe',
    'email'    => 'jane@example.com'
];

3. $_FILES Superglobal

The $_FILES array contains data about files uploaded via an HTML form.

Example:

HTML Form:

<form method="POST" action="upload.php" enctype="multipart/form-data">
    <input type="file" name="profile_picture">
    <input type="submit">
</form>

PHP Code (upload.php):

$_FILES = [
    'profile_picture' => [
        'name'     => 'profile.jpg',
        'type'     => 'image/jpeg',
        'tmp_name' => '/tmp/phpYzdqkD',
        'error'    => 0,
        'size'     => 123456
    ]
];

4. $_REQUEST Superglobal

$_REQUEST is a merged array that includes data from $_GET, $_POST, and $_COOKIE. It’s useful when you want to capture data from any of these sources.

Example:

URL: example.com/?name=John

HTML Form:

<form method="POST" action="submit.php">
    <input type="text" name="email" value="jane@example.com">
    <input type="submit">
</form>

PHP Code (submit.php):

$_GET = [
    'name' => 'John'
];

$_POST = [
    'email' => 'jane@example.com'
];

$_REQUEST = [
    'name'  => 'John',
    'email' => 'jane@example.com'
];

5. $_SERVER Superglobal

The $_SERVER array contains server and execution environment information. It’s filled automatically by PHP and provides details about the server, request, and script execution.

Example:

$_SERVER = [
    'SERVER_NAME' => 'example.com',
    'REQUEST_METHOD' => 'POST',
    'SCRIPT_FILENAME' => '/var/www/html/submit.php',
    'HTTP_USER_AGENT' => 'Mozilla/5.0',
    'REMOTE_ADDR' => '192.168.1.1',
];

Underlying Data Structure

The underlying data structure for these superglobal arrays is associative arrays. PHP uses keys to store specific pieces of information, and you can access the data by referencing those keys.

Here's a conceptual diagram for $_FILES:

$_FILES
 └── 'profile_picture' 
      ├── 'name'     => 'profile.jpg'
      ├── 'type'     => 'image/jpeg'
      ├── 'tmp_name' => '/tmp/phpYzdqkD'
      ├── 'error'    => 0
      └── 'size'     => 123456

This structure helps PHP efficiently organize and access incoming data based on the request type (GET, POST, file uploads, etc.).

In summary:

soraraso42 commented 1 month ago

How PHP process multiple choice form input

When a form contains multiple checkboxes, the $_POST superglobal in PHP captures the selected values as an array under the corresponding checkbox name. This allows you to handle multiple checkbox choices easily.

How it Works

In the HTML form, you can use the same name attribute with square brackets ([]) to indicate that multiple values should be collected and sent as an array. When the form is submitted, $_POST will contain the checkbox values in an array format.

Example of a Form with Multiple Checkboxes

HTML Form:

<form method="POST" action="process.php">
    <label>
        <input type="checkbox" name="hobbies[]" value="Reading"> Reading
    </label><br>
    <label>
        <input type="checkbox" name="hobbies[]" value="Traveling"> Traveling
    </label><br>
    <label>
        <input type="checkbox" name="hobbies[]" value="Cooking"> Cooking
    </label><br>
    <label>
        <input type="checkbox" name="hobbies[]" value="Gardening"> Gardening
    </label><br>
    <input type="submit" value="Submit">
</form>

In this example, the name="hobbies[]" attribute with square brackets indicates that the form will submit the selected checkbox values as an array.

When the Form is Submitted

If the user selects "Reading" and "Cooking", the $_POST['hobbies'] array will look like this:

$_POST = [
    'hobbies' => [
        0 => 'Reading',
        1 => 'Cooking'
    ]
];

PHP Code to Process the Checkbox Values

You can loop through the $_POST['hobbies'] array to access the selected values.

process.php:

if (isset($_POST['hobbies'])) {
    $selected_hobbies = $_POST['hobbies'];

    foreach ($selected_hobbies as $hobby) {
        echo "You selected: " . htmlspecialchars($hobby) . "<br>";
    }
} else {
    echo "No hobbies selected.";
}

Explanation:

  1. isset($_POST['hobbies']): Checks if the hobbies field exists in the $_POST array (i.e., if any checkboxes were selected).
  2. $_POST['hobbies']: Contains the array of selected values.
  3. foreach loop: Iterates through the array to print the selected hobbies.
  4. htmlspecialchars(): Sanitizes the output to avoid XSS attacks by converting special characters like < and > into HTML entities.

If No Checkboxes Are Selected

If the user submits the form without selecting any checkboxes, $_POST['hobbies'] will not exist. Therefore, you should check for its presence using isset() before processing it, as shown above.

Data Structure

Here’s what the $_POST array might look like if multiple checkboxes are selected:

$_POST = [
    'hobbies' => [
        0 => 'Reading',
        1 => 'Cooking',
        2 => 'Gardening'
    ]
];

This associative array contains:

This structure allows PHP to handle multiple checkbox inputs seamlessly, giving you access to all selected values for further processing.