doudao5287 2016-02-23 12:44
浏览 38
已采纳

上传错误的文件类型PHP时无法获得echo错误

I'm trying to make it so that when the user uploads any document that isn't a csv file an echo error appears. However when I tested it I got the echo error on both the correct file type and an incorrect file type. Anyone know where I'm going wrong?

<?php
    ob_clean();session_start();

    if (isset($_GET['logout'])){
    session_destroy();  
    }

    if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] == false) {
        header("Location: index.php");
    }

    if(isset($_FILES['UploadFileField'])){
    $allowed = array('csv');
    $UploadName = $_FILES['UploadFileField']['name'];
    $UploadTmp = $_FILES['UploadFileField']['tmp_name'];
    $UploadType = $_FILES['UploadFileField']['type'];
    $NewFileName = "project1file.txt";


    if(!$UploadTmp){
        echo '<font color="#FF0000" size="3"><p align="center"><b>No File Selected, Please Try Again.</b></p></font>';
    }else{
        move_uploaded_file($UploadTmp, "UPLOADS/$NewFileName");
        echo '<font color="#006600" size="3"><p align="center"><b>File Successfully Uploaded.</b></p></font>';

    }

    if(!in_array($UploadTmp,$allowed) ) {
    echo 'error';
}

}

?>
  • 写回答

3条回答 默认 最新

  • dongshuohuan5291 2016-02-23 12:54
    关注

    Use the below code to find the extension of the uploaded file:

    $type = $_FILES["UploadFileField"]["type"];
    

    And then echo

    if(!in_array($type,$allowed) ) {
        echo 'error';
    }
    

    Update 1:

    $mimes = array('application/vnd.ms-excel','text/plain','text/csv','text/tsv');
    
    if(in_array($_FILES['UploadFileField']['type'],$mimes)){
      // do something
    } else {
      die("Sorry, mime type not allowed");
    }
    

    Update 2:

    You can use this as well, actually $_FILES...['type'] is not safe to use.

    $types = array('csv');
    
    $ext = pathinfo($UploadName, PATHINFO_EXTENSION);
    
    
    if(in_array($ext,$types)){
    // do something
    } else {
        die("Sorry, only CSV type allowed");
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵