Server configuration and verification related to PHP upload files

1. Server configuration for uploading files in PHP

parameter explain
file_uploads
Switch whether to allow file upload via HTTP, default On
upload_tmp_dir
Files are uploaded to the server where temporary files are stored. If not specified, the system default temporary folder will be used.
upload_max_filesize
The maximum size of files allowed to be uploaded, the default is 2M
post_max_size
The maximum value that can be received via form POST to PHP, including all values ​​in the form, the default is 8M
max_execution_time
The maximum time value (seconds) for each PHP page to run, the default is 30 seconds
max_file_uploads
The maximum number of files allowed to be uploaded in one request, default 20
max_input_nesting_level
Set the nesting depth of input variables, default 64
max_input_time
The maximum time required for each PHP page to receive data, default 60 seconds
max_input_vars
Set the maximum number of input variables, default 2500
memory_limit
The maximum amount of memory occupied by each PHP process. This value must be greater than the file size allowed to be uploaded. The default is 8M.

2. Back-end inspection of file upload

1. Determine whether the file upload method is post form

if(strtolower($_SERVER['REQUEST_METHOD']) == 'post'){

    return json_encode(['code'=>500, 'msg'=>'文件上传必须用POST方式提交']);
}

2. Determine whether the post form submits files

One problem here is that after the server sets the post_max_size parameter, if the uploaded file is larger than this value, the file information cannot be received using the $_FILES function. In this case, you need to use the CONTENT_LENGTH value of the $_SERVER function to determine whether Documents submitted.

if((isset($_SERVER['CONTENT_LENGTH']) && !$_SERVER['CONTENT_LENGTH']) || (empty($_FILES) && $_POST)){

    return json_encode(['code'=>500, 'msg'=>'请导入要上传的文件']);
}

3. Determine whether the size of the file uploaded by the post form exceeds the server configuration parameters

if(empty($_FILES) || (empty($_FILES['file']['tmp_name']) && $_FILES['file']['error'] == 1)){

    return json_encode(['code'=>500, 'msg'=>'上传的文件不能超过'.ini_get('upload_max_filesize')]);
}

4. Determine whether the uploaded file is an empty file with 0 bytes

if(isset($_FILES['file']['size']) && !$_FILES['file']['size']){
 
    return json_encode(['code'=>500, 'msg'=>'上传的文件为空文件']); 
}

5. Determine the type of uploaded file, taking Excel files as an example

$extension = explode(".", $_FILES['file']['name']);
if(!in_array($extension[1], ['xlsx', 'xls'])){

	return json_encode(['code'=>500, 'msg'=>'上传文件的格式有误,必须是Excel文件']); 
}

After completing the above verification, you can read and process the uploaded file. If it is an Excel file, please refer to

Summary of phpexcel import and export operations_phpexcel export_m0_68949064's blog-CSDN blog

Guess you like

Origin blog.csdn.net/m0_68949064/article/details/131207683