Open In App

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

Last Updated : 13 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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

  • Checking File Type
    • Determine acceptable file extensions or MIME types.
    • Use pathinfo( ) function to extract the file extension.
    • Compare the file extension or MIME type against the list of allowed types.
  • Checking File Size
    • Determine the maximum allowed file size.
    • Use $_FILES superglobal array to access the uploaded file’s size.
    • Compare the file size against the maximum allowed size.

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

  • Defined allowed file types (jpg, jpeg, png, gif) and maximum file size (2MB).
  • Retrieved file details using $_FILES['file'] array.
  • Checked if the file type is allowed using in_array() function.
  • Checked if the file size is within the maximum limit using a simple comparison.
  • If both checks pass, the code proceeds with file upload.

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

  • Security: File type and size validation help prevent security vulnerabilities such as file upload attacks or denial of service attacks.
  • User Experience: Proper validation provides feedback to users about allowed file types and sizes, improving the user experience.

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads