Open In App

How to check the Type and Size before File Uploading in PHP ?

In PHP, it’s essential to validate file types and sizes before allowing users to upload files to a server. This helps prevent potential security vulnerabilities and ensures that only allowed file types and sizes are accepted. PHP provides various methods to perform these validations, including checking file extensions, MIME types, and file sizes.

Approach

Syntax:

// Define allowed file types and maximum file size
$allowedTypes = array('jpg', 'jpeg', 'png', 'gif');
$maxFileSize = 2 * 1024 * 1024; // 2MB

// Get file details
$fileName = $_FILES['file']['name'];
$fileSize = $_FILES['file']['size'];
$fileType = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));

// Check file type
if (!in_array($fileType, $allowedTypes)) {
echo "Only JPG, JPEG, PNG, and GIF files are allowed.";
}

// Check file size
if ($fileSize > $maxFileSize) {
echo "File size exceeds the maximum limit of 2MB.";
}

// If both checks pass, proceed with file upload

Explanation

Difference between File Type and Size

Checking File Type Checking File Size
Verify file extensions or MIME types against a predefined list Compare the file size against the maximum allowed size
Use functions like pathinfo() or MIME type detection to determine file type Access file size information using $_FILES superglobal array
Prevents uploading of disallowed file types Prevents uploading of excessively large files

Usage

Article Tags :