What are some best practices for implementing an upload script in PHP?

When implementing an upload script in PHP, it is important to validate the file type and size to prevent security risks and ensure smooth functionality. Additionally, consider storing uploaded files in a secure directory outside of the web root to prevent direct access. Lastly, provide clear error messages to users in case of upload failures.

<?php
// Check if the file was uploaded without errors
if ($_FILES['file']['error'] == UPLOAD_ERR_OK) {
    // Validate file type
    $allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
    if (!in_array($_FILES['file']['type'], $allowedTypes)) {
        die('Invalid file type. Allowed types: jpeg, png, gif');
    }

    // Validate file size
    $maxFileSize = 5 * 1024 * 1024; // 5MB
    if ($_FILES['file']['size'] > $maxFileSize) {
        die('File is too large. Max file size is 5MB');
    }

    // Move the uploaded file to a secure directory
    $uploadDir = 'uploads/';
    $uploadFile = $uploadDir . basename($_FILES['file']['name']);
    
    if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadFile)) {
        echo 'File uploaded successfully';
    } else {
        echo 'Upload failed';
    }
} else {
    echo 'Error uploading file';
}
?>