php completes file upload according to array and steps
The file content submitted by the form form points to file.php.
We process uploaded files through PHP code in file.php.
We choose a picture named to upload. Assume the name of the picture is: psu.jpg, click to upload.
PHP has prepared a dedicated system function $_FILES for file data. All related data of uploaded files are stored in this system function.
In the PHP file, we print $_FILES to observe the structure of this array:
<?php //var_dump()或print_r() //打印變量的相關(guān)信息,將變量的信息詳細(xì)的展示出來 var_dump($_FILES); ?>
The array structure of the printed result is as follows:
array (size=1) 'file' => array (size=5) //文件名 'name' => string 'psu.jpg' (length=7) //文件的mime類型 'type' => string 'image/jpeg' (length=10) //緩存文件,上傳的圖片即保存在這里 'tmp_name' => string 'E:\wamp\tmp\phpC32A.tmp' (length=23) //錯誤碼,詳見上面錯誤碼介紹 'error' => int 0 //上傳的文件大小 'size' => int 225824
We get the above Array structure.
We can start the file processing process.
The first step is to determine the error code:
<?php if($_FILES['file']['error'] > 0){ switch ($_FILES['file']['error']) { //錯誤碼不為0,即文件上傳過程中出現(xiàn)了錯誤 case '1': echo '文件過大'; break; case '2': echo '文件超出指定大小'; break; case '3': echo '只有部分文件被上傳'; break; case '4': echo '文件沒有被上傳'; break; case '6': echo '找不到指定文件夾'; break; case '7': echo '文件寫入失敗'; break; default: echo "上傳出錯<br/>"; } }else{ //錯誤碼為0,即上傳成功,可以進(jìn)行后續(xù)處理,處理流程見下文 } ?>
The above code introduces the error code and corresponding error in detail. We can Error code to generate accurate error prompts.
The second step is to determine whether the file exceeds the size. In actual projects, due to system hardware limitations and storage device limitations, it is impossible for users to upload files without limit, so we have to limit the size of files uploaded by users. Defining an appropriate limit size can make our application run more stably.
<?php //判斷錯誤 if ($_FILES['file']['error'] > 0) { //有錯誤可停止執(zhí)行 } else { //當(dāng)前上傳文件無誤,運(yùn)行本段代碼 //判斷文件是否超出了指定的大小 //單位為byte $MAX_FILE_SIZE = 100000; if ($_FILES['file']['size'] > $MAX_FILE_SIZE) { //判斷,如果上傳的文件,大小超出了我們給的限制范圍,退上傳并產(chǎn)生錯誤提示 exit("文件超出指定大小"); } } ?>
Define the file size we specify as $MAX_FILE_SIZE. The counting unit of this variable is byte, which corresponds to the $_FILES['file']['size'] size of the uploaded file.
In the sample code, the limit is files with a size of approximately 100K and below.
The third step is to determine whether the mime type of the file is correct.
More often, our file upload function needs to determine whether the files uploaded by users meet the requirements. After uploading unavailable files, the overall display effect of the online application will be affected. , will cause adverse effects. So we need to use the mime type and suffix name to determine whether the file uploaded by the user meets the requirements.
In the following sample code, we assume that the current project requirement is to specify uploaded images, requiring the uploading of files with the suffix GIF or jpg. When the user uploads a file that does not meet the requirements, an error message is returned.
<?php /*判斷后綴名和MIME類型是否符合指定需求 例如: 當(dāng)前項(xiàng)目指定上傳后綴為.jpg或.gif的圖片,則$allowSuffix = array('jpg','gif'); */ //定義允許的后綴名數(shù)組 $myImg = explode('.', $_FILES['file']['name']); /* explode() 將一個字符串用指定的字符切割,并返回一個數(shù)組,這里我們將文件名用'.''切割,結(jié)果存在$myImg中,文件的后綴名即為數(shù)組的最后一個值 */ $myImgSuffix = array_pop($myImg); /* 根據(jù)上傳文件名獲取文件的后綴名 使用in_array()函數(shù),判斷上傳文件是否符合要求 當(dāng)文件后綴名不在我們允許的范圍內(nèi)時退出上傳并返回錯誤信息 */ if(!in_array($myImgSuffix, $allowSuffix)){ exit("文件后綴名不符"); } /* mime類型和文件后綴名的對應(yīng)關(guān)系,我們可以通過很多途徑查詢到,為了避免用戶自主修改文件后綴名造成文件無法使用。 mime類型也必須做出限制檢查mime類型,是為了防止上傳者直接修改文件后綴名 導(dǎo)致文件不可用或上傳的文件不符合要求。 */ //數(shù)組內(nèi)容為允許上傳的mime類型 $allowMime = array( "image/jpg", "image/jpeg", "image/pjpeg", "image/gif" ); if(!in_array($_FILES['file']['type'], $allowMime)){ //判斷上傳文件的mime類型是否在允許的范圍內(nèi) exit('文件格式不正確,請檢查'); //如果不在允許范圍內(nèi),退出上傳并返回錯誤信息 } ?>
The fourth step is to generate the specified path and file name.
According to the file arrangement of the project, the file storage path is generated. In order to avoid errors caused by duplicate file names, a random file name is generated according to a certain format.
<?php //指定上傳文件夾 $path = "upload/images/"; /* 根據(jù)當(dāng)前時間生成隨機(jī)文件名,本行代碼是使用當(dāng)前時間 + 隨機(jī)一個0-9的數(shù)字組合成文件名,后綴即為前面取到的文件后綴名 */ $name = date('Y').date('m').date("d").date('H').date('i').date('s').rand(0,9).'.'.$myImgSuffix; ?>
The fifth step is to determine whether the file is uploaded.
The is_uploaded_file() function is a dedicated function to determine whether the target file is an uploaded file.
<?php //使用is_uploaded_file()判斷是否是上傳文件,函數(shù)介紹見上文 if(is_uploaded_file($_FILEs['file']['tmp_name'])){ } ?>
The sixth step is to move the file to the specified location.
Use the move_uploaded_file() function to move the file to the specified location and name it. It should be noted that the Linux system has permissions for the target directory and whether the disk space is sufficient, otherwise the upload operation will fail.
<?php /* 使用move_uploaded_file()移動上傳文件至指定位置,第一個參數(shù)為上傳文件,第二個參數(shù)為我們在前面指定的上傳路徑和名稱。 */ if(move_uploaded_file($_FILEs['file']['tmp_name'], $path.$name)){ //提示文件上傳成功 echo "上傳成功"; }else{ /* 文件移動失敗,檢查磁盤是否有足夠的空間,或者linux類系統(tǒng)中文件夾是否有足夠的操作權(quán)限 */ echo '上傳失敗'; } }else{ echo '不是上傳文件'; } } ?>
We organize this file fragment into a whole file:
<?php if ($_FILES['file']['error'] > 0) { switch ($_FILES['file']['error']) { //錯誤碼不為0,即文件上傳過程中出現(xiàn)了錯誤 case '1': echo '文件過大'; break; case '2': echo '文件超出指定大小'; break; case '3': echo '只有部分文件被上傳'; break; case '4': echo '文件沒有被上傳'; break; case '6': echo '找不到指定文件夾'; break; case '7': echo '文件寫入失敗'; break; default: echo "上傳出錯<br/>"; } } else { $MAX_FILE_SIZE = 100000; if ($_FILES['file']['size'] > $MAX_FILE_SIZE) { exit("文件超出指定大小"); } $allowSuffix = array( 'jpg', 'gif', ); $myImg = explode('.', $_FILES['file']['name']); $myImgSuffix = array_pop($myImg); if (!in_array($myImgSuffix, $allowSuffix)) { exit("文件后綴名不符"); } $allowMime = array( "image/jpg", "image/jpeg", "image/pjpeg", "image/gif", ); if (!in_array($_FILES['file']['type'], $allowMime)) { exit('文件格式不正確,請檢查'); } $path = "upload/images/"; $name = date('Y') . date('m') . date("d") . date('H') . date('i') . date('s') . rand(0, 9) . '.' . $myImgSuffix; if (is_uploaded_file($_FILEs['file']['tmp_name'])) { if (move_uploaded_file($_FILEs['file']['tmp_name'], $path . $name)) { echo "上傳成功"; } else { echo '上傳失敗'; } } else { echo '不是上傳文件'; } } ?>