dongshai2022 2016-09-18 07:24 采纳率: 100%
浏览 7

如何使用PHP验证多个上传的文件?

I am using PHP to upload multiple file to the database. So when I check file extension its always showing me my given error message even if file extension is correct:

File type is not allowed, We accept only .jpg, .png and .gif extension file

Here is the validation :

$total = count($_FILES['client_doc']['name']);                  
for($i=0; $i<$total; $i++) {
    $file_name = htmlspecialchars($_FILES['client_doc']['name'][$i]);
    $file_tmp =  htmlspecialchars($_FILES['client_doc']['tmp_name'][$i]);
    $file_size = htmlspecialchars($_FILES['client_doc']['size'][$i]);
    $file_ext = explode('.', $file_name);
    $file_ext = strtolower(end($file_ext));
    $allowed_type =  array('jpg', 'jpeg', 'gif', 'png');
}

if(!empty($file_name)) {
    if(!in_array($file_ext, $allowed_type)) {
        $msg[] = 'File type is not allowed, We accept only .jpg, .png and .gif extension file';
        $msg['error'] = true;
    }elseif($file_size > 2097152) { // only 2 mb size is allowed
        $msg[] = 'Uploaded file name must be less than 2MB';
        $msg['error'] = true;                            
    }
}
  • 写回答

1条回答 默认 最新

  • dongtang7347 2016-09-18 08:04
    关注

    I've tested your code by giving the $file_name variable test.png value and it works fine. Are you sure your file form works correctly? Try to echo $file_name's at the end of for loop and check if there's any output.

    Another tips:

    1. Do you want to validate all the files? As far as I'm concerned your current code validates only the last file - you iterate through all the files, but you overwrite variables storing file's data. In order to validate all the elements you have to put your condition inside the for loop.
    2. Because your $allowed_type is a constant, you don't have to overwrite it inside the loop.
    评论

报告相同问题?

悬赏问题

  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助
  • ¥15 STM32控制MAX7219问题求解答