dongyun3805 2017-10-24 12:31 采纳率: 0%
浏览 102
已采纳

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 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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料