How can the code provided be improved to ensure that all uploaded files are deleted if the wrong file format is detected during the upload process?
To ensure that all uploaded files are deleted if the wrong file format is detected during the upload process, we can modify the code to delete the uploaded file if it does not match the allowed file formats. This can be achieved by adding a condition to check the file format before moving it to the upload directory. If the file format is incorrect, we can delete the file before exiting the script.
<?php
$allowed_formats = ['jpg', 'png', 'gif'];
$upload_dir = 'uploads/';
if(isset($_FILES['file'])) {
$file_name = $_FILES['file']['name'];
$file_ext = pathinfo($file_name, PATHINFO_EXTENSION);
if(in_array($file_ext, $allowed_formats)) {
move_uploaded_file($_FILES['file']['tmp_name'], $upload_dir . $file_name);
echo "File uploaded successfully!";
} else {
unlink($_FILES['file']['tmp_name']);
echo "Invalid file format. File deleted.";
}
}
?>