【问题标题】:How to allow all file upload types except a specific one [duplicate]如何允许除特定文件之外的所有文件上传类型[重复]
【发布时间】:2016-01-08 13:27:14
【问题描述】:

我的上传 php 代码可以允许所有文件类型,但我想阻止某些文件类型 这是我上传的php代码 我想屏蔽 .exe、.php 等文件类型

请简单说明一下我是php初学者

    <?php
$target_dir = "/uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$FileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
    $check = filetype($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== true) {
        echo "THANK YOU - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
    }
}
// Check if file already exists
if (file_exists($target_file)) {
    echo "Sorry, file already exists.";
    $uploadOk = 0;
}



// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}
?>

【问题讨论】:

  • 你能简单解释一下吗

标签: php


【解决方案1】:

核心 PHP(发现于 http://php.net/manual/en/features.file-upload.php):

// DO NOT TRUST $_FILES['upfile']['mime'] VALUE !!
// Check MIME Type by yourself.
$finfo = new finfo(FILEINFO_MIME_TYPE);
if (false === $ext = array_search(
    $finfo->file($_FILES['upfile']['tmp_name']),
    array(
        'jpg' => 'image/jpeg',
        'png' => 'image/png',
        'gif' => 'image/gif',
    ),
    true
)) {
    throw new RuntimeException('Invalid file format.');
}

所以永远不要相信$_FILES['upfile']['mime'],总是使用fileinfo

【讨论】:

    猜你喜欢
    • 2015-08-06
    • 1970-01-01
    • 1970-01-01
    • 2020-08-09
    • 1970-01-01
    • 2017-12-08
    • 2021-02-27
    • 2019-12-04
    • 2021-01-26
    相关资源
    最近更新 更多