What are best practices for checking the size of a file before uploading it in PHP?

When uploading files in PHP, it is important to check the size of the file to ensure it does not exceed any limitations set by the server or application. One common best practice is to use the $_FILES superglobal array to access the 'size' key, which contains the size of the uploaded file in bytes. You can compare this value to a maximum file size limit to determine if the file is within acceptable limits before proceeding with the upload.

// Check the size of the uploaded file before proceeding with the upload
$maxFileSize = 1048576; // 1 MB limit
if ($_FILES['file']['size'] > $maxFileSize) {
    echo 'Error: File size exceeds the limit of 1 MB.';
    // Handle the error or stop the upload process
} else {
    // Proceed with the file upload process
}