Welcome to this comprehensive tutorial on PHP File Upload Type Validation! In this lesson, we'll learn how to validate the file type while uploading files using PHP. This skill is crucial for ensuring the security and integrity of your web applications.
File Type Validation is a process to check if an uploaded file adheres to specific file type requirements, such as only allowing .jpg, .png, or .pdf files. This helps prevent unwanted scripts or malicious files from being uploaded to your server.
Before we dive in, make sure you have a basic understanding of PHP and HTML. If not, check out our PHP Tutorial for Beginners and HTML Tutorial first.
upload_file.php).<form action="upload_file.php" method="post" enctype="multipart/form-data">
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>Before we validate the file type, let's quickly review how to handle file uploads in PHP.
<?php
if(isset($_POST['submit'])){
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file);
}
?>Now, let's validate the file type!
To validate file types, we'll check the file extension against a list of allowed extensions. Here's how:
<?php
$allowedExts = array("jpg", "jpeg", "png", "gif", "pdf");
$extension = pathinfo($target_file, PATHINFO_EXTENSION);
if (!in_array($extension, $allowedExts)) {
echo "Invalid file type.";
exit();
}
?>Now, our script checks the file type before saving it to the server.
Let's expand on the previous example by adding a file size limit, too.
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$allowedExts = array("jpg", "jpeg", "png", "gif", "pdf");
$extension = pathinfo($target_file, PATHINFO_EXTENSION);
// Limit file size (5MB)
$maxSize = 5000000;
if ($_FILES["fileToUpload"]["size"] > $maxSize) {
echo "File exceeds maximum size.";
$uploadOk = 0;
}
// Validate file extension
if (!in_array($extension, $allowedExts)) {
echo "Invalid file type.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
} else {
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file);
echo "The file ". htmlspecialchars( basename( $_FILES["fileToUpload"]["name"])). " has been uploaded.";
}
?>What does `$uploadOk` represent in the practical example?
By now, you should have a good understanding of PHP File Upload Type Validation! Practicing and experimenting with the provided examples will help solidify your knowledge. Happy coding! π
Stay tuned for more PHP tutorials on CodeYourCraft! π