What are some best practices for handling file uploads in PHP to ensure smooth functionality and prevent errors?

When handling file uploads in PHP, it is important to ensure that the server has appropriate settings configured for file uploads and that the uploaded file is processed securely to prevent any vulnerabilities. One common best practice is to validate the file type and size before allowing the upload to proceed. Additionally, it is recommended to store uploaded files in a secure directory outside of the web root to prevent direct access.

<?php
// Check if the file was uploaded without errors
if(isset($_FILES['file']) && $_FILES['file']['error'] == UPLOAD_ERR_OK) {
    $uploadDir = 'uploads/';
    $uploadFile = $uploadDir . basename($_FILES['file']['name']);

    // Validate file type and size
    $allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
    $maxSize = 5 * 1024 * 1024; // 5MB

    if(in_array($_FILES['file']['type'], $allowedTypes) && $_FILES['file']['size'] <= $maxSize) {
        // Move the uploaded file to a secure directory
        if(move_uploaded_file($_FILES['file']['tmp_name'], $uploadFile)) {
            echo 'File uploaded successfully.';
        } else {
            echo 'Failed to upload file.';
        }
    } else {
        echo 'Invalid file type or size.';
    }
} else {
    echo 'Error uploading file.';
}
?>