What are the best practices for handling file uploads and checking file extensions in PHP?
When handling file uploads in PHP, it is important to validate file extensions to prevent malicious files from being uploaded to the server. One way to do this is by checking the file extension against a list of allowed extensions. This can help ensure that only safe file types are uploaded.
// Define an array of allowed file extensions
$allowedExtensions = array('jpg', 'jpeg', 'png', 'gif');
// Get the file extension of the uploaded file
$uploadedFileExtension = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
// Check if the file extension is in the list of allowed extensions
if (!in_array($uploadedFileExtension, $allowedExtensions)) {
// Invalid file extension, handle the error accordingly
echo 'Invalid file extension. Only JPG, JPEG, PNG, and GIF files are allowed.';
} else {
// File extension is valid, proceed with file upload
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
echo 'File uploaded successfully.';
}