search
HomeBackend DevelopmentPHP TutorialUse php to complete common file upload functions

File uploading is very common now. You can upload files, upload avatars, etc. Different browsers have different "file upload" effects.

Let's take a look at the effect of Firefox browser first. :

Use php to complete common file upload functions

Look at the IE browser again:

Use php to complete common file upload functions

There are many other browsers, just Instead of checking the effects one by one, how is this upload achieved?

1. File upload function

(1) The first is to have this upload page

The first is to write the form elements (including the processing page "About The upload has been processed, and some of the rules can be written." There is also the transmission method, and then there is an important attribute. Because it is a file upload, it must have this attribute: enctype="multipart/form-data") and then there is the button. , after the form is determined, it is the content inside. The natural button type for file upload is "file"; then there is the "upload" button. This requires submission, so the button type must be "submit". The code is as follows:

<form action="wenjiansccl.php" method="post" enctype="multipart/form-data">  <!--处理页面起个名字,做文件上传是这个属性:enctype="multipart/form-data"-->
  <input type="file" name="file"/> //浏览文件的按钮
  <input type="submit" value="上传" /> //提交的上传按钮
</form>

Let’s take a look at the effect first:

Use php to complete common file upload functions

(2) The second is the important file upload processing page

We can upload the value and output it first to see what will appear after the file is uploaded. Note that: the value transfer method of the file, you cannot use post or get here, you must use the value transfer method $_FILES[""]

var_dump($_FILES["file"]);  //输出传过来的值

The output result is as shown in the figure:

Use php to complete common file upload functions

Note: Because the information in this picture will be used below, I will start here. A name (array), so that it is not clear when used below

It is not difficult to see several two-dimensional arrays: including the name, type, save location, error message and file size of the file, so that in fact the file It will be temporarily saved on the server.

There are 4 things to note when uploading files:

1. Control the type of uploaded files

2. Control the size of uploaded files

3. Prevent duplicate file names

3.1 Modify the saved file name

3.11 User name + timestamp + random number + file name

3.12 Running water No.

3.2 Use folder

3.21public/lch/2017-2-12/1.jpg

4. Save the file

I know this Four attention items (also equivalent to steps), then just start writing the processing page step by step

(1) When outputting, you can see that one of the items is an "error" item. First of all You can judge whether there is an error in the transmission

if($_FILES["file"]["error"]) //将文件传值到处理页面,找到出错的索引,也就是(array)图中的错误项error
{
  echo $_FILES["file"]["error"];
}

(2) The above is to output the error message if there is an error. If there is no error, proceed to the following content: Start writing according to the precautions

The first thing is: control the type and size of the file when uploading (also find the type and size from the (array) picture, and then assign them the desired type value). We limit the two types of jpeg and png. Kind, or multiple kinds, just write it with "or". Also use an if statement to judge here (if the file type is jpeg or png and the file size is less than 1024000, it can be uploaded, otherwise the upload fails)

if($_FILES["file"]["type"]=="image/jpeg" || $_FILES["file"]["type"]=="image/png" && $_FILES["file"]["size"]<1024000)
{<br>  //注意事项3和4的内容<br>}
else
{
  echo "文件类型不正确!";
}

(3) in Start writing files at the comments in the code (contents of Notes 3 and 4) to avoid duplication and saving

First: Find the saving location of the file (where you want to save it), and then splice the modified file Name method (using timestamp method)

$filesname = "./files/".date("YmdHis").$_FILES["file"]["name"]; //$_FILES["file"]["name"]这也同样的也是(array)图的名称name

Second: Determine whether the file exists (if it exists, it will prompt, if it does not exist, it will save it to the folder)

if(file_exists($filesname)) //file_exists()方法:判断文件是否存在,里面的值就是定义的保存位置
{
  echo "文件已经存在"; //存在给出提示
}
else
{
  //不存在就,保存文件(move_uploaded_file()保存)
  move_uploaded_file($_FILES["file"]["tmp_name"],$filesname);  //里面的值要有当前的保存位置,将要保存到哪的位置
}
<span style="font-family: 宋体; font-size: 15px"><span style="font-size: 18px">注意:</span><br>1.可能上传的时候是UTF-8的编码格式,Windows是用的国标的编码格式,上传上汉子可能成为乱码了,可以在文件保存位置下面加上“转换编码格式”<br>使用的是:</span><span style="font-size: 15px">iconv()方法:</span><span style="font-size: 15px">里面有3个值,一是现在使用的编码格式,二是想要转换的编码格式,三是想要转换的字符串</span>
$filename = iconv("UTF-8","gb2312",$filesname); //这个iconv()里面有3个值,一是现在使用的编码格式,二是想要转换的编码格式,三是想要转化的字符串
<span style="font-family: 宋体; font-size: 15px">2.如果上面的文件的上传格式是篡改的格式,也用move_uploaded_file()方法</span>

This completes the file upload. You can try it out.

2. Upload file preview

When uploading a picture, you will first check the effect before uploading. The next step is the picture preview function

(1) Yes First there is a file button for selecting the file

<input id="uploadImage" type="file" name="photoimage" class="fimg1" onchange="PreviewImage();" /> //对这个按钮加一个事件

(2) A div for displaying this image

<div id="uploadPreview"></div>

for this Add some style to the div

#uploadPreview {
  width: 168px;
  height: 168px;            
  background-position: center center;
  background-size: cover;
  border: 4px solid #fff;
  -webkit-box-shadow: 0 0 0px 0px rgba(0, 0, 0, 0);
  display: inline-block;<br>}

Look at the effect:

Use php to complete common file upload functions

##Then write the event

$("#uploadImage").on("change", function(){
  // 得到一个参考文件列表
  var files = !!this.files ? this.files : [];
  // 如果没有选择任何文件,或者没有文件读到就返回
  if (!files.length || !window.FileReader) return;
  // 只有进行选择的文件是一个形象
  if (/^image/.test( files[0].type)){
    // 创建一个新的FileReader的实例
    var reader = new FileReader();
    // 读取本地文件作为一个DataURL
    reader.readAsDataURL(files[0]);
    // 当加载时,图像数据设置为背景的div
    reader.onloadend = function(){
    $("#uploadPreview").css("background-image", "url("+this.result+")");
    }
  }
});

This is just a simple upload preview. The processing page for uploading to the file has not been written yet. The complete upload image code will be added another day.

See the effect of the selected image

Use php to complete common file upload functions

In this way, the file upload and image preview are over. Combining these two can make the image upload. I will continue to add the complete version later~~~

For more articles related to using PHP to complete common file upload functions, please pay attention to the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP's Purpose: Building Dynamic WebsitesPHP's Purpose: Building Dynamic WebsitesApr 15, 2025 am 12:18 AM

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP: Handling Databases and Server-Side LogicPHP: Handling Databases and Server-Side LogicApr 15, 2025 am 12:15 AM

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

How do you prevent SQL Injection in PHP? (Prepared statements, PDO)How do you prevent SQL Injection in PHP? (Prepared statements, PDO)Apr 15, 2025 am 12:15 AM

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.

PHP and Python: Code Examples and ComparisonPHP and Python: Code Examples and ComparisonApr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP in Action: Real-World Examples and ApplicationsPHP in Action: Real-World Examples and ApplicationsApr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: Creating Interactive Web Content with EasePHP: Creating Interactive Web Content with EaseApr 14, 2025 am 12:15 AM

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

PHP and Python: Comparing Two Popular Programming LanguagesPHP and Python: Comparing Two Popular Programming LanguagesApr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

The Enduring Relevance of PHP: Is It Still Alive?The Enduring Relevance of PHP: Is It Still Alive?Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.