Php 文件上传与安全

Php 文件上传与安全,php,file-upload,Php,File Upload,我目前正在写一个上传图片的上传类。我执行扩展名检查,以验证上载的图像是否属于支持的类型,并且当上载的文件复制到其静止位置时,照片始终为chmod(0664)。这相对安全吗?我对图像编码知之甚少,但即使有人通过某种方式欺骗了我的扩展名检查,该文件无论如何也无法在服务器上运行,除非其他地方存在安全漏洞,并且攻击者已经进入了我的文件系统,对吗?这是我的分机支票: function validate_ext() { //Function validates that the files extensio

我目前正在写一个上传图片的上传类。我执行扩展名检查,以验证上载的图像是否属于支持的类型,并且当上载的文件复制到其静止位置时,照片始终为chmod(0664)。这相对安全吗?我对图像编码知之甚少,但即使有人通过某种方式欺骗了我的扩展名检查,该文件无论如何也无法在服务器上运行,除非其他地方存在安全漏洞,并且攻击者已经进入了我的文件系统,对吗?这是我的分机支票:

function validate_ext() { //Function validates that the files extension matches the list of allowed extensions
    $extension = $this->get_ext($this->theFile);
    $ext_array = $this->extensions;
    if (in_array($extension, $ext_array)) { //Check if file's ext is in the list of allowed exts
        return true;
        echo "ext found";
    } else {
        $this->error[] = "That file type is not supported. The supported file types are: ".$this->extString;
        return false;
    }
}
这是一个将上传的文件复制到最终存放位置的函数

if ($_FILES[$this->uploadName]['error'] === UPLOAD_ERR_OK){
    $newfile = $this->uploadDir.$this->theFile;
    if (!move_uploaded_file($this->tempFile, $newfile)) {
        $this->error[] = "The file could not be moved to the new directory. Check permissions and folder paths.";
        die($this->error_text());   
    }else{
        $this->error[] = "The file ".$this->originalName." was successfully uploaded.";
        if ($this->renameFile == true){
            $this->error[] = $this->originalName." was renamed to ".$this->theFile;
        }
        chmod($newfile , $this->fileperm);
    }
}else{
    $this->error[] = $this->file_upload_error_message($_FILES[$this->uploadName]['error']);
    die($this->error_text());
}

读取扩展名并不是检查文件类型的好方法。您应该读取文件mime类型。。。当然,这也可以伪造,但伪造更麻烦。

在Linux世界中,只要您授予文件非可执行权限,文件就无法执行。不管是.jpeg还是.bash。另一方面也是如此。具有可执行权限的.jpeg也可以执行(如果.jpeg文件的内容是可执行文件,而不是图像内容)。

您可以使用来检查文件本身。

因此,只需确保权限,而不必关心扩展名。)因此,它可能不会比执行扩展名检查、mime检查和确保用户可以在任何地方上传文件更安全,这些文件总是保存在类似644的文件中。非常感谢所有insight的家伙们!为了确保不会以某种方式执行任何操作,只需围绕它构建一个包装器脚本。包装器脚本应该执行一个标题(“内容类型:$mime_类型”)并将文件内容转储到标准输出。要确定mime类型,请检查fileinfo pecl扩展()。