dongyun3805
2017-10-24 12:31 阅读 62
已采纳

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

I am trying to upload either pdf or jpg, jpeg files to a folder and the code is as follows:

//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';
    }
}

while trying to upload files with correct extension and size i am able to upload it.

But if i try to upload an over sized or incorrect format file, it displays my error message, but the file always get uploaded to the folder.

Why is it so ?? Please, What is wrong with my code??

Is the way, i am doing it is secure enough ?? the folder is owned by www-data and permission is 755. I have a .htaccess file too in the file upload folder to prevent executables as follows:

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

The file always uploading is confusing me.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

  • 已采纳
    dongtaijue1578 dongtaijue1578 2017-10-24 12:35

    You are not using the errors you just found to check if you need to continue.

    This:

    if(is_uploaded_file($tmp_path))
    

    Should be something like:

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

    And you should initialize your $error array at the start as an empty array if you are not doing that already.

    点赞 评论 复制链接分享

相关推荐