What are the best practices for handling file uploads in PHP?

When handling file uploads in PHP, it is important to validate the file type, size, and ensure proper file permissions are set. Additionally, always use a secure file upload path to prevent malicious file uploads. Finally, sanitize the file name to prevent directory traversal attacks.

// Example code snippet for handling file uploads in PHP

// Check if file was uploaded without errors
if ($_FILES['file']['error'] == UPLOAD_ERR_OK) {
    // Validate file type
    $allowed_types = array('image/jpeg', 'image/png');
    if (in_array($_FILES['file']['type'], $allowed_types)) {
        // Validate file size
        if ($_FILES['file']['size'] <= 5000000) {
            // Set upload path
            $upload_path = 'uploads/';
            // Sanitize file name
            $file_name = basename($_FILES['file']['name']);
            $file_path = $upload_path . $file_name;
            // Move uploaded file to upload path
            move_uploaded_file($_FILES['file']['tmp_name'], $file_path);
            echo "File uploaded successfully.";
        } else {
            echo "File size exceeds limit.";
        }
    } else {
        echo "Invalid file type.";
    }
} else {
    echo "Error uploading file.";
}