php處理檔案上傳
阿新 • • 發佈:2018-11-10
注意點:
1、<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">處理檔案上傳的時候,如果一個表單裡面有檔案域的時候,mothod="post",enctype="multipart/form-data',這裡必須這樣設定
2、用$_FILES超全域性成員來接受檔案
3、move_uploaded_file(sourcename,targetname);移動的目標路徑中資料夾到目的資料夾
4、檔案上傳的大小限制,和post請求體的大小限制
這個需要修改php.ini檔案upload_max_filesize= ; 和post_max_size= ;
<?php function upload(){ $_FILES;//獲取接受的檔案 if(empty($_FILES['avatar'])){ $GLOBALS['message'] = '請選擇檔案'; return ; } $avatar=$_FILES['avatar']; if($avatar['error']!==0){//如果沒有錯誤時顯示0 $GLOBALS['message'] = '有檔案上傳錯誤'; return ; } //為了便於理解,我們可以將在客戶端返回的內容寫在這裡 // $avatar => array(5) { // ["name"]=> // string(11) "icon-02.png" // ["type"]=> // string(9) "image/png" // ["tmp_name"]=> // string(27) "C:\Windows\Temp\php1138.tmp" // ["error"]=> // int(0) // ["size"]=> // int(4398) // } //上面兩步都沒有錯誤,說明,檔案檔案上傳成功 echo $GLOBALS['message'] ="上傳成功"; //在服務端並沒有顯示這個圖片的路徑,我們必須把上傳檔案時那個暫時存放的路徑指向一個能在檔案根目錄顯示的路徑 //原始檔 $source=$avatar["tmp_name"]; //目的檔案 $target=mkdir('load').$avatar["name"]; //移動 $moved = move_uploaded_file($source, $target); if(!$moved){ $GLOBALS['message'] = "上傳失敗"; return; } } if($_SERVER['REQUEST_METHOD']=='POST'){ upload(); } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data"> <input type="file" name="avatar"> <button>提交</button> </form> </body> </html>