What are some best practices for handling file uploads in PHP to ensure security and proper functionality?

When handling file uploads in PHP, it is important to validate the file type, size, and content to prevent malicious files from being uploaded. Additionally, it is crucial to store uploaded files outside of the web root directory to prevent direct access. To enhance security, consider using unique file names and implementing file upload limits.

// Check if the file has been uploaded
if(isset($_FILES['file'])){
    $file = $_FILES['file'];
    
    // Validate file type
    $allowedTypes = ['image/jpeg', 'image/png'];
    if(!in_array($file['type'], $allowedTypes)){
        die('Invalid file type');
    }
    
    // Validate file size
    if($file['size'] > 5242880){ // 5MB
        die('File is too large');
    }
    
    // Move the uploaded file to a secure directory
    $uploadDir = 'uploads/';
    $uploadFile = $uploadDir . basename($file['name']);
    if(move_uploaded_file($file['tmp_name'], $uploadFile)){
        echo 'File uploaded successfully';
    } else {
        echo 'Error uploading file';
    }
}