What are some best practices for handling file uploads in PHP to avoid errors and ensure successful uploads?
When handling file uploads in PHP, it is important to set the appropriate configuration options, validate the file type and size, and move the uploaded file to a secure location. To avoid errors and ensure successful uploads, use the move_uploaded_file() function to move the uploaded file to a designated directory after validating it.
// Check if file was uploaded without errors
if(isset($_FILES['file']) && $_FILES['file']['error'] == 0){
$targetDir = 'uploads/';
$targetFile = $targetDir . basename($_FILES['file']['name']);
// Validate file type
$fileType = pathinfo($targetFile, PATHINFO_EXTENSION);
if(in_array($fileType, ['jpg', 'jpeg', 'png', 'pdf'])){
// Move the uploaded file to the designated directory
if(move_uploaded_file($_FILES['file']['tmp_name'], $targetFile)){
echo "File uploaded successfully.";
} else {
echo "Error uploading file.";
}
} else {
echo "Invalid file type. Allowed file types: jpg, jpeg, png, pdf";
}
} else {
echo "Error uploading file.";
}