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

报告相同问题?

悬赏问题

  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题