To limit file uploads to a specific file type in PHP, you can use the following steps:
<form action="upload.php" method="POST" enctype="multipart/form-data">
<input type="file" name="fileUpload">
<input type="submit" value="Upload">
</form>
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.';
}
?>
$_FILES['fileUpload']['tmp_name']
and $_FILES['fileUpload']['type']
.$allowedFileTypes
array using in_array()
function.$uploadDir
).move_uploaded_file()
function.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.