如何防止shell上传

时间:2017-04-12 10:27:22

标签: php

我已经为基本文件上传创建了以下代码,我还写了一篇文章。但是有一位读者表示它很容易受到shell上传的影响。现在我需要帮助来了解我的代码是如何易受攻击的,以及我如何解决它。

 <!DOCTYPE html>
    <html>
    <head>

    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

    <!-- Latest compiled and minified JavaScript -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
        <title>Image handler</title>
    </head>
    <body style="margin:10px;">

    <?php

    if (!empty($_FILES["image"])) {
        $myFile = $_FILES["image"];


    if($myFile['error'] > 0){
        die('<div class="alert alert-danger" role="alert"> An error occured while uploading the file </div>');
    }

    $name = preg_replace("/[^A-Z0-9._-]/i", "_", $myFile["name"]);

        $i = 0;
        $parts = pathinfo($name);
        while (file_exists("upload/". $name)) {
            $i++;
            $name = $parts["filename"] . "-" . $i . "." . $parts["extension"];
        }

    $fileType = exif_imagetype($myFile["tmp_name"]);
    $allowed = array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG);
    if (!in_array($fileType, $allowed)) {
     die('<div class="alert alert-danger" role="alert"> File type not supported </div>');
    }

    if($myFile['size'] > 500000){
        die('<div class="alert alert-danger" role="alert"> File is too big </div>');
    }

        $i = 0;
        $parts = pathinfo($name);
        while (file_exists("upload/" . $name)) {
            $i++;
            $name = $parts["filename"] . "-" . $i . "." . $parts["extension"];
        }

     $success = move_uploaded_file($myFile["tmp_name"],"upload/" . $name);
          if (!$success) { 
                echo '<div class="alert alert-danger" role="alert"> Sorry unable to upload file </div>';
               exit;
            }
          else
         {  
          chmod("upload/" . $name, 0644);
            echo '<div class="alert alert-success" role="alert"> Your file is successfully uploaded </div>';

         }





    }

    ?>

    </body>
    </html>

0 个答案:

没有答案