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条)

报告相同问题?

悬赏问题

  • ¥20 keepalive配置业务服务双机单活的方法。业务服务一定是要双机单活的方式
  • ¥50 关于多次提交POST数据后,无法获取到POST数据参数的问题
  • ¥15 win10,这种情况怎么办
  • ¥15 如何在配置使用Prettier的VSCode中通过Better Align插件来对齐等式?(相关搜索:格式化)
  • ¥100 在连接内网VPN时,如何同时保持互联网连接
  • ¥15 MATLAB中使用parfor,矩阵Removal的有效索引在parfor循环中受限制
  • ¥20 Win 10 LTSC 1809版本如何无损提升到20H1版本
  • ¥50 win10 LTSC 虚拟键盘不弹出
  • ¥30 微信小程序请求失败,网页能正常带锁访问
  • ¥15 Matlab求解微分方程,如何用fish2d进行预优?