PHP Upload File Extension Check 🎯

beginner
10 min

PHP Upload File Extension Check 🎯

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.

What is File Extension Check in PHP? πŸ“

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.

Getting Started πŸ’‘

Before diving into the code, let's set up a simple HTML form for file upload:

html
<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.

Checking File Extension in PHP πŸ’‘

Now, let's create the upload.php file to check the file extension and handle the upload process.

php
<?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:

  1. We define an array $allowedExtensions containing the extensions we want to allow.
  2. We use the explode function to separate the file name into parts based on the dot (.).
  3. We extract the file extension using the end function.
  4. We check if the file extension is present in the $allowedExtensions array.
  5. If the file size is more than 1MB, we display an error message.
  6. If the file extension is allowed and size is within the limit, we move the uploaded file to the uploads folder.

Quiz πŸ’‘

Quick Quiz
Question 1 of 1

What is the purpose of the `$allowedExtensions` array in the PHP code?

Pro Tips πŸ’‘

  • To allow multiple file types, simply add the extensions to the $allowedExtensions array.
  • Always validate user input to prevent security risks.
  • Store uploaded files in a separate folder to keep your project organized.

Conclusion βœ…

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! πŸŽ‰