doujiu1447 2016-11-17 16:07
浏览 50
已采纳

限制“.php”文件上传

I am making basic photo hosting, just to upload images and resize them.

Everything works fine, I also have added accept="image/*" for my File upload button, but it is still possible to upload other files. So in my PHP code I check whether it is image or other file, so if it is not image, I basically remove it. But I have a problem. If user uploads "index.php" file, my index file on server will be overwritten and as my code should do, it removes "index.php" so. basically self destruction.

Is there way to restrict file upload before file is actually uploaded on server?

Or at least, is there way to change root directory of file that is uploaded?

I don't think that JavaScript or HTML restriction will do anything, because "hackermans" can change it easily in inspect element.

  • 写回答

1条回答 默认 最新

  • dqyuipw44576 2016-11-17 16:18
    关注
    class Upload {
    
    private $destinationPath;
    private $errorMessage;
    private $extensions;
    private $allowAll;
    private $maxSize;
    private $uploadName;
    private $seqnence;
    private $imageSeq;
    public $name = 'Uploader';
    public $useTable = false;
    
    function setDir($path) {
        $this->destinationPath = $path;
        $this->allowAll = false;
    }
    
    function allowAllFormats() {
        $this->allowAll = true;
    }
    
    function setMaxSize($sizeMB) {
        $this->maxSize = $sizeMB * (1024 * 1024);
    }
    
    function setExtensions($options) {
        $this->extensions = $options;
    }
    
    function setSameFileName() {
        $this->sameFileName = true;
        $this->sameName = true;
    }
    
    function getExtension($string) {
        $ext = "";
        try {
            $parts = explode(".", $string);
            $ext = strtolower($parts[count($parts) - 1]);
        } catch (Exception $c) {
            $ext = "";
        }
        return $ext;
    }
    
    function setMessage($message) {
        $this->errorMessage = $message;
    }
    
    function getMessage() {
        return $this->errorMessage;
    }
    
    function getUploadName() {
        return $this->uploadName;
    }
    
    function setSequence($seq) {
        $this->imageSeq = $seq;
    }
    
    function getRandom() {
        return strtotime(date('Y-m-d H:i:s')) . rand(1111, 9999) . rand(11, 99) . rand(111, 999);
    }
    
    function sameName($true) {
        $this->sameName = $true;
    }
    
    function uploadFile($fileBrowse) {
        $result = false;
        $size = $_FILES[$fileBrowse]["size"];
        $name = $_FILES[$fileBrowse]["name"];
        $ext = $this->getExtension($name);
        if (!is_dir($this->destinationPath)) {
            $this->setMessage("Destination folder is not a directory ");
        } else if (!is_writable($this->destinationPath)) {
            $this->setMessage("Destination is not writable !");
        } else if (empty($name)) {
            $this->setMessage("File not selected ");
        } else if ($size > $this->maxSize) {
            $this->setMessage("Too large file !");
        } else if ($this->allowAll || (!$this->allowAll && in_array($ext, $this->extensions))) {
    
            if ($this->sameName == false) {
                $this->uploadName = $this->imageSeq . "-" . substr(md5(rand(1111, 9999)), 0, 8) . $this->getRandom() . rand(1111, 1000) . rand(99, 9999) . "." . $ext;
            } else {
                $this->uploadName = $name;
            }
            if (move_uploaded_file($_FILES[$fileBrowse]["tmp_name"], $this->destinationPath . $this->uploadName)) {
                $result = true;
            } else {
                $this->setMessage("Upload failed , try later !");
            }
        } else {
            $this->setMessage("Invalid file format !");
        }
        return $result;
    }
    
    function deleteUploaded() {
        unlink($this->destinationPath . $this->uploadName);
    }
    

    }

    How to use it :

    function callMe(){
                    $uploader   =   new Upload();
                    $directory = "NAMEDIR"
                    if(!is_dir($directory)){
                        mkdir($directory);
                    }
                    $uploader->setDir($directory);
                    $uploader->setExtensions(array('jpg','jpeg','png','gif'));  //allowed extensions list//
                    $uploader->setMaxSize(.5);                          //set max file size to be allowed in MB//
                    $uploader->sameName(true);
                    if($uploader->uploadFile('file')){   //txtFile is the filebrowse element name //     
                        $image  =   $uploader->getUploadName(); //get uploaded file name, renames on upload//
    
                        echo json_encode(array("success"=>true,"message"=>"Success Add","image"=>$directory.$image,"image_upload"=>$image));
    
                    }else{//upload failed
                        echo json_encode(array("success"=>false,"message"=>$uploader->getMessage(),"image"=>""));
                    }
                }
                callMe();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀