Welcome to this comprehensive guide on PHP File Extension Check! In this tutorial, we'll learn how to control the types of files that can be uploaded to your PHP website, making it more secure and reliable.
File extension check in PHP is a process of ensuring that only specific file types are allowed to be uploaded to your server. This is crucial to prevent potential security issues, such as malicious code injection, from unauthorized file types.
Before diving into the code, let's set up a simple HTML form for file upload:
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>In this example, our form submits the file to upload.php.
Now, let's create the upload.php file to check the file extension and handle the upload process.
<?php
$allowedExtensions = array("jpg", "jpeg", "png", "gif");
$temp = explode(".", $_FILES["fileToUpload"]["name"]);
$fileExtension = strtolower(end($temp));
if (in_array($fileExtension, $allowedExtensions)) {
if ($_FILES["fileToUpload"]["size"] <= 1000000) {
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], "uploads/" . $_FILES["fileToUpload"]["name"]);
echo "File uploaded successfully.";
} else {
echo "File size is too big.";
}
} else {
echo "Invalid file type.";
}
?>In this code:
$allowedExtensions containing the extensions we want to allow.explode function to separate the file name into parts based on the dot (.).end function.$allowedExtensions array.uploads folder.What is the purpose of the `$allowedExtensions` array in the PHP code?
$allowedExtensions array.In this lesson, we've learned how to check file extensions in PHP, which is a crucial step in securing your website from potential threats. Practice this code and feel free to customize it according to your project's needs. Happy coding! π