php文件上傳——php經典實例


 php文件上傳——php經典實例

表單頁

<html>
    <head>
        <title>文件上傳</title>
        <meta  charset='utf-8' />
    </head>
    <body>
        <form action='doupload.php' method='post' enctype='multipart/form-data'>
            <input type='file' name='filename' />
            <input type='submit' />
        </form>
    </body>
</html>

上傳處理頁

<?php
    //var_dump($_FILES);
    /*'filename' => 
    array (size=5)
      'name' => string '7730-15042G60S6-52.jpg' (length=22)
      'type' => string 'image/jpeg' (length=10)
      'tmp_name' => string 'D:\wamp64\tmp\phpE94A.tmp' (length=25)
      'error' => int 0
      'size' => int 338411*/
    //獲取文件信息
    $fileinfo=$_FILES['filename'];
    //文件上傳路徑
    $path="./uploads/";
    //大小 0不限止
    $maxsize=0;
    
    //判斷錯誤號
    if($fileinfo['error']>0){
        switch($fileinfo['error']){
            case 1:$error="上傳的文件超過了 php.ini 中 upload_max_filesize 選項限制的值";break;
            case 2:$error="上傳文件的大小超過了 HTML 表單中 MAX_FILE_SIZE 選項指定的值";break;
            case 3:$error="文件只有部分被上傳。";break;
            case 4:$error="沒有文件被上傳。";break;
            case 6:$error="找不到臨時文件夾";break;
            case 7:$error="文件寫入失敗";break;
            default:$error="未知錯誤,請稍后再試...";
        }
    }
    //定義允許類型
    $typearr=array("image/jpeg","image/png","image/gif");
    //判斷類型
    if(count($typearr)>0){
        if(!in_array($fileinfo['type'],$typearr)){
            die("文件上傳失敗!類型不符");
        }
    }
    //取后綴
    $ext=pathinfo($fileinfo['name'],PATHINFO_EXTENSION);
    
    //生成隨機文件名
    do{
    
        $newname=date("YmdHis").rand(1000,9999).".".$ext;
    
    }while(file_exists($path.$newname));
    
    //判斷是否上傳成功
    if(is_uploaded_file($fileinfo['tmp_name'])){
        if(move_uploaded_file($fileinfo['tmp_name'],$path.$newname)){
            echo "上傳成功!";
        }else{
            die("移動失敗!");
        }
    
    }else{
        die("未知錯誤!請重試");
    
    }
    
?>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM