search

 

创建一个文件上传表单

 

允许用户从表单上传文件是非常有用的。

请看下面这个供上传文件的 HTML 表单:




enctype ="multipart/form-data" >
Filename: label >
 


form >

body >
html >

请留意如下有关此表单的信息:

标签的 enctype 属性规定了在提交表单时要使用哪种内容类型。在表单需要二进制数据时,比如文件内容,请使用 "multipart/form-data"。

标签的 type="file" 属性规定了应该把输入作为文件来处理。举例来说,当在浏览器中预览时,会看到输入框旁边有一个浏览按钮。

注释:允许用户上传文件是一个巨大的安全风险。请仅仅允许可信的用户执行文件上传操作。

创建上传脚本

"upload_file.php" 文件含有供上传文件的代码:

if ( $_FILES["file"]["error"] > 0)
  {
   echo "Error: " .  $_FILES["file"]["error"] . "
";
  }
else
  {
   echo "Upload: " .  $_FILES["file"]["name"] . "
";
   echo "Type: " .  $_FILES["file"]["type"] . "
";
   echo "Size: " . ( $_FILES["file"]["size"] / 1024) . " Kb
";
   echo "Stored in: " .  $_FILES["file"]["tmp_name"];
  }
?>

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

第一个参数是表单的 input name,第二个下标可以是 "name", "type", "size", "tmp_name" 或 "error"。就像这样:

$_FILES["file"]["name"] - 被上传文件的名称 $_FILES["file"]["type"] - 被上传文件的类型 $_FILES["file"]["size"] - 被上传文件的大小,以字节计 $_FILES["file"]["tmp_name"] - 存储在服务器的文件的临时副本的名称 $_FILES["file"]["error"] - 由文件上传导致的错误代码

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

上传限制

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


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

?>

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

保存被上传的文件

上面的例子在服务器的 PHP 临时文件夹创建了一个被上传文件的临时副本。

这个临时的复制文件会在脚本结束时消失。要保存被上传的文件,我们需要把它拷贝到另外的位置:

if ((( $_FILES["file"]["type"] == "image/gif")
|| ( $_FILES["file"]["type"] == "image/jpeg")
|| ( $_FILES["file"]["type"] == "image/pjpeg"))
&& ( $_FILES["file"]["size"]   {
   if ( $_FILES["file"]["error"] > 0)
    {
     echo "Return Code: " .  $_FILES["file"]["error"] . "
";
    }
   else
    {
     echo "Upload: " .  $_FILES["file"]["name"] . "
";
     echo "Type: " .  $_FILES["file"]["type"] . "
";
     echo "Size: " . ( $_FILES["file"]["size"] / 1024) . " Kb
";
     echo "Temp file: " .  $_FILES["file"]["tmp_name"] . "
";

     if ( file_exists("upload/" .  $_FILES["file"]["name"]))
      {
       echo  $_FILES["file"]["name"] . " already exists. ";
      }
     else
      {
       move_uploaded_file( $_FILES["file"]["tmp_name"],
      "upload/" .  $_FILES["file"]["name"]);
       echo "Stored in: " . "upload/" .  $_FILES["file"]["name"];
      }
    }
  }
else
  {
   echo "Invalid file";
  }
?>

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

注释:这个例子把文件保存到了名为 "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
Working with Flash Session Data in LaravelWorking with Flash Session Data in LaravelMar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

PHP Logging: Best Practices for PHP Log AnalysisPHP Logging: Best Practices for PHP Log AnalysisMar 10, 2025 pm 02:32 PM

PHP logging is essential for monitoring and debugging web applications, as well as capturing critical events, errors, and runtime behavior. It provides valuable insights into system performance, helps identify issues, and supports faster troubleshoot

cURL in PHP: How to Use the PHP cURL Extension in REST APIscURL in PHP: How to Use the PHP cURL Extension in REST APIsMar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

Simplified HTTP Response Mocking in Laravel TestsSimplified HTTP Response Mocking in Laravel TestsMar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

12 Best PHP Chat Scripts on CodeCanyon12 Best PHP Chat Scripts on CodeCanyonMar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Explain the concept of late static binding in PHP.Explain the concept of late static binding in PHP.Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

Customizing/Extending Frameworks: How to add custom functionality.Customizing/Extending Frameworks: How to add custom functionality.Mar 28, 2025 pm 05:12 PM

The article discusses adding custom functionality to frameworks, focusing on understanding architecture, identifying extension points, and best practices for integration and debugging.

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)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor