php如何实现上传指定类型及指定大小的文件

时间:2016-08-23
在开发文件上传功能时,有时候因为某些特殊原因只允许上传指定类型的文件,比如只允许上传图片,或只允许上传pdf文件,或只能上传小于2M的文件等等,这时候我们就需要对上传文件的类型和大小作出判断,然后决定是否执行上传操作,PHP具体实现源代码如下。

下面的代码演示了php中如何获取用户上传的文件,并限制文件类型的一般图片文件,最后保存到服务器

HTML源码:

<html>
<head>
     <title>Upload Form</title>
</head>
<body>
<form action="UploadSingle.php" method="post" enctype="multipart/form-data">
    Upload a file: <input type="file" name="thefile"><br><br>
    <input type="submit" name="Submit" value="Submit">
</form>
</body>
</html>

php上传并判断文件类型源码

<?php
    $aErrors = "";
    if ( !empty( $thefile_name ) ) // no file selected
    {
        $$thefile_type=$_FILES["file"]["type"];
        if ( ( $thefile_type == "image/gif" ) ||
             ( $thefile_type == "image/pjpeg" ) ||
             ( $thefile_type == "image/jpeg" ) ){
            if ( $thefile_size < ( 1024 * 100 ) ){
                $aCurBasePath = dirname( $PATH_TRANSLATED );
                $aNewName = $aCurBasePath . $thefile_name;
                copy( $thefile, $aNewName );
            } else {
                $aErrors .= "超过最大上传文件限制";
            }
        } else {
            $aErrors .= "文件不是图片";
        }
    } else{
        $aErrors .= "没有选中任何文件上传";
    }
?>