The previous article introduced you to "How to edit a simple graphing calculator with PHP?》, this article continues to introduce to you how to upload files in PHP? What do we need to pay attention to? It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.
File Upload.
Follow-up questions on file upload.
Realize the reuse of the upload function code: encapsulate the file upload function core
Function: upload files.
Conditions: Conditions are determined.
Information of the file to be uploaded: corresponding array of 5 elements;
1. Is the file type appropriate? Specify the external MIME type.
2. Where are the files stored? Externally specified.
3. File format restrictions (file suffix)? External restrictions.
4. File size limit? Externally specified.
Result: File upload is achieved.
1. Success: The result can be seen later: the path and file name of the file need to be returned (stored to the database).
2. Failure: return false and specify the error reason (reference parameter).
(1) Encapsulate an upload function
First we create a new file, in which we implement file upload (single file)
@param1 array $file," Required. Uploaded file information: - -Dimensional 5-element array (name\tmp_ name\error\size\type)
@param2 array $allow_ _type, allowed. Uploaded MIME type
@param3 string $path, stored path
@param4 string &$error , If the error occurs
@param5 array $allow_ format = array(), Allowed. Uploaded file format
@param6 int $max_ size = 20000 The maximum value allowed to be uploaded
Then continue to write the function code as follows:
In this case, our function is basically defined ,
(2) Determine whether the file is valid
The code is as follows:
function upload_ single($file,$a11ow_ .type, $path, &$error, $al1ow_ format = array(),$max_ _size = 2000000){ //判断文件是否有效 if(!is_ array($file)|| !isset($file[ 'error'])){ 1/文件无效 $error = '不是- 一个有效的.上传文件! '; return false;
(3) Determine whether the file storage path is valid
if(!is_ _dir($path)){ //路径不存在 $error = '文件存储路径不存在! '; return false;
(4) Determine whether there is an error in the process of uploading the file itself: error
switch($file[ 'error']){ case 1: case 2: $error = '文件超出服务器允许大小! '; return false; case 3: $error = '文件. 上传过程中出现问题,只上传一.部分! '; return false; case 4: $error = '用户没有选中要上传的文件! '; return false; case 6: case 7 : $error = '文件保存失败! '; return false;
Recommended study: "PHP Video Tutorial》
The above is the detailed content of How to upload files in PHP? What do we need to pay attention to?. For more information, please follow other related articles on the PHP Chinese website!