How to limit file uploads to a specific file type (e.g., image, PDF) in PHP?

To limit file uploads to a specific file type in PHP, you can use the following steps:

  1. Add a file input field in your HTML form:
<form action="upload.php" method="POST" enctype="multipart/form-data"> <input type="file" name="fileUpload"> <input type="submit" value="Upload"> </form>
  1. Create a PHP script (e.g., upload.php) to handle the file upload:
<?php $allowedFileTypes = ['image/jpeg', 'image/png', 'application/pdf']; // Allowed file types if ($_FILES['fileUpload']['size'] > 0) { $tempFile = $_FILES['fileUpload']['tmp_name']; $fileType = $_FILES['fileUpload']['type']; if (in_array($fileType, $allowedFileTypes)) { $uploadDir = 'uploads/'; // Directory to store uploaded files $uploadFile = $uploadDir . basename($_FILES['fileUpload']['name']); if (move_uploaded_file($tempFile, $uploadFile)) { echo 'File uploaded successfully.'; } else { echo 'Error uploading file.'; } } else { echo 'Invalid file type. Only JPEG, PNG, and PDF files are allowed.'; } } else { echo 'No file selected.'; } ?>
  1. In the PHP script, check if a file is selected and its size is greater than 0.
  2. Get the temporary file name and file type using $_FILES['fileUpload']['tmp_name'] and $_FILES['fileUpload']['type'].
  3. Check if the file type is present in the $allowedFileTypes array using in_array() function.
  4. If the file type is allowed, specify the directory where you want to upload the files ($uploadDir).
  5. Move the uploaded file from the temporary location to the desired directory using move_uploaded_file() function.
  6. Display appropriate success or error messages based on the file upload result.

Note: Make sure the directory where you want to upload files has the necessary write permissions so that PHP can move the files to that directory.