What are some best practices for handling file size validation before uploading files using PHP?

When handling file uploads in PHP, it's important to validate the file size before allowing it to be uploaded to prevent large files from consuming excessive server resources. One way to do this is by checking the file size against a maximum limit set by your application.

// Set maximum file size in bytes (e.g. 5MB)
$maxFileSize = 5 * 1024 * 1024;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if ($_FILES['file']['size'] > $maxFileSize) {
        echo "File size is too large. Please upload a file smaller than 5MB.";
    } else {
        // File size is within limit, proceed with file upload
        move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
        echo "File uploaded successfully!";
    }
}