PHP Superglobals: GET, POST, REQUEST, FILES
PHP Superglobals are built-in variables that are always available in all scopes throughout a script. They provide useful information to PHP scripts about the web server environment, including data from HTML forms and other sources. Among the numerous superglobals in PHP, four particularly significant ones for handling user input and file uploads are $_GET
, $_POST
, $_REQUEST
, and $_FILES
. These superglobals play a crucial role in creating dynamic web applications by enabling interaction between the client (browser) and the server-side script.
1. $_GET
$_GET
is an associative array containing data submitted with URLs through the query_string
. Data is sent with a URL in the name=value
format, separated by ampersands (&
). It is primarily used for retrieving information passed via the query string of a URL. For example, if a user navigates to http://www.example.com/page.php?id=5
, the $_GET
array will look like this:
<?php
var_dump($_GET);
// Output:
// array(1) {
// ["id"] =>
// string(1) "5"
// }
?>
Advantages of $_GET:
- Bookmarkability: You can bookmark URLs with
$_GET
parameters. - Booklet-friendly: Useful when you want to print or share URLs with data.
- Idempotence: Operations performed with
$_GET
should not modify any data on the server.
Disadvantages of $_GET:
- Security Risks: Since
$_GET
data appears in the URL, it might be intercepted or tampered with. - Data Size Limitations: Most browsers and servers limit the size of URLs, so
$_GET
can only handle a small amount of data (around 2048 characters).
Use Cases:
- Pagination links within web applications.
- Filtering search results based on URL parameters.
- Passing non-sensitive data between pages.
Example Usage:
<!-- HTML Form -->
<form action="example.php" method="get">
Search: <input type="text" name="search_term">
<input type="submit" value="Search">
</form>
<!-- PHP Script (example.php) -->
<?php
if (isset($_GET['search_term'])) {
$searchTerm = htmlspecialchars(trim($_GET['search_term']));
// Perform search operation using $searchTerm
echo "You searched for: " . $searchTerm;
}
?>
2. $_POST
$_POST
is an associative array containing data submitted through an HTML form with the method
attribute set to "POST"
. It's suitable for handling larger amounts of data and more sensitive information as these details aren't visible in the URL.
Advantages of $_POST:
- Security: Unlike
$_GET
, data is not visible in the URL, making it more secure for sending sensitive data. - No Size Limitation: Typically, there are no size restrictions imposed by browsers or web servers (though actual limits may vary).
- Not Bookmarked: Data isn’t visible in the URL, preventing unauthorized access to data via bookmarks.
Disadvantages of $_POST:
- Non-Bookmarkability: URLs with
$_POST
data cannot be bookmarked. - Less Shareable: Not ideal for sharing data since it’s not part of the URL.
- Complexity for Debugging: Can be harder to debug since there’s no easy way to see the transmitted data.
Use Cases:
- Handling user login forms.
- Sending feedback or comments through a form.
- Uploading files.
Example Usage:
<!-- HTML Form -->
<form action="login.php" method="post">
Username: <input type="text" name="username">
Password: <input type="password" name="password">
<input type="submit" value="Login">
</form>
<!-- PHP Script (login.php) -->
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = htmlspecialchars(trim($_POST['username']));
$password = htmlspecialchars(trim($_POST['password']));
// Perform authentication using $username and $password
echo "Welcome, " . $username;
}
?>
3. $_REQUEST
The $_REQUEST
superglobal is a merged array of $_GET
, $_POST
, and $_COOKIE
variables. When a value is passed via $_GET
or $_POST
, it also appears in $_REQUEST
.
Example Usage:
<!-- HTML Form (can use either method) -->
<form action="example.php" method="post"> <!-- or method="get" -->
Name: <input type="text" name="user_name">
Age: <input type="number" name="user_age">
<input type="submit" value="Submit">
</form>
<!-- PHP Script (example.php) -->
<?php
if (isset($_REQUEST['user_name']) && isset($_REQUEST['user_age'])) {
$userName = htmlspecialchars(trim($_REQUEST['user_name']));
$userAge = htmlspecialchars(trim($_REQUEST['user_age']));
echo "Name: " . $userName . "<br>";
echo "Age: " . $userAge;
}
?>
Advantages of $_REQUEST:
- Convenience: Access GET, POST, and COOKIE data with a single variable.
Potential Disadvantages:
- Security Concerns: Merging data from different sources can pose security risks. If cookies and GET/POST variables share similar names, unintended behavior can occur.
- Performance Overhead: Processing this merged array might lead to unnecessary overhead compared to handling only
$_GET
or$_POST
.
Note: In many cases, $_REQUEST
is considered less secure and its usage is generally discouraged unless necessary for compatibility reasons.
4. $_FILES
$_FILES
is a special superglobal array used to handle files uploaded via an HTML form. When a file is uploaded, several pieces of information about the file are included in $_FILES
, such as the file name, temporary upload path, file size, MIME type, and error code.
Structure of $_FILES Array:
$_FILES['field_name']['name']
: The original name of the file before upload.$_FILES['field_name']['type']
: The MIME type of the file.$_FILES['field_name']['tmp_name']
: The temporary file name stored on the server during upload.$_FILES['field_name']['error']
: The error code associated with the file upload.$_FILES['field_name']['size']
: The size of the uploaded file in bytes.
Uploading Files:
To handle file uploads safely, you must configure your php.ini
file correctly and validate the file data before moving it to its permanent storage location.
Example Usage:
<!-- HTML Form -->
<form action="upload.php" method="post" enctype="multipart/form-data">
Upload File: <input type="file" name="uploaded_file">
<input type="submit" value="Upload">
</form>
<!-- PHP Script (upload.php) -->
<?php
$targetDir = "uploads/";
$targetFile = $targetDir . basename($_FILES["uploaded_file"]["name"]);
$uploadOk = 1;
// Check if image file is a actual image or fake image
$imageFileType = strtolower(pathinfo($targetFile, PATHINFO_EXTENSION));
if (isset($_POST["submit"])) {
$check = getimagesize($_FILES["uploaded_file"]["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($targetFile)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size (max 5MB)
if ($_FILES["uploaded_file"]["size"] > 5000000) {
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["uploaded_file"]["tmp_name"], $targetFile)) {
echo "The file ". htmlspecialchars( basename( $_FILES["uploaded_file"]["name"])). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
Important Considerations:
- Security: Always validate file data before uploading it. Check the file type, size, and ensure it passes security checks to prevent malicious file uploads.
- Configuration: Ensure
file_uploads
directive inphp.ini
is enabled. - Temporary Storage: PHP stores uploaded files temporarily in a server-specified directory before processing them. This location can be configured using the
upload_tmp_dir
directive. - Error Codes: Check the
$_FILES['field_name']['error']
value for proper file upload validation and error handling.
In summary, these PHP superglobals ($_GET
, $_POST
, $_REQUEST
, $_FILES
) form powerful tools for web development, enabling interactions between clients and server-side scripts. Proper understanding and utilization of these superglobals can greatly enhance your ability to build robust and secure web applications. However, always remember to handle client inputs carefully to avoid common pitfalls like SQL injection, XSS attacks, and improper file uploads.
Certainly! Understanding PHP superglobals like $_GET
, $_POST
, $_REQUEST
, and $_FILES
is crucial for handling user data effectively in web applications. Here’s a step-by-step guide to help beginners navigate these concepts.
Setting Up the Environment
- Install a Web Server: Make sure you have a local server environment installed on your computer. XAMPP, WAMP, or MAMP are popular options for this purpose.
- Create a Project Directory: Inside your server's root directory (e.g.,
htdocs
for XAMPP), create a folder namedphp_superglobals
. You’ll be working within this folder.
Examples and Implementation Steps
1. Using $_GET
$_GET
is used to collect form data after submitting an HTML form with method="get". Or it can also be used to collect data sent in the URL.
Step-by-Step Example:
- Create
get_example.php
:
<?php
if (isset($_GET['name'])) {
echo "Hello, " . htmlspecialchars($_GET['name']) . "!";
} else {
echo "Please enter your name.";
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>GET Method Example</title>
</head>
<body>
<form action="get_example.php" method="get">
Name: <input type="text" name="name">
<input type="submit">
</form>
</body>
</html>
- Explanation: This form uses
method="get"
to send data. After submission, the page reloads with the input data displayed in the URL.$_GET['name']
retrieves the 'name' parameter from the URL.
2. Using $_POST
$_POST
collects form data after submitting an HTML form with method="post".
Step-by-Step Example:
- Create
post_example.php
:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Collect and sanitize input data
$name = htmlspecialchars(trim($_POST['name']));
$email = htmlspecialchars(trim($_POST['email']));
// Display collected data
echo "Hello, " . $name . "! Your email address is: " . $email;
} else {
echo "Please fill out the form";
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>POST Method Example</title>
</head>
<body>
<form action="post_example.php" method="post">
Name: <input type="text" name="name"><br>
Email: <input type="email" name="email"><br>
<input type="submit">
</form>
</body>
</html>
- Explanation: Unlike
$_GET
, the data submitted usingPOST
will not appear in the URL. It is typically used for sensitive information. Here,$_POST['name']
and$_POST['email']
are used to retrieve the submitted values.
3. Using $_REQUEST
$_REQUEST
is used to collect data after submitting an HTML form. It retrieves data from $_GET
, $_POST
, and $_COOKIE
.
Step-by-Step Example:
- Modify
post_example.php
to use$_REQUEST
:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Collect and sanitize input data
$name = htmlspecialchars(trim($_REQUEST['name']));
$email = htmlspecialchars(trim($_REQUEST['email']));
// Display collected data
echo "Hello, " . $name . "! Your email address is: " . $email;
} else {
echo "Please fill out the form";
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>REQUEST Method Example</title>
</head>
<body>
<form action="post_example.php" method="post">
Name: <input type="text" name="name"><br>
Email: <input type="email" name="email"><br>
<input type="submit">
</form>
</body>
</html>
- Explanation:
$_REQUEST
gathers data from both$_POST
and$_GET
automatically. In this example, changing$_POST
to$_REQUEST
still yields the same result because data is being posted.
4. Using $_FILES
$_FILES
is commonly used to handle file uploads through an HTML form.
Step-by-Step Example:
- Create
file_upload.php
:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Check if file was uploaded without errors
if (isset($_FILES["fileToUpload"]) && $_FILES["fileToUpload"]["error"] == 0) {
$allowed = ["jpg" => "image/jpg", "jpeg" => "image/jpeg", "gif" => "image/gif", "png" => "image/png"];
$filename = $_FILES["fileToUpload"]["name"];
$filetype = $_FILES["fileToUpload"]["type"];
$filesize = $_FILES["fileToUpload"]["size"];
// Verify file extension
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if (!array_key_exists($ext, $allowed)) die("Error: Please select a valid file format.");
// Verify file size - 5MB maximum
$maxsize = 5 * 1024 * 1024;
if ($filesize > $maxsize) die("Error: File size is larger than the allowed limit.");
// Verify MIME type of the file
if (in_array($filetype, $allowed)) {
// Check whether file exists before uploading it
if (file_exists("upload/" . $filename)) {
echo $filename . " is already exists.";
} else {
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], "upload/" . $filename);
echo "Your file was uploaded successfully.";
}
} else {
echo "Error: There was a problem uploading your file. Please try again.";
}
} else {
echo "Error: " . $_FILES["fileToUpload"]["error"];
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>File Upload Example</title>
</head>
<body>
<h1>Upload Image File</h1>
<form action="file_upload.php" method="post" enctype="multipart/form-data">
<p>Select image to upload:</p>
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
- Explanation: Ensure you have an
upload/
directory in the same folder asfile_upload.php
where files will be saved. The$_FILES
array stores all the uploaded files. Various checks are performed for security purposes such as file type, size, and MIME type.
Data Flow
- Form Submission: The user fills out a form and clicks submit.
- Method Execution: Depending on the form method (
GET
,POST
), the data is sent to the server. - Data Handling: The corresponding PHP script processes the data using superglobals (
$_GET
,$_POST
,$_REQUEST
,$_FILES
). - Output: Depending on the processing logic, data may be displayed back to the user, stored in a database, used for further calculations, etc.
- File Handling (optional): If the form includes file uploads, the uploaded files are accessed via
$_FILES
and handled accordingly (like moving them to a specific folder).
Summary
Understanding and effectively using PHP superglobals ($_GET
, $_POST
, $_REQUEST
, and $_FILES
) enables developers to create interactive, responsive, and secure web applications that handle user inputs efficiently. By following these step-by-step examples, beginners can gain a solid foundation in handling different types of user data in PHP.
Feel free to experiment with these examples and modify them according to your needs to deepen your understanding of how these superglobals work. Happy coding!