search
HomeBackend DevelopmentPHP TutorialPHP 文件上传表单 学习笔记

PHP文件上传
通过PHP,可以把文件上传到服务器。
-------------------------------------------------------------------------------------------------------------------
创建一个文件上传表单:允许用户从表单上传文件时非常有用的;

下面是一个供上传文件的html表单:




标签的enctype属性规定了在提交表单时要使用那种内容类型。在表单需要二进制数据时,比如文件内容,请使用"multipart/form-data"。
标签的type="file"属性规定了应该把输入作为文件来处理,。举例来说,当在浏览器中预览时,会看到输入框旁边有一个浏览按钮。

注释: 允许用户上传文件是一个巨大的安全风险。请仅仅允许可信的用户执行文件上的操作。
-------------------------------------------------------------------------------------------------------------------
创建上传脚本:
"upload_file.php" 文件含有供上传文件的代码:

<?php <span style="white-space:pre">	if($_FILES["file"]["error"] > 0) {<span style="white-space:pre">		</span>echo "Upload Error: ". $_FILES["file"]["error"] . "<br>";<span style="white-space:pre">	</span>}else {<span style="white-space:pre">		</span>echo "Upload : ". $_FILES["file"]["name"] . "<br>";<span style="white-space:pre">		</span>echo "Type : ". $_FILES["file"]["type"] . "<br>";<span style="white-space:pre">		</span>echo "Size : ". $_FILES["file"]["size"]/1024 . " kb<br>";<span style="white-space:pre">		</span>echo "Store in : ". $_FILES["file"]["tmp_name"] . "<br>" ;<span style="white-space:pre">	</span>}?>

通过使用PHP的全局数组$_FILES,你可以从客户计算机向远程服务器上传文件。

第一个参数是表单的input name,第二个下表可以是:"name", "type", "size", "tmp_name"或"error". just like this:
$_FILES["file"]["name"] - 被上传文件的名称
$_FILES["file"]["type"] - 被上传文件的类型
$_FILES["file"]["size"] - 被上传文件的大小,以字节计
$_FILES["file"]["tmp_name"] - 存储在服务器的文件的临时副本的名称
$_FILES["file"]["error"] - 由文件上传导致的错误代码

这是一种非常简单文件上传方式。基于安全方面的考虑,您应当增加有关什么用户有权上传文件的限制。

在这个脚本中,我们增加了对文件上传的限制。用户只能上传 .gif 或 .jpeg 文件,文件大小必须小于 20 kb:

<?php <span style="white-space:pre">	if ((($_FILES["file"]["type"] == "image/gif")<span style="white-space:pre">	</span>|| ($_FILES["file"]["type"] == "image/jpeg")<span style="white-space:pre">	</span>|| ($_FILES["file"]["type"] == "image/pjpeg"))<span style="white-space:pre">	</span>&& ($_FILES["file"]["size"] 		if ($_FILES["file"]["error"] > 0) {<span style="white-space:pre">			</span>echo "Error: " . $_FILES["file"]["error"] . "<br>";<span style="white-space:pre">		</span>}else {<span style="white-space:pre">			</span>echo "Upload: " . $_FILES["file"]["name"] . "<br>";<span style="white-space:pre">			</span>echo "Type: " . $_FILES["file"]["type"] . "<br>";<span style="white-space:pre">			</span>echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br>";<span style="white-space:pre">			</span>echo "Stored in: " . $_FILES["file"]["tmp_name"];<span style="white-space:pre">		</span>}<span style="white-space:pre">	</span>}else {<span style="white-space:pre">		</span>echo "Invalid file";<span style="white-space:pre">	</span>}?>

注释:对于 IE,识别 jpg 文件的类型必须是 pjpeg,对于 FireFox,必须是 jpeg。

<?php <span style="white-space:pre">	if ((($_FILES["file"]["type"] == "image/gif")<span style="white-space:pre">	</span>|| ($_FILES["file"]["type"] == "image/jpeg")<span style="white-space:pre">	</span>|| ($_FILES["file"]["type"] == "image/pjpeg"))<span style="white-space:pre">	</span>&& ($_FILES["file"]["size"] 		if ($_FILES["file"]["error"] > 0) {<span style="white-space:pre">			</span>echo "Return Code: " . $_FILES["file"]["error"] . "<br>";<span style="white-space:pre">		</span>}else {<span style="white-space:pre">			</span>echo "Upload: " . $_FILES["file"]["name"] . "<br>";<span style="white-space:pre">			</span>echo "Type: " . $_FILES["file"]["type"] . "<br>";<span style="white-space:pre">			</span>echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br>";<span style="white-space:pre">			</span>echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";<span style="white-space:pre">			</span>if (file_exists("upload/" . $_FILES["file"]["name"])) {<span style="white-space:pre">				</span>echo $_FILES["file"]["name"] . " already exists. ";<span style="white-space:pre">			</span>}else {<span style="white-space:pre">				</span>move_uploaded_file($_FILES["file"]["tmp_name"],<span style="white-space:pre">				</span>"upload/" . $_FILES["file"]["name"]);<span style="white-space:pre">				</span>echo "Stored in: " . "upload/" . $_FILES["file"]["name"];<span style="white-space:pre">			</span>}<span style="white-space:pre">		</span>}<span style="white-space:pre">	</span>}else {<span style="white-space:pre">		</span>echo "Invalid file";<span style="white-space:pre">	</span>}?>

上面的脚本检测了是否已存在此文件,如果不存在,则把文件拷贝到指定的文件夹。

注释:这个例子把文件保存到了名为 "upload" 的新文件夹。
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
Dependency Injection in PHP: Avoiding Common PitfallsDependency Injection in PHP: Avoiding Common PitfallsMay 16, 2025 am 12:17 AM

DependencyInjection(DI)inPHPenhancescodeflexibilityandtestabilitybydecouplingdependencycreationfromusage.ToimplementDIeffectively:1)UseDIcontainersjudiciouslytoavoidover-engineering.2)Avoidconstructoroverloadbylimitingdependenciestothreeorfour.3)Adhe

How to Speed Up Your PHP Website: Performance TuningHow to Speed Up Your PHP Website: Performance TuningMay 16, 2025 am 12:12 AM

ToimproveyourPHPwebsite'sperformance,usethesestrategies:1)ImplementopcodecachingwithOPcachetospeedupscriptinterpretation.2)Optimizedatabasequeriesbyselectingonlynecessaryfields.3)UsecachingsystemslikeRedisorMemcachedtoreducedatabaseload.4)Applyasynch

Sending Mass Emails with PHP: Is it Possible?Sending Mass Emails with PHP: Is it Possible?May 16, 2025 am 12:10 AM

Yes,itispossibletosendmassemailswithPHP.1)UselibrarieslikePHPMailerorSwiftMailerforefficientemailsending.2)Implementdelaysbetweenemailstoavoidspamflags.3)Personalizeemailsusingdynamiccontenttoimproveengagement.4)UsequeuesystemslikeRabbitMQorRedisforb

What is the purpose of Dependency Injection in PHP?What is the purpose of Dependency Injection in PHP?May 16, 2025 am 12:10 AM

DependencyInjection(DI)inPHPisadesignpatternthatachievesInversionofControl(IoC)byallowingdependenciestobeinjectedintoclasses,enhancingmodularity,testability,andflexibility.DIdecouplesclassesfromspecificimplementations,makingcodemoremanageableandadapt

How to send an email using PHP?How to send an email using PHP?May 16, 2025 am 12:03 AM

The best ways to send emails using PHP include: 1. Use PHP's mail() function to basic sending; 2. Use PHPMailer library to send more complex HTML mail; 3. Use transactional mail services such as SendGrid to improve reliability and analysis capabilities. With these methods, you can ensure that emails not only reach the inbox, but also attract recipients.

How to calculate the total number of elements in a PHP multidimensional array?How to calculate the total number of elements in a PHP multidimensional array?May 15, 2025 pm 09:00 PM

Calculating the total number of elements in a PHP multidimensional array can be done using recursive or iterative methods. 1. The recursive method counts by traversing the array and recursively processing nested arrays. 2. The iterative method uses the stack to simulate recursion to avoid depth problems. 3. The array_walk_recursive function can also be implemented, but it requires manual counting.

What are the characteristics of do-while loops in PHP?What are the characteristics of do-while loops in PHP?May 15, 2025 pm 08:57 PM

In PHP, the characteristic of a do-while loop is to ensure that the loop body is executed at least once, and then decide whether to continue the loop based on the conditions. 1) It executes the loop body before conditional checking, suitable for scenarios where operations need to be performed at least once, such as user input verification and menu systems. 2) However, the syntax of the do-while loop can cause confusion among newbies and may add unnecessary performance overhead.

How to hash strings in PHP?How to hash strings in PHP?May 15, 2025 pm 08:54 PM

Efficient hashing strings in PHP can use the following methods: 1. Use the md5 function for fast hashing, but is not suitable for password storage. 2. Use the sha256 function to improve security. 3. Use the password_hash function to process passwords to provide the highest security and convenience.

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Clair Obscur: Expedition 33 - How To Get Perfect Chroma Catalysts
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft