一,比較簡單的實現文件上傳
文件上傳原理:文件上傳原理:將客戶端的文件先上傳到服務器端,然后再將服務器端的臨時文件移動到指定的目錄。
客戶端配置:要上傳文件,我們需要采用表單,并且表單發送的形式來POST請求,而且要求將enctype設置為multipart/form-data,總結上傳的條件如下:
瀏覽器表單頁面:表單發送方式為post,指定enctype=multipart/form-data,客戶端的代碼:
- <form action="uploadFile.php" method="post" accept-charset="utf-8" enctype="multipart/form-data">
- 請選擇要上傳的文件:
- <input type="file" name="myfile">
- <input type="submit" value="上傳文件">
- </form>
$_FILES文件變量,下面是上傳一個圖片然后打印整理出來的數據:
- // name => 'QC8054R7QPGQ_1000x500.jpg'
- // type => 'image/jpeg'
- // tmp_name => '/Applications/MAMP/tmp/php/php1X5KZU'
- // error => 0
- // size => 229936
$_FILES上傳的參數含義說明:
name:上傳的文件的名稱
type: 上傳的文件的MIME類型
tmp_name:文件上傳到服務器的臨時路徑
site:上傳的文件的大小
error:上傳的文件的錯誤碼,0表示上傳成功UPLOAD_ERR_OK
移動文件
移動文件方式一:上傳文件到服務器端是在一個臨時路徑下,我們需要將文件移動到指定的目錄下,我們可以通過下面的函數來實現移動:將指定的文件移到的目錄路徑下,要求待移動的文件是通過HTTP POST上傳的.
bool move_uploaded_file ( string $filename , string $destination )
我們需要判斷一下是否是通過HTTP POST上傳的,下面的方法可以判斷:判斷文件是否是通過HTTP POST上傳的,如果是返回TRUE,否則返回FALSE
bool is_uploaded_file ( string $filename )
移動文件方式二:
我們還可以通過下面的函數來實現移動文件:
參數一:待移動的文件
參數二:移動到的目標路徑
bool copy ( string $source , string $dest [, resource $context ] )
處理上傳:
- define('UPLOAD_PATH', 'Uploads');
- $name = $_FILES['myfile']['name'];
- $type = $_FILES['myfile']['type'];
- $tmp_name = $_FILES['myfile']['tmp_name'];
- $error = $_FILES['myfile']['error'];
- $size = $_FILES['myfile']['size'];
- if ($error == UPLOAD_ERR_OK) {
- if (is_uploaded_file($tmp_name)) {
- move_uploaded_file($tmp_name, UPLOAD_PATH . '/' . $name);
- } else {
- if (is_file($tmp_name) && !copy($tmp_name, UPLOAD_PATH . '/' . $name)) {
- var_dump('ok');
- } //Vevb.com
- }
- } else {
- // 上傳到服務器就已經出錯了
- var_dump($error);
- }
php.ini上傳配置:
假設我們要支持上傳20M的文件,那么我們可以設置以下選項:
一定要設置為On,才能上傳文件,若設置為Off,則服務器是接收不到文件數據的
file_uploads = On
指定上傳文件到服務器的臨時目錄,默認為不打開的,可以不寫
upload_tmp_dir = "d:/uploads_tmp"
支持上傳的文件的最大為20M
upload_max_filesize = 20M
設置POST請求允許一次請求的最大值為100M
post_max_size = 100M
上傳操作允許的最長時間,超過600秒則會停止腳本運行,0表示無限制
max_execution_time = 600
PHP腳本解析請求數據所用的最大時間,默認為60秒,0表示無限制
max_input_time = 600
單個PHP腳本所能申請的最大內存,-1表示無限制!
memory_limit = 128M
上傳文件錯誤碼:
UPLOAD_ERR_OK:代表上傳成功
UPLOAD_ERR_EXTENSION:上傳的文件被PHP擴展程序中斷
UPLOAD_ERR_PARTIAL:文件只有部分被上傳
UPLOAD_ERR_CANT_WRITE:文件寫入失敗
UPLOAD_ERR_FORM_SIZE:表單文件超過了post_max_size
UPLOAD_ERR_INI_SIZE:文件大小超過了限制上傳的大小
UPLOAD_ERR_NO_FILE:沒有文件被上傳
UPLOAD_ERR_NO_TMP_DIR:找不到臨時目錄
客戶端限制上傳:
我們可以通過隱藏域來實現限制上傳的文件大小,同時可以通過accept來限制上傳的文件的類型,如下所示:
- <form action="uploadFile.php" method="post" accept-charset="utf-8" enctype="multipart/form-data">
- <input type="hidden" name="MAX_FILE_SIZE" value="1024">
- 請選擇要上傳的文件:
- <input type="file" name="myfile" accept="image/png">
- <input type="submit" value="上傳文件">
- </form>
服務端限制上傳:
我們可以通過在服務端來判斷文件類型、文件大小,上傳方式等來判斷是否滿足條件,然后才處理文件!
- define('UPLOAD_PATH', 'Uploads');
- define('MAX_FILE_SIZE', 2 * 1024 * 1024);
- header('Content-type:text/html;Charset=utf-8');
- $name = $_FILES['myfile']['name'];
- $type = $_FILES['myfile']['type'];
- $tmp_name = $_FILES['myfile']['tmp_name'];
- $error = $_FILES['myfile']['error'];
- $size = $_FILES['myfile']['size'];
- $allowExt = array('png', 'jpg', 'jpeg');
- if ($error == UPLOAD_ERR_OK) {
- if ($size > MAX_FILE_SIZE) {
- exit('上傳的文件過大');
- }
- // 取上傳的文件的擴展類型
- $ext = pathinfo($name, PATHINFO_EXTENSION);
- if (!in_array($ext, $allowExt)) {
- exit('非法文件類型');
- }
- if (!is_uploaded_file($tmp_name)) {
- exit('文件不是HTTP POST上傳過來的');
- }
- if (move_uploaded_file($tmp_name, UPLOAD_PATH . '/' . $name)) {
- echo '文件上傳成功';
- } else {
- echo "文件上傳失敗";
- }
- } else {
- // 上傳到服務器就已經出錯了
- var_dump($error);
- }
忽略文件重名之類的問題,那些需要額外添加一些小處理哦!
二,上傳文件類
- ini_set('display_errors', 'On');
- error_reporting(E_ALL);
- header('Content-type:text/html;Charset=utf-8');
- /**
- * Class for Uploading a single image
- */
- class Upload {
- protected $fileName; /* eg, $_FILES['file'], the name is file. */
- protected $allowExt; /* Allow extension for uploading a file */
- protected $allowMIMEType; /* Allow uploading file mine types */
- protected $fileMaxSize; /* Limit a uploading file size */
- protected $uploadPath; /* The destination path */
- protected $isImageFlag; /* Note that file is an image or not. */
- protected $errorMessage;
- protected $fileExt;
- protected $fileInfos;
- protected $fileUniqueName;
- protected $fileDestPath;
- public function __construct($fileName = 'file', $uploadPath = './Uploads', $isImageFlag = true, $fileMaxSize = 1048576, $allowExt = array('png', 'jpg', 'jpeg', 'gif'), $allowMIMEType = array('image/png', 'image/jpeg', 'image/gif')) {
- $this->fileName = $fileName;
- $this->allowExt = $allowExt;
- $this->allowMIMEType = $allowMIMEType;
- $this->uploadPath = $uploadPath;
- $this->isImageFlag = $isImageFlag;
- $this->fileMaxSize = $fileMaxSize;
- // print_r($_FILES);
- $this->fileInfos = $_FILES[$fileName];
- }
- public function uploadFile() {
- if ($this->isValidExt()
- && $this->isValidMIMEType()
- && $this->isValidFileSize()
- && $this->isRealImage()
- && $this->isHTTPPOST()
- && !$this->hasError()) {
- $this->isUploadPathExist();
- $this->fileUniqueName = $this->getUniqueName();
- $this->fileDestPath = $this->uploadPath . '/' . $this->fileUniqueName . '.' . $this->fileExt;
- // echo iconv('gb2312', 'UTF-8', $this->fileDestPath);
- if (@move_uploaded_file($this->fileInfos['tmp_name'], $this->fileDestPath)) {
- return $this->fileDestPath;
- } else {
- $this->errorMessage = '文件上傳失敗';
- }
- } else {
- $this->errorMessage = '文件上傳失敗';
- }
- exit('<span style="color:red">'.$this->errorMessage.'</span>');
- }
- protected function hasError() {
- $ret = true;
- if (!is_null($this->fileInfos)) {
- switch ($this->fileInfos['error']) {
- case UPLOAD_ERR_INI_SIZE:
- $this->errorMessage = '文件大小超過PHP.ini文件中upload_max_filesize';
- break;
- case UPLOAD_ERR_FORM_SIZE:
- $this->errorMessage = '文件大小超過了表單中MAX_FILE_SIZE設置的值';
- break;
- case UPLOAD_ERR_NO_TMP_DIR:
- $this->errorMessage = '找不到臨時文件目錄';
- break;
- case UPLOAD_ERR_NO_FILE:
- $this->errorMessage = '沒有選擇任何文件上傳';
- break;
- case UPLOAD_ERR_CANT_WRITE:
- $this->errorMessage = '文件不可寫';
- break;
- case UPLOAD_ERR_PARTIAL:
- $this->errorMessage = '只有部分文件被上傳';
- break;
- case UPLOAD_ERR_EXTENSION:
- $this->errorMessage = '文件上傳過程中被PHP擴展程序中斷';
- break;
- default:
- $this->errorMessage = '';
- $ret = false;
- }
- } else {
- $this->errorMessage = '文件上傳出錯';
- }
- return $ret;
- }
- protected function isValidFileSize() {
- if ($this->fileInfos['size'] > $this->fileMaxSize) {
- $this->errorMessage = '文件太大';
- return false;
- }
- return true;
- }
- protected function isValidExt() {
- $ext = pathinfo($this->fileInfos['name'], PATHINFO_EXTENSION);
- if (!in_array($ext, $this->allowExt)) {
- $this->errorMessage = '不支持的文件類型';
- return false;
- }
- $this->fileExt = $ext;
- return true;;
- }
- protected function isValidMIMEType() {
- $type = $this->fileInfos['type'];
- if (!in_array($type, $this->allowMIMEType)) {
- $this->errorMessage = '不支持的文件MIME類型';
- return false;
- }
- return true;
- }
- protected function isHTTPPOST() {
- if (!is_uploaded_file($this->fileInfos['tmp_name'])) {
- $this->errorMessage = '文件不是通過HTTP POST傳上來的';
- return false;
- }
- return true;
- }
- protected function isRealImage() {
- if ($this->isImageFlag && !getimagesize($this->fileInfos['tmp_name'])) {
- $this->errorMessage = '文件不是圖片';
- return false;
- }
- return true;
- }
- protected function isUploadPathExist() {
- if (!file_exists($this->uploadPath)) {
- mkdir($this->uploadPath, 0777, true);
- }
- }
- protected function getUniqueName() {
- return md5(microtime(true), true);
- }
- }
- $upload = new Upload('myfile');
- if ($upload->uploadFile()) {
- echo "文件上傳成功";
- }
新聞熱點
疑難解答