Are there any best practices or guidelines for handling file uploads in PHP forms?

When handling file uploads in PHP forms, it is important to validate the file type and size to prevent security vulnerabilities such as uploading malicious files or exceeding server limits. It is also recommended to store uploaded files in a secure directory outside of the web root to prevent direct access by users.

<?php
// Check if file was uploaded without errors
if(isset($_FILES['file']) && $_FILES['file']['error'] == 0){
    // Validate file type
    $allowed_types = array('jpg', 'jpeg', 'png', 'gif');
    $file_ext = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
    if(!in_array($file_ext, $allowed_types)){
        echo 'Invalid file type. Only JPG, JPEG, PNG, GIF files are allowed.';
    } else {
        // Validate file size
        if($_FILES['file']['size'] > 5242880){ // 5MB
            echo 'File is too large. Maximum file size allowed is 5MB.';
        } else {
            // Move uploaded file to secure directory
            $upload_dir = 'uploads/';
            $upload_file = $upload_dir . basename($_FILES['file']['name']);
            move_uploaded_file($_FILES['file']['tmp_name'], $upload_file);
            echo 'File uploaded successfully.';
        }
    }
} else {
    echo 'Error uploading file.';
}
?>