PHP檔案上傳操作和封裝,

來源:互聯網
上載者:User

PHP檔案上傳操作和封裝,

PHP檔案上傳主要兩個步驟:

1.首先前端html寫好檔案表單上傳網頁

2.在前端點提交時,web伺服器php指令碼通過超全域變數$_FILES和一個move_uploaded_file函數搞定

前端html如下:

<!DOCTYPE HTML><html><head>    <meta charset="utf-8">    <title>檔案上傳</title></head><body>    <form action="upload.php" method="post" enctype="multipart/form-data">       <div style="margin: 0 auto; padding:50px 0px; width:300px;">            <input type="file" id="upload" name="uploadpic" style="display:none"/>            <input type="text" id="filename" value="檔案名稱">            <input type="button" id="picbtn" value="圖片上傳" />            <input type="submit" value="提交" />                     </div>    </form>    <script type="text/javascript">    function $(id)    {        var objs = document.getElementById(id);        return objs;    }    window.onload = function(){        $("picbtn").onclick = function(){        $("upload").click();   //點圖片上傳時,同時觸發檔案選擇        }        $("upload").onchange = function(){            $("filename").value = this.value;   //擷取檔案選擇值        }            }       </script></body></html>
註:表單上傳檔案時,method必須用post,且須聲明是enctype="multipart/form-data"

2.伺服器php指令碼upload.php代碼如下:

<?phpif(move_uploaded_file($_FILES['uploadpic']['tmp_name'], './fileupload/'.$_FILES['uploadpic']['name'])){    echo "ok";    }else {    echo "fail";}
註:可以用print_r($_FILES)列印查看超全域變數裡面放的內容,可以看到檔案的相關資訊都放在這個變數裡面;如

array (  'uploadpic' =>   array (    'name' => '1客棧首頁.jpg',    'type' => 'image/jpeg',    'tmp_name' => 'C:\\Windows\\Temp\\php3F1C.tmp',    'error' => 0,    'size' => 1706919,  ),)ok
從變數的數組裡面可以知道上傳的檔案名稱,檔案類型、web伺服器臨時存放圖片的位置(如果要更改臨時存放路徑,可以去php.ini裡面更改),錯誤資訊和檔案大小(限制檔案上傳大小,也可以到php.ini裡修改)。

error有如下幾種:

其值為 0,沒有錯誤發生,檔案上傳成功。 
其值為 1,上傳的檔案超過了 php.ini 中 upload_max_filesize 選項限制的值。 
其值為 2,上傳檔案的大小超過了 HTML 表單中 MAX_FILE_SIZE 選項指定的值。 
其值為 3,檔案只有部分被上傳。 
其值為 4,沒有檔案被上傳。
其值為 6,找不到臨時檔案夾。PHP 4.3.10 和 PHP 5.0.3 引進。 
其值為 7,檔案寫入失敗。PHP 5.1.0 引進。


==========檔案上傳封裝類============

<?phpclass UpFile{    public $maxsize=2; //1M    public $errmsg="";    public $ext = "png,jpg,bmp,gif";        //上傳大小是否符合    function isAllowSize($size)    {         if($size <= $this->maxsize*1024*1024)         {             return true;         }         else          {             return false;         }    }        //判斷尾碼名是否符合    function isAllowExt($ext)    {        return in_array(strtolower($ext), explode(',', $this->ext));    }        //擷取檔案尾碼名    function getFileExt($file)    {        $arr = explode('.', $file);        return end($arr);    }        //圖片上傳,$pickey為input的name值,$save_path儲存路徑    function upload($pickey,$save_path)    {        if(!isset($_FILES[$pickey]))        {            return false;        }                if($_FILES[$pickey]['error'] !=0)        {            $this->errmsg = $this->getErrorType($_FILES[$pickey]['error']);            return false;        }        $file_ext = $this->getFileExt($_FILES[$pickey]['name']);        echo $file_ext;        if(!$this->isAllowExt($file_ext))        {            $this->errmsg = "檔案尾碼名不符合";            return false;        }        echo $_FILES[$pickey]['size'];        if(!$this->isAllowSize($_FILES[$pickey]['size']))        {            $this->errmsg = "大小超過限制";            return false;        }                $str = "abcdefjhijkmnpqrst23456789";        $filename = date("YmdHis",time()).substr(str_shuffle($str), 0,6);        $dir = $this->makeDir($save_path);        if(move_uploaded_file($_FILES[$pickey]['tmp_name'], $dir.'/'.$filename.'.'.$file_ext))        {                       return true;        }        else         {            $this->errmsg = "上傳失敗";            return false;        }    }    //建立目錄    function makeDir($save_path)    {       $path = $save_path.'/'.date("Ymd",time());              if(is_dir($path) || mkdir($path,0777,true))  //不存在該目錄檔案,建立       {           echo $path;           return $path;       }       else        {           return false;       }    }        //錯誤類型分析    function getErrorType($error)    {        $errmsg = "";        switch ($error)        {            case 0:                $errmsg = "檔案上傳成功";                break;            case 1:                $errmsg = "上傳的檔案超過了 php.ini 中 upload_max_filesize 選項限制的值";                break;            case 2:                $errmsg = "上傳檔案的大小超過了 HTML 表單中 MAX_FILE_SIZE 選項指定的值";                break;            case 3:                $errmsg = "檔案只有部分被上傳";                break;            case 4:                $errmsg = "沒有檔案被上傳";                break;            case 6:                $errmsg = "找不到臨時檔案夾";                break;            case 7:                $errmsg = "檔案寫入失敗";                break;        }        return $errmsg;    }}

使用如下:

<?phpinclude 'upfile.class.php';$upfile = new UpFile();if($upfile->upload('uploadpic', "./fileupload")){    echo "ok";}else{    echo $upfile->errmsg;}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.