PHP Superglobals & Forms Handling:- $_SERVER, $_SESSION, $_COOKIE, $_FILES
PHP is a widely used server-side scripting language that is specially designed for web development. It can be embedded into HTML.
What are Superglobals in PHP?
Superglobals are built-in variables that are always available in all scopes. This means that they can be accessed from any function, class, or file without any special declaration.
There are several Superglobals available in PHP, but we’ll focus on four key ones related to forms and server interactions:
$_SERVER
: This superglobal holds information about the server and the execution environment.$_SESSION
: This superglobal is used to store information about user sessions.$_COOKIE
: This superglobal is used to store and retrieve cookies.$_FILES
: This superglobal is used to handle uploaded files.
Let’s dive into each of them.
$_SERVER
The $_SERVER
superglobal array contains information created by the web server. It’s a treasure trove of data about the current request, headers, and script locations.
Common uses:
$_SERVER['PHP_SELF']
: Returns the filename of the currently executing script. Useful for directing form submissions back to the same page.$_SERVER['REQUEST_METHOD']
: Returns the request method used to access the page (e.g.,GET
,POST
). Essential for processing form data correctly.$_SERVER['HTTP_USER_AGENT']
: Provides information about the user’s browser.$_SERVER['REMOTE_ADDR']
: The IP address from which the user is viewing the current page.
Example:
PHP
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Process form data
echo "Form submitted using POST method.";
} else {
echo "This page was accessed using the " . $_SERVER['REQUEST_METHOD'] . " method.";
}
echo "<br>Your browser: " . $_SERVER['HTTP_USER_AGENT'];
?>
$_SESSION
Sessions provide a way to store information about a user across multiple page requests. Unlike cookies, session data is stored on the server, making it more secure for sensitive information.
Key concepts:
- To start a session, you must call
session_start()
at the beginning of your script. - Session variables are stored as key-value pairs in the
$_SESSION
superglobal. - Session data persists until the user closes their browser or the session expires.
Example:
PHP
<?php
session_start(); // Always start the session at the beginning
if (isset($_SESSION['username'])) {
echo "Welcome back, " . $_SESSION['username'] . "!";
} else {
$_SESSION['username'] = "Guest";
echo "Hello, " . $_SESSION['username'] . "! This is your first visit.";
}
// You can store more data
$_SESSION['fav_color'] = "blue";
// To destroy a session
// session_unset(); // Unset all session variables
// session_destroy(); // Destroy the session
?>
$_COOKIE
Cookies are small text files stored on the client’s (user’s) browser by the website. They are commonly used to remember user preferences, login status, or tracking information.
Key concepts:
- You set a cookie using the
setcookie()
function. - Cookies can have an expiration time, path, and domain.
- Cookies are sent with every HTTP request, so they can be accessed via the
$_COOKIE
superglobal.
Example:
PHP
<?php
$cookie_name = "user";
$cookie_value = "John Doe";
$expiration_time = time() + (86400 * 30); // 30 days
setcookie($cookie_name, $cookie_value, $expiration_time, "/"); // Set cookie for 30 days
if (isset($_COOKIE[$cookie_name])) {
echo "Welcome back, " . $_COOKIE[$cookie_name] . "!";
} else {
echo "Welcome, new user!";
}
// To delete a cookie, set its expiration time to a past date
// setcookie($cookie_name, "", time() - 3600);
?>
$_FILES
The $_FILES
superglobal is your go-to for handling file uploads through HTML forms. When a form with enctype="multipart/form-data"
is submitted, information about the uploaded files is populated in this array.
Key components of $_FILES
for an uploaded file:
$_FILES['input_name']['name']
: The original filename on the client machine.$_FILES['input_name']['type']
: The MIME type of the file.$_FILES['input_name']['tmp_name']
: The temporary filename of the file in which the uploaded file was stored on the server.$_FILES['input_name']['error']
: The error code associated with this file upload.$_FILES['input_name']['size']
: The size of the uploaded file in bytes.
Example (HTML form):
HTML
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
Example (upload.php):
PHP
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size (e.g., limit to 500KB)
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". htmlspecialchars( basename( $_FILES["fileToUpload"]["name"])). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
Conclusion
Understanding PHP superglobals like $_SERVER
, $_SESSION
, $_COOKIE
, and $_FILES
is fundamental to building dynamic and interactive web applications. They provide the necessary tools to handle user input, maintain state, manage user preferences, and process file uploads efficiently and securely. Mastering these superglobals will significantly enhance your PHP web development skills.