sirjay
sirjay

Reputation: 1766

How to protect from file upload attack in php?

I have file upload script as below (upload.php). As I can guess, someone can write script that sends 1000+ files to upload.php at the small period of time.

So, how to protect myself from numerous file uploads attack?

<?php
    if (!empty($_FILES)) {   
        $ds = DIRECTORY_SEPARATOR;
        $storeFolder = 'uploads';

        $rand_dir = rand(1, 1000);
        $targetPath = realpath(dirname(__FILE__) . '/..') . $ds . $storeFolder . $ds . $rand_dir . $ds;
        $targetPath_clean = $storeFolder . $ds . $rand_dir . $ds;

        if (!file_exists($targetPath))
            mkdir($targetPath, 0777, true);

        $filename = date('YmdHis_') . generateRandomString() . '.' . pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);

        move_uploaded_file($_FILES['file']['tmp_name'], $targetPath . $filename);
        echo $targetPath_clean . $filename;
    } else {
        die('access denied');
    }
?>

Upvotes: 0

Views: 1023

Answers (1)

Abdel5
Abdel5

Reputation: 1120

This mainly depends on what you want to achieve.

If form is anonymous you can use kind of capatcha or limit the file upload from one host (e.g. saving given IP in database and limiting its ability to upload further files). If your script requires user authorization you can limit file upload by given login.

Please give us more details what is your business logic so we will be able to help you.

Upvotes: 1

Related Questions