当前位置:网站首页>Implementation of simple upload function in PHP development
Implementation of simple upload function in PHP development
2022-07-28 05:05:00 【A dream against the sky】
The first 1 Chapter PHP Development of simple upload function
1.1 PHP Upload principle and implementation of file upload
file.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> Upload files </title>
</head>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
Please select the file to upload :<br>
<input type="file" name="myFile"><br>
<input type="submit" value=" Upload ">
</form>
</body>
</html>
upload.php:
<?php
header("content-type:text/html;charset=utf-8");
// File upload processing program
// $_FILES File upload variables
//echo "<pre>";
//var_dump($_FILES);
//exit();
//echo "</pre>";
// Handling upload files
$filename = $_FILES['myFile']['name'];
$type = $_FILES['myFile']['type'];
$tmp_name = $_FILES['myFile']['tmp_name'];
$size = $_FILES['myFile']['size'];
$error = $_FILES['myFile']['error'];
// Move the temporary files on the server to the specified location
move_uploaded_file($tmp_name, "upload/".$filename); // Folders should be created in advance
// Check according to our errors or report to the user directly
if ($error == 0) {
echo " Upload successful !!";
} else {
switch ($error) {
case 1:
echo " Exceeded the maximum upload file , Please upload 2M The following documents !";
break;
case 2:
echo " Too many uploaded files !";
break;
case 3:
echo " The file has not been uploaded !";
break;
case 4:
echo " No upload file selected !";
break;
case 5:
echo " The upload file is 0!";
break;
}
}
?>
1.2 PHP Realize the upload limit of file upload
file2.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> Upload files ( Client limitations )</title>
</head>
<body>
<form action="upload2.php" method="post" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="101321">
Please select the file to upload :
<input type="file" name="myFile" accept="image/jpeg,image/gif,text/html"><br>
<input type="submit" value=" Upload ">
</form>
</body>
</html>
upload2.php:
<?php
header('content-type:text/html;charset=utf-8');
// Receive the file , Temporary file information
$file_info = $_FILES['myFile']; // Dimension reduction operation
$file_name = $file_info['name'];
$tmp_name = $file_info['tmp_name'];
$size = $file_info['size'];
$type = $file_info['type'];
$error = $file_info['error'];
// Set limits on the server side
$maxsize = 10485760; // 10M,10*1024*1024
$allowExt = array('jpeg','jpg','png','gif'); // The types of files allowed to be uploaded ( Extension )
$ext = pathinfo($file_name, PATHINFO_EXTENSION); // Extract the extension of the uploaded file
// Target storage folder
$path = "uploads";
if (!file_exists($path)) {
// If the directory does not exist , Create
mkdir($path, 0777, true); // Create directory
chmod($path, 0777); // Modify file mode , Everyone has read 、 Write 、 Executive authority
}
// Get a unique file name , Prevent overwriting due to the same file name
$uniName = md5(uniqid(microtime(true),true)).".$ext"; // md5 encryption ,uniqid Produce a unique id,microtime Prefix
// Destination file address
$destination = $path."/".$uniName;
// When the file is uploaded successfully , Save to temporary folder , The server starts to judge
if ($error===0) {
if ($size > $maxsize) {
exit(" The upload file is too large !");
}
if (!in_array($ext, $allowExt)) {
exit(" Illegal file type !");
}
if (!is_uploaded_file($tmp_name)) {
exit(" Wrong upload method , Please use post The way !");
}
// Determine whether it is a real picture ( Prevent viruses disguised as pictures
if (!getimagesize($tmp_name)) {
// getimagesize by true Returns an array , Otherwise return to false
exit(" It's not really a picture type !");
}
// move_uploaded_file($tmp_name, "upload/".$file_name);
if (@move_uploaded_file($tmp_name, $destination)) {
// @ Error suppressor , Don't let users see the warning
echo " file ".$file_name." Upload successful !";
} else {
echo " file ".$file_name." Upload failed !";
}
} else {
switch ($error) {
case 1:
echo " The maximum number of uploaded files has been exceeded , Please upload 2M The following documents !";
break;
case 2:
echo " Too many uploaded files , You can only upload files at a time, and it must not exceed 20 individual !";
break;
case 3:
echo " The file was not completely uploaded , Please try again !";
break;
case 4:
echo " No upload file selected !";
break;
case 7:
echo " No temporary folders !";
break;
}
}
1.3 PHP Realize the package upload function of file upload
file3.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> Upload files ( Client limitations )</title>
</head>
<body>
<form action="upload3.php" method="post" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="101321">
Please select the file to upload :
<input type="file" name="myFile" accept="image/jpeg,image/gif,text/html"><br>
<input type="submit" value=" Upload ">
</form>
</body>
</html>
file_upload.php:
<?php
function uploadFile ($file_info, $path, $maxsize, $allowExt) {
header('content-type:text/html;charset=utf-8');
// Receive the file , Temporary file information
$file_name = $file_info['name'];
$tmp_name = $file_info['tmp_name'];
$size = $file_info['size'];
$type = $file_info['type'];
$error = $file_info['error'];
// Set limits on the server side
$ext = pathinfo($file_name, PATHINFO_EXTENSION); // Extract the extension of the uploaded file
// Target storage folder
if (!file_exists($path)) {
// If the directory does not exist , Create
mkdir($path, 0777, true); // Create directory
chmod($path, 0777); // Modify file mode , Everyone has read 、 Write 、 Executive authority
}
// Get a unique file name , Prevent overwriting due to the same file name
$uniName = md5(uniqid(microtime(true),true)).".$ext"; // md5 encryption ,uniqid Produce a unique id,microtime Prefix
// Destination file address
$destination = $path."/".$uniName;
// When the file is uploaded successfully , Save to temporary folder , The server starts to judge
if ($error===0) {
if ($size > $maxsize) {
exit(" The upload file is too large !");
}
if (!in_array($ext, $allowExt)) {
exit(" Illegal file type !");
}
if (!is_uploaded_file($tmp_name)) {
exit(" Wrong upload method , Please use post The way !");
}
// Determine whether it is a real picture ( Prevent viruses disguised as pictures
if (!getimagesize($tmp_name)) {
// getimagesize by true Returns an array , Otherwise return to false
exit(" It's not really a picture type !");
}
// move_uploaded_file($tmp_name, "upload/".$file_name);
if (@move_uploaded_file($tmp_name, $destination)) {
// @ Error suppressor , Don't let users see the warning
echo " file ".$file_name." Upload successful !";
} else {
echo " file ".$file_name." Upload failed !";
}
} else {
switch ($error) {
case 1:
echo " The maximum number of uploaded files has been exceeded , Please upload 2M The following documents !";
break;
case 2:
echo " Too many uploaded files , You can only upload files at a time, and it must not exceed 20 individual !";
break;
case 3:
echo " The file was not completely uploaded , Please try again !";
break;
case 4:
echo " No upload file selected !";
break;
case 7:
echo " No temporary folders !";
break;
}
}
return $destination;
}
upload3.php:
<?php
header('content-type:text/html;charset=utf-8');
// Initialization of related variables
$file_info = $_FILES['myFile']; // Dimension reduction operation
$maxsize = 10485760; // 10M,10*1024*1024
$allowExt = array('jpeg','jpg','png','gif'); // The types of files allowed to be uploaded ( Extension )
$path = "uploads";
// Introduce file upload function
include_once 'file_upload.php';
uploadFile($file_info, $path, $maxsize, $allowExt);
?>
1.4 PHP Realize the uploading of many files
file4.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> Multiple file upload </title>
</head>
<body>
<form action="upload4.php" method="post" enctype="multipart/form-data">
Please select the file to upload :<br>
<input type="file" name="myFile1"><br>
Please select the file to upload :<br>
<input type="file" name="myFile2"><br>
Please select the file to upload :<br>
<input type="file" name="myFile3"><br>
Please select the file to upload :<br>
<input type="file" name="myFile4"><br>
Please select the file to upload :<br>
<input type="file" name="myFile5"><br>
Please select the file to upload :<br>
<input type="file" name="myFile6"><br>
<input type="submit" value=" Upload ">
</form>
</body>
</html>
upload4.php:
<?php
header("content-type:text/html;charset=utf-8");
include_once 'file_upload.php';
// Initialization of related variables
$maxsize = 10485760; // 10M,10*1024*1024
$allowExt = array('jpeg','jpg','png','gif'); // The types of files allowed to be uploaded ( Extension )
$path = "uploads";
foreach ($_FILES as $file_info) {
$file[] = uploadFile($file_info, $path, $maxsize, $allowExt);
}
边栏推荐
- 使用nfpm制作rpm包
- Configuration experiment of building virtual private network based on MPLS
- [internal mental skill] - creation and destruction of function stack frame (C implementation)
- Pipe /createpipe
- Easycvr Video Square snapshot adding device channel offline reason display
- Analysis of the reason why easycvr service can't be started and tips for dealing with easy disk space filling
- How to send and receive reports through outlook in FastReport VCL?
- HDU 1435 stable match
- 【CVPR2022】Lite Vision Transformer with Enhanced Self-Attention
- 【ARXIV2203】CMX: Cross-Modal Fusion for RGB-X Semantic Segmentation with Transformers
猜你喜欢

What is the core value of testing?

Comprehensively analyze the differences between steam and maker Education

C语言ATM自动取款机系统项目的设计与开发

如何在 FastReport VCL 中通过 Outlook 发送和接收报告?

【ARXIV2203】SepViT: Separable Vision Transformer

Real intelligence has been certified by two of the world's top market research institutions and has entered the global camp of excellence

Driving the powerful functions of EVM and xcm, how subwallet enables Boca and moonbeam

Dcgan:deep volume general adaptive networks -- paper analysis

【CPU占用高】software_reporter_tool.exe

Table image extraction based on traditional intersection method and Tesseract OCR
随机推荐
基于MPLS构建虚拟专网的配置实验
Leetcode 15. sum of three numbers
With a monthly salary of 15.5K, he failed to start a business and was heavily in debt. How did he reverse the trend through software testing?
【ARIXV2204】Neighborhood attention transformer
(manual) [sqli labs27, 27a] error echo, Boolean blind injection, filtered injection
[internal mental skill] - creation and destruction of function stack frame (C implementation)
How to quickly locate bugs? How to write test cases?
RT_ Use of thread message queue
CPU and memory usage are too high. How to modify RTSP round robin detection parameters to reduce server consumption?
App test process and test points
猿辅导技术进化论:助力教与学 构想未来学校
Have you ever seen this kind of dynamic programming -- the stock problem of state machine dynamic programming (Part 2)
[paper notes] - low illumination image enhancement - zeroshot - rrdnet Network - 2020-icme
Data security is gradually implemented, and we must pay close attention to the source of leakage
从微服务基本概念到核心组件-通过一个实例来讲解和分析
list indices must be integers or slices, not tuple
Read the paper -- a CNN RNN framework for clip yield prediction
Online sql to XML tool
Testcafe provides automatic waiting mechanism and live operation mode
面试了一位38岁程序员,听说要加班就拒绝了