When a user submits a form, the data is sent to the specified PHP file, where it can be accessed using PHP superglobals like $_POST or $_GET.
Processing Form Data with $_POST
Using the example form above, we can retrieve the submitted data in process_form.php:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST['name'];
$email = $_POST['email'];
echo "Name: " . htmlspecialchars($name) . "<br>";
echo "Email: " . htmlspecialchars($email) . "<br>";
}
?>
In this example:
- $_POST[‘name’] and $_POST[’email’] retrieve the submitted data.
- htmlspecialchars() sanitizes the output, preventing potential XSS attacks.
File Upload Using Forms
To upload files, set the form’s enctype attribute to multipart/form-data.
<!DOCTYPE html>
<html>
<body>
<h2>File Upload Form</h2>
<form action="upload_file.php" method="POST" enctype="multipart/form-data">
Select file: <input type="file" name="fileToUpload"><br><br>
<input type="submit" value="Upload File">
</form>
</body>
</html>
Processing File Uploads in PHP
In upload_file.php, PHP can handle the uploaded file with $_FILES.
<?php
$targetDir = "uploads/";
$targetFile = $targetDir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
// Check if file already exists
if (file_exists($targetFile)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size (example limit: 500KB)
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// If all checks are okay, try to upload the file
if ($uploadOk == 1) {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $targetFile)) {
echo "The file " . htmlspecialchars(basename($_FILES["fileToUpload"]["name"])) . " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
In this example:
- $_FILES[“fileToUpload”][“tmp_name”] is the temporary filename of the file.
- move_uploaded_file() moves the uploaded file to a permanent location.
- Checks are performed for file existence and file size.