⚙️ | Predefined Variables
https://www.php.net/manual/en/reserved.variables.php
https://www.php.net/manual/en/language.variables.scope.php
In PHP, some predefined variables are available at all times and facilitate the management of interactions between the server, the client, and the execution environment. Among these variables, we find superglobals and other specific variables.
Superglobals
Superglobals are associative arrays that contain information related to the execution environment, HTTP requests, uploaded files, etc. They are accessible everywhere in the script, without the need to pass them as arguments.
$GLOBALS
Contains all global variables of the script.
$_SERVER
Information about the server and the environment (e.g., $_SERVER['HTTP_HOST']
for the host name).
$_GET
Contains data sent via an HTTP GET request (e.g., from a URL).
URL : http://example.com/page.php?name=toto&age=30
echo "Name: " . $_GET['name'];
echo "Age: " . $_GET['age'];
🖥️ Output
Name: toto
Age: 30
$_POST
Contains data sent via an HTTP POST request (e.g., from a form).
<form method="post" action="/process.php">
<input type="text" name="first_name" placeholder="Your first name">
<input type="submit" value="Send">
</form>
// Display the first name sent via the form
echo "First Name: " . $_POST['first_name'];
$_FILES
Contains files uploaded via a form.
<form action="/upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="my_file">
<input type="submit" value="Upload">
</form>
// No error
if ($_FILES['my_file']['error'] === UPLOAD_ERR_OK) {
$file_name = $_FILES['my_file']['name'];
$temporary_name = $_FILES['my_file']['tmp_name'];
move_uploaded_file($temporary_name, "uploads/$file_name");
}
// One or more errors
else {
echo "Error during upload.";
}
See the list of file upload errors.
$_COOKIE
Contains the cookies sent by the client.
setcookie('user', 'toto', time() + 3600);
if (isset($_COOKIE['user'])) {
echo 'User: ' . $_COOKIE['user'];
}
🖥️ Output
User: toto
$_SESSION
Sessions allow storing user information across different pages.
- session_start(): Must be called to initialize the session.
- session_destroy(): Used to destroy all session variables.
Example:
// Start the session
session_start();
// Store data in the session
$_SESSION['user'] = 'toto';
// Access the data
echo "User: " . $_SESSION['user'];
// Destroy the session
session_destroy();
🖥️ Output
User: toto
$_REQUEST
Combines data from $_GET
, $_POST
, and $_COOKIE
.
$_ENV
Contains server environment variables.
echo $_ENV['HOME'];
🖥️ Output
/home/toto
Other predefined variables
$argc
Contains the number of arguments passed to the script via the command line (similar to C).
$argv
Contains an array of arguments passed via the command line (similar to C).