php文件上传即使出错也总是上传文件

时间:2017-10-24 12:31:51

标签: php file-upload

我正在尝试将pdf或jpg,jpeg文件上传到文件夹,代码如下:

//Get the uploaded file information
if(!$_FILES['medreport']['error'])
{
    $medreport = basename($_FILES['medreport']['name']);
    $medreport_extn = substr($medreport, strrpos($medreport, '.') + 1);//get the file extension of the file
    $medreport_size = $_FILES["medreport"]["size"]/1024;//size in KBs
    $tmp_path = $_FILES["medreport"]["tmp_name"];
    $report_folder = "../reports/";

    //Settings
    $max_allowed_file_size = 200; // size in KB
    $allowed_extensions = array("jpg", "jpeg", "pdf");

    //Validations
}

if($medreport_size > $max_allowed_file_size )
{
    $error[] = "Size of the report file should be less than $max_allowed_file_size KB";
}

//Validate the file extension
$allowed_ext = false;
for($i=0; $i<sizeof($allowed_extensions); $i++)
{
    if(strcasecmp($allowed_extensions[$i],$medreport_extn) == 0)
    {
        $allowed_ext = true;
    }
}

if(!$allowed_ext)
{
    $error[] = "The uploaded report file is not a supported file type. "."Only pdf, jpg and jpeg report file types are supported. ";
}

//replace filename with unixtime
$unixtime =time();
$medreport = $unixtime.mt_rand(0,9).'.'.$medreport_extn;

$report_path = $report_folder . $medreport;
if(is_uploaded_file($tmp_path))
{
    if(!copy($tmp_path,$report_path))
    {
        $error[] = 'Error while copying the uploaded report file';
    }
}

在尝试上传具有正确扩展名和大小的文件时,我可以上传它。

但是,如果我尝试上传超大或不正确的格式文件,它会显示我的错误消息,但该文件始终会上传到该文件夹​​。

为什么会这样?请问,我的代码出了什么问题?

顺便问一下,我这样做是否足够安全?该文件夹由www-data拥有,权限为755.我在文件上传文件夹中也有一个.htaccess文件,以防止可执行文件如下:

SetHandler none
SetHandler default-handler
Options -ExecCGI
php_flag engine off

总是上传的文件令我困惑。

1 个答案:

答案 0 :(得分:3)

您没有使用刚发现的错误来检查是否需要继续。

此:

if(is_uploaded_file($tmp_path))

应该是这样的:

if(count($error) === 0 && is_uploaded_file($tmp_path))

如果您还没有这样做,那么您应该在开始时将$error数组初始化为空数组。