duanbin3021 2016-01-15 08:44
浏览 49
已采纳

使用php检查文件大小和类型

My assignment is to make a php file for uploading files to a directory. The user should only be able to upload a file if the file size is less than 512kb and the file type is txt, zip or jpg. My code is not working properly as it ignores the output if file is not relevant and it also does not check the file type properly. Can anyone help please?

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Files</title>

</head>

<body>



<form method="POST" enctype="multipart/form-data">
<input type="file" name="dat">
<input type="submit" value="Upload">
<div>(max. size: 512kb, Type: jpg,txt,zip)</div>
</form>
<?php
if(isset($_FILES["dat"])){
    $file=$_FILES["dat"];
    $name=$file["name"];
    $size=$file["size"];
    $location=$file["tmp_name"];
    $location_file=$location . basename($name);


    if($size>512000 or $location_file!="txt" or $location_file!="zip" or $location_file!="jpg"){
        echo "The file is too big or the format is not correct...";
    }
    else{
        move_uploaded_file($location,"files/".$name);
    }
}

?>
</body>

</html>
  • 写回答

3条回答 默认 最新

  • doubutao6216 2016-01-15 09:00
    关注

    First try to debug your uploaded file. Secondly don't rely on the name of the file since it can be spoofed easily. tmp_name gives you the files temporary location, which will be a random string. Your best option is to call getimagesize on tmp_name, for images, and finfo_open or new finfo for other file types to compare its mime type, you could also explode the name and use end which will give you an extension as well. maybe define an array of accepted extensions and use in_array to check if extension is valid. Will provide example code after I get to a PC.

    LE: as promised a more complex check with comments and security concepts

    <?php
    // you can make sure you have every variable set
    // then procced further
    if(
        isset(
            $_FILES['dat'], $_FILES['dat']['tmp_name'],
            $_FILES['dat']['name'], $_FILES['dat']['size'],
            $_FILES['dat']['error']
        )
    ){
    
        $accepted = array(
            'image/jpeg'      => 'jpg',
            'text/plain'      => 'txt',
            'application/zip' => 'zip',
        );
        $file      = $_FILES['dat'];
        $maxSize   = 512 * 1024; // 512 KB
    
        // check if any upload error occured
        if( UPLOAD_ERR_OK !== $file['error'] ){
    
            // http://php.net/manual/en/features.file-upload.errors.php
            echo 'Upload error: ', $file['error'], '<br/>';
    
        // check if file size is bigger than $maxSize
        } elseif( $file['size'] > $maxSize ){
            // if filesize is bigger than upload_max_filesize directive in php.ini
            // script may timeout without any error
            // post_max_size and upload_max_filesize need to be high enough
            echo 'Error: File size is to big!<br/>';
    
        // can proceed further
        } else {
    
            // you will need to have the fileinfo enabled in php ini to use these
            $finfo    = finfo_open( FILEINFO_MIME );
            $mime     = finfo_file( $finfo, $file['tmp_name'] );
            // finfo may give you charset info as well
            // text/plain; charset=utf-8 or image/jpeg; charset=binary
            $mime     = array_shift( explode( ';', $mime ) );
            // change uploaded file name do to security reasons
            // google "php null char upload"
            // nice read http://resources.infosecinstitute.com/null-byte-injection-php/
            $filename = md5( time() . $file['name'] ) . '.';
            // if mime is accepted
            if( ! array_key_exists( $mime, $accepted ) /* or use isset: ! isset( $accepted[ $mime ] ) */ ){
    
                echo 'Error: Unsupported file type!<br/>';
    
            // you could check if file is image and check min-max width & height
            // for now move the uploaded file
            } elseif( ! @move_uploaded_file( $file['tmp_name'], 'files/' . $filename . $accepted[ $mime ] ) ){
    
                echo 'Unable to save uploaded image to <strong>',
                    htmlspecialchars( 'files/' . $filename . $accepted[ $mime ] ),
                '</strong>';
    
            } else {
    
                echo '<a href="files/', htmlspecialchars( $filename . $accepted[ $mime ] ), '" target="_blank">',
                    htmlspecialchars( $filename . $accepted[ $mime ] ),
                '</a>';
    
            }
    
        }
    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?