php檔案上傳、下載
以前一直在做java,最近轉行去搞php開發,總覺得力不從心。這幾天有個需求,是關於php的檔案上傳和下載的。給大家分享下自己的學習資料。
?
1.先來個請求頁面upload.html
Administration - upload new filesUpload new news files
?
2.php處理用戶端請求的資料upload.html
Uploading...Uploading file...
0) { echo 'Problem: '; switch ($_FILES['userfile']['error']) { case 1:echo 'File exceeded upload_max_filesize'; break; case 2:echo 'File exceeded max_file_size'; break; case 3:echo 'File only partially uploaded'; break; case 4:echo 'No file uploaded'; break; case 6: echo 'Cannot upload file: No temp directory specified.'; break; case 7: echo 'Upload failed: Cannot write to disk.'; break; } exit; } // Does the file have the right MIME type? if ($_FILES['userfile']['type'] != 'text/plain') { echo 'Problem: file is not plain text'; exit; } // put the file where we'd like it $upfile = '/uploads/'.$_FILES['userfile']['name']; if (is_uploaded_file($_FILES['userfile']['tmp_name'])) { if (!move_uploaded_file($_FILES['userfile']['tmp_name'], $upfile)) { echo 'Problem: Could not move file to destination directory'; exit; } } else { echo 'Problem: Possible file upload attack. Filename: '; echo $_FILES['userfile']['name']; exit; } echo 'File uploaded successfully
'; // reformat the file contents $fp = fopen($upfile, 'r'); $contents = fread ($fp, filesize ($upfile)); fclose ($fp); $contents = strip_tags($contents); $fp = fopen($upfile, 'w'); fwrite($fp, $contents); fclose($fp); // show what was uploaded echo 'Preview of uploaded file contents:
'; echo $contents; echo '
';?>
?
3.php檔案下載
?總的來說,上面的3個程式碼片段只是簡單介紹了php檔案的上傳下載,還有很多問題要解決,就例如上傳大檔案的時候怎麼處理,批量上傳、大檔案下載等等問題。當然跟java一樣,php也有很多架構可以解決這方面。