What are some best practices for handling file uploads in PHP to ensure that all uploaded files are deleted if an error occurs during the upload process?
When handling file uploads in PHP, it is important to ensure that all uploaded files are deleted if an error occurs during the upload process to prevent unnecessary files from accumulating on the server. One way to achieve this is by using a try-catch block to catch any exceptions that may occur during the upload process and then deleting the uploaded file within the catch block.
try {
// Code to handle file upload
// Move uploaded file to desired location
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
} catch (Exception $e) {
// Delete uploaded file if an error occurs
unlink('uploads/' . $_FILES['file']['name']);
echo 'An error occurred during file upload: ' . $e->getMessage();
}