0
0
PHPprogramming~5 mins

File upload security risks in PHP

Choose your learning style9 modes available
Introduction

Uploading files can let users add content to your website. But if not careful, bad files can harm your site or steal data.

When allowing users to upload profile pictures or avatars.
When users can submit documents or images to your site.
When building a form that accepts file attachments.
When creating a content management system that supports media uploads.
When enabling users to share files or resources on your platform.
Syntax
PHP
<?php
// Example of checking file upload
if (isset($_FILES['upload'])) {
    $file = $_FILES['upload'];
    // Check file type and size here
}
?>

Always check the file type and size before saving.

Never trust the file name or MIME type sent by the browser.

Examples
This checks if the uploaded file has an allowed extension.
PHP
<?php
// Check file extension
$allowed = ['jpg', 'png', 'gif'];
$ext = pathinfo($_FILES['upload']['name'], PATHINFO_EXTENSION);
if (!in_array(strtolower($ext), $allowed)) {
    echo 'File type not allowed.';
}
?>
This prevents very large files from being uploaded.
PHP
<?php
// Check file size (max 2MB)
if ($_FILES['upload']['size'] > 2 * 1024 * 1024) {
    echo 'File is too large.';
}
?>
This saves the uploaded file to a folder on the server.
PHP
<?php
// Move uploaded file safely
$target = 'uploads/' . basename($_FILES['upload']['name']);
if (move_uploaded_file($_FILES['upload']['tmp_name'], $target)) {
    echo 'File uploaded successfully.';
} else {
    echo 'Upload failed.';
}
?>
Sample Program

This program checks the file type and size, then saves the file with a unique name to avoid overwriting. It shows clear messages for success or errors.

PHP
<?php
if (isset($_FILES['upload'])) {
    $allowed = ['jpg', 'png', 'gif'];
    $ext = strtolower(pathinfo($_FILES['upload']['name'], PATHINFO_EXTENSION));
    if (!in_array($ext, $allowed)) {
        echo 'Error: Only JPG, PNG, GIF files allowed.';
        exit;
    }
    if ($_FILES['upload']['size'] > 2 * 1024 * 1024) {
        echo 'Error: File size must be under 2MB.';
        exit;
    }
    $target_dir = 'uploads/';
    $target_file = $target_dir . uniqid('img_', true) . '.' . $ext;
    if (move_uploaded_file($_FILES['upload']['tmp_name'], $target_file)) {
        echo 'Success: File uploaded as ' . basename($target_file);
    } else {
        echo 'Error: Upload failed.';
    }
} else {
    echo 'No file uploaded.';
}
?>
OutputSuccess
Important Notes

Always rename uploaded files to avoid overwriting and hiding original names.

Store uploaded files outside the web root or restrict access to prevent direct execution.

Scan files for viruses or malware if possible before saving.

Summary

File uploads can be risky if you don't check the file type and size.

Always validate and rename files before saving to keep your site safe.

Use clear error messages to help users upload correct files.