简体   繁体   中英

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');
    }
?>

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 (eg 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM