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.

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

报告相同问题?

悬赏问题

  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)