This article mainly explains how to encapsulate a PHP function for file upload and download, which can be used for the avatar upload function in this demo. By the way, it also explains how to upload multiple files. If you are particularly familiar with file uploading, you can skip this section.
Still using the same interface as before.
addUser.php:
<html><head><metacharset="utf-8"><title>title>head><body><H3>添加管理员H3><FORMaction="doAdminAction.php?act=addUser"method="post"><TABLEwidth="60%"border="1"cellpadding="5"cellspacing="0"bgcolor="#cccccc"><tr><TDalign="right">用户名称TD><TD><inputtype="text"name="username"placeholder="请输入用户名称"/>TD>tr><tr><TDalign="right">用户密码TD><TD><inputtype="text"name="password"placeholder="请输入用户名称"/>TD>tr><tr><TDalign="right">用户邮箱TD><TD><inputtype="text"name="email"placeholder="请输入用户名称"/>TD>tr><tr><tdalign="right">性别td><td><inputtype="radio"name="sex"value="1"checked="checked"/>男 <inputtype="radio"name="sex"value="2" />女 <inputtype="radio"name="sex"value="3" />保密 td>tr><tr><tdalign="right">头像td><td><inputtype="file"name="face" />td>tr><tr><TDcolspan="2"><inputtype="submit"value="添加用户"/>TD>tr>FORM>body>html>
Here is the file directory:
In doAdminAction.php submitted by the form, just addmove_uploaded_file($_FILES["face"]["tmp_name"],
This line of code can place the files uploaded by the client in the corresponding place on the server. But there are some problems with this code
"upload/" . $_FILES["face"]["name"]);
(1) If the upload folder does not exist in the admin, the file cannot be uploaded.
(2) The type of uploaded files is not checked. It will be more dangerous if virus files appear.
(3) If a file with the same name as the file in the upload folder is uploaded, the original file will be replaced.
(4) Some errors that may occur when uploading files are not handled, for example, the file size exceeds 2M (the default upload limit size specified in the php ini file is 2M)
Here is the solution:
(1) First determine whether the uploaded folder exists. If it does not exist, create it
$path="upload/"; //如果路径不存在就建立的路径上 if(!file_exists($path)) { mkdir($path,0777,true); }
(2) Use strtolower(end(explode(“.”, $filename))); to obtain the file extension
Then determine whether the extension is in the required file type.
(3) Use md5(uniqid(microtime(true),true)); to get a unique string concatenated with the previously obtained file extension as the file name of the uploaded file.
(4) Now start writing the code for doAdminAction. The fourth question will be explained in the code.
require_once'../include.php'; //print_r($_FILES["face"]);$path="upload/"; //如果路径不存在就建立的路径上if(!file_exists($path)) { mkdir($path,0777,true); } //允许的类型$allowExt=array("gif","jpeg","png","jpg","wbmp"); $filename=$_FILES["face"]["name"]; $ext=getExt($filename); if(!in_array($ext,$allowExt)){ exit("非法文件类型"); } //得到了唯一的文件名的文件$filename=getUniName().".".$ext; if(move_uploaded_file($_FILES["face"]["tmp_name"], $path.$filename)) { echo"文件上传成功"; } else { switch($_FILES["face"]['error']){ case1: $mes="超过了配置文件上传文件的大小";//UPLOAD_ERR_INI_SIZEbreak; case2: $mes="超过了表单设置上传文件的大小"; //UPLOAD_ERR_FORM_SIZEbreak; case3: $mes="文件部分被上传";//UPLOAD_ERR_PARTIALbreak; case4: $mes="没有文件被上传";//UPLOAD_ERR_NO_FILEbreak; case6: $mes="没有找到临时目录";//UPLOAD_ERR_NO_TMP_DIRbreak; case7: $mes="文件不可写";//UPLOAD_ERR_CANT_WRITE;break; case8: $mes="由于PHP的扩展程序中断了文件上传";//UPLOAD_ERR_EXTENSIONbreak; } echo$mes; } ?>
If any errors occur, they will be printed. Now that the content of single file upload has been explained, now the above code is encapsulated into a function.
functionuploadFile($path="upload/",$allowExt=array("gif","jpeg","png","jpg","wbmp"),$imgFlag=true) {//如果路径不存在就建立的路径上if(!file_exists($path)) { mkdir($path,0777,true); } //允许的类型$filename=$_FILES["face"]["name"]; $ext=getExt($filename); if(!in_array($ext,$allowExt)){ exit("非法文件类型"); } if($imgFlag){ //如何验证图片是否是一个真正的图片类型//getimagesize($filename):验证文件是否是图片类型 正确返回数组错误返回false$info=getimagesize($tmp_name); //var_dump($info);exit;if(!$info){ exit("不是真正的图片类型"); } } //得到了唯一的文件名的文件$filename=getUniName().".".$ext; if(move_uploaded_file($_FILES["face"]["tmp_name"], $path.$filename)) { echo"文件上传成功"; } else { switch($_FILES["face"]['error']){ case1: $mes="超过了配置文件上传文件的大小";//UPLOAD_ERR_INI_SIZEbreak; case2: $mes="超过了表单设置上传文件的大小"; //UPLOAD_ERR_FORM_SIZEbreak; case3: $mes="文件部分被上传";//UPLOAD_ERR_PARTIALbreak; case4: $mes="没有文件被上传";//UPLOAD_ERR_NO_FILEbreak; case6: $mes="没有找到临时目录";//UPLOAD_ERR_NO_TMP_DIRbreak; case7: $mes="文件不可写";//UPLOAD_ERR_CANT_WRITE;break; case8: $mes="由于PHP的扩展程序中断了文件上传";//UPLOAD_ERR_EXTENSIONbreak; } echo$mes; } }
Multiple file uploads are divided into two situations
(1) Multiple single file upload
<html><head><metacharset="utf-8"><title>title>head><body><FORMaction="doAction2.php"method="post"enctype="multipart/form-data"><INPUTtype="hidden"name="MAX_FILE_SIZE"value="1048576"/> 请选择上传文件:<INPUTtype="file"name="myFile1"/><br/> 请选择上传文件:<INPUTtype="file"name="myFile2"/><br/> 请选择上传文件:<INPUTtype="file"name="myFile3"/><br/><inputtype="submit"value="上传"/>FORM>body>html>
This form is equivalent to uploading multiple single files, print_r($_FILES) in doAction2.php; get
Array ( [myFile1] => Array ( [name] => touxiang.jpg [type] => image/jpeg [tmp_name] => D:\xampp\tmp\php79E3.tmp [error] => 0 [size] => 28747 ) [myFile2] => Array ( [name] => 文章.png [type] => image/png [tmp_name] => D:\xampp\tmp\php7A03.tmp [error] => 0 [size] => 11655 ) [myFile3] => Array ( [name] => 增加.png [type] => image/png [tmp_name] => D:\xampp\tmp\php7A04.tmp [error] => 0 [size] => 7439 ) )
(2) Multiple file upload
<html><head><metacharset="utf-8"><title>title>head><body><FORMaction="doAction2.php"method="post"enctype="multipart/form-data"><INPUTtype="hidden"name="MAX_FILE_SIZE"value="1048576"/> 请选择上传文件:<INPUTtype="file"name="myFile[]"/><br/> 请选择上传文件:<INPUTtype="file"name="myFile[]"/><br/> 请选择上传文件:<INPUTtype="file"name="myFile[]"/><br/><inputtype="submit"value="上传"/>FORM>body>html>
Similarly print_r( $_files)
Array ( [myFile] => Array ( [name] => Array ( [0] => touxiang.jpg [1] => 文章.png [2] => 增加.png ) [type] => Array ( [0] => image/jpeg [1] => image/png [2] => image/png ) [tmp_name] => Array ( [0] => D:\xampp\tmp\php1EC.tmp [1] => D:\xampp\tmp\php1ED.tmp [2] => D:\xampp\tmp\php1EE.tmp ) [error] => Array ( [0] => 0 [1] => 0 [2] => 0 ) [size] => Array ( [0] => 28747 [1] => 11655 [2] => 7439 ) ) )
found that there are many differences in the arrays obtained by the two methods.
For the first case (equivalent to a file array) we can
foreach ($_FILESas$var) { //对于每一个文件进行了文件上传操作$info=uploadFile($var); echo$info; }
For the second case we can convert the three-dimensional array shown into the two-dimensional array shown in the first case.
foreach($_FILES[myFile][name] as $key=>$var ) { $files[$key][name]=$_FILES[myFile][name][$key]; $files[$key][type]=$_FILES[myFile][type][$key]; $files[$key][tmp_name]=$_FILES[myFile][tmp_name][$key]; $files[$key][error]=$_FILES[myFile][error][$key]; $files[$key][size]=$_FILES[myFile][size][$key]; } print_r($files);
The result
Array ( [0] => Array ( [name] => touxiang.jpg [type] => image/jpeg [tmp_name] => D:\xampp\tmp\php3227.tmp [error] => 0 [size] => 28747 ) [1] => Array ( [name] => 文章.png [type] => image/png [tmp_name] => D:\xampp\tmp\php3228.tmp [error] => 0 [size] => 11655 ) [2] => Array ( [name] => 增加.png [type] => image/png [tmp_name] => D:\xampp\tmp\php3229.tmp [error] => 0 [size] => 7439 ) )
was successful. Now we start to encapsulate a file upload function. This function can handle both single file upload and multiple file upload. Then we just need to write this part of the array processing and call the upload() function.
require_once"../include.php"; //用于转换数组functionbuildInfo() {foreach($_FILESas$file) { $i=0; if(is_string($file['name'])) { $files[$i]=$file; $i++; } else { foreach($file[name] as$key=>$var) { $files[$key][name]=$file[name][$key]; $files[$key][type]=$file[type][$key]; $files[$key][tmp_name]=$file[tmp_name][$key]; $files[$key][error]=$file[error][$key]; $files[$key][size]=$file[size][$key]; } } } return$files; } //用于上传functionuploadFile($path="upload/",$allowExt=array("gif","jpeg","png","jpg","wbmp")) {//如果路径不存在就建立的路径上if(!file_exists($path)) { mkdir($path,0777,true); } $files=buildInfo(); foreach($filesas$file) { //允许的类型$filename=$file["name"]; $ext=getExt($filename); if(!in_array($ext,$allowExt)){ exit("非法文件类型"); } //校验是否是一个真正的图片类型if($imgFlag){ if(!getimagesize($file['tmp_name'])){ exit("不是真正的图片类型"); } } //得到了唯一的文件名的文件$filename=getUniName().".".$ext; if(move_uploaded_file($file["tmp_name"], $path.$filename)) { echo"文件上传成功"; } else { switch($file['error']){ case1: $mes="超过了配置文件上传文件的大小";//UPLOAD_ERR_INI_SIZEbreak; case2: $mes="超过了表单设置上传文件的大小"; //UPLOAD_ERR_FORM_SIZEbreak; case3: $mes="文件部分被上传";//UPLOAD_ERR_PARTIALbreak; case4: $mes="没有文件被上传";//UPLOAD_ERR_NO_FILEbreak; case6: $mes="没有找到临时目录";//UPLOAD_ERR_NO_TMP_DIRbreak; case7: $mes="文件不可写";//UPLOAD_ERR_CANT_WRITE;break; case8: $mes="由于PHP的扩展程序中断了文件上传";//UPLOAD_ERR_EXTENSIONbreak; } echo$mes; } } }
This code also adds a check on whether the uploaded image is in image format and a check on the image size, because some virus files will disguise themselves as image files.
The above introduces the demo of using PHP to complete a user registration and management (php implements the uploading of single files and multiple files), including the relevant content. I hope it will be helpful to friends who are interested in PHP tutorials.