search
HomeBackend DevelopmentPHP TutorialPHP上传文件超过文件最大限制罗致无法上传成功

PHP上传文件超过文件最大限制导致无法上传成功

     最近在学习《HeadFirst PHP & MySQL》一书的第5章“使用存储在文件中的数据”,做一个文件上传的应用时,出现了错误,就是文件无法成功上传。这个问题困扰了我很久,不过还好最后终于解决了。原因是我上传的图片文件大小超过了HTML 表单中MAX_FILE_SIZE 选项指定的值32768Bytes即32KB导致无法上传成功。

    我使用了XAMPP(Apache + MySQL + PHP + Perl)集成开发包和Zend Studio 10.6作为PHP IDE开发环境,另外关于PHP调试我采用了XDebug,在Zend Studio10.6中配置Xdebug的PHP调试环境我参考了博文Zend Studio 10.5 与 XDebug 调试| Zend Debugger 说明 Drupal 源代码 (一)一文。

      相应的文件上传示例PHP代码addscore.php如下:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"><head>  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />  <title>Guitar Wars - Add Your High Score</title>  <link rel="stylesheet" type="text/css" href="style.css" /></head><body>  <h2 id="Guitar-Wars-Add-Your-High-Score">Guitar Wars - Add Your High Score</h2><?php  require_once &#39;appvars.php&#39;;  require_once &#39;connectvars.php&#39;;		  if (isset($_POST[&#39;submit&#39;])) {    // Grab the score data from the POST    $name = $_POST[&#39;name&#39;];    $score = $_POST[&#39;score&#39;];    $screenshot = $_FILES[&#39;screenshot&#39;][&#39;name&#39;];        if (!empty($name) && !empty($score) && !empty($screenshot)) {      // Move the file to the target upload folder      $target = GW_UPLOADPATH . $screenshot;      echo json_encode($_FILES);            if (move_uploaded_file($_FILES[&#39;screenshot&#39;][&#39;tmp_name&#39;], $target)) {       	// Connect to the database		$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) 		    or die(&#39;Error Connecting to MySQL Database!&#39;);		// Write the data to the database		$query = "INSERT INTO guitarwars VALUES (0, NOW(), &#39;$name&#39;, &#39;$score&#39;,&#39;$screenshot&#39;)";		mysqli_query($dbc, $query) or die(&#39;Error querying database;&#39;);		// Confirm success with the user		echo &#39;<p>Thanks for adding your new high score!</p>&#39;;		echo &#39;<p><strong>Name:</strong> &#39; . $name . &#39;<br />&#39;;		echo &#39;<strong>Score:</strong> &#39; . $score;		echo &#39;<img src="/static/imghwm/default1.png"  data-src="/img/2014/07/09/143017574.jpg"  class="lazy" alt="Score image" /></p>&#39;;		echo &#39;<p><a href="index.php"><< Back to high scores</a></p>&#39;;		// Clear the score data to clear the form		$name = "";		$score = "";		$screenshot = "";		mysqli_close($dbc);      }    }    else {      echo &#39;<p class="error">Please enter all of the information to add your high score.</p>&#39;;    }  }?>  <hr />  <form method="post" enctype="multipart/form-data" action="<?php echo $_SERVER[&#39;PHP_SELF&#39;]; ?>">  	<input type="hidden" name="MAX_FILE_SIZE" value="32768" />    <label for="name">Name:</label>    <input type="text" id="name" name="name" value="<?php if (!empty($name)) echo $name; ?>" /><br />    <label for="score">Score:</label>    <input type="text" id="score" name="score" value="<?php if (!empty($score)) echo $score; ?>" /><br />    <label for="screeshot">ScreenShot</label>    <input type="file" id="screenshot" name="screenshot" />    <hr />    <input type="submit" value="Add" name="submit" />  </form></body> </html>

在使用Zend Sutdio10.6设置断点并调试上面这段PHP代码时我发现“if (move_uploaded_file($_FILES['screenshot']['tmp_name'], $target)) {”这行代码里面的代码块没有执行,于是查看了超全局变量$_FILES['screenshot']['tmp_name']的值为空,然后我在这行代码前以JSON格式打印出$_FILES变量的值,如下:
{"screenshot":{"name":"Penguins.jpg","type":"","tmp_name":"","error":2,"size":0}}

相应的运行截图如下:


然后我查询$_FILES['screenshot']['error']为2,上网查询了一下,关于$_FILES超级全局变量的介绍大体如下:

PHP编程语言中的常见的$_FILES系统函数用法有:
$_FILES['myFile']['name'] 显示客户端文件的原名称。
$_FILES['myFile']['type'] 文件的 MIME 类型,例如"image/gif"。
$_FILES['myFile']['size'] 已上传文件的大小,单位为字节。
$_FILES['myFile']['tmp_name'] 储存的临时文件名,一般是系统默认。
$_FILES['myFile']['error'] 该文件上传相关的错误代码。以下为不同代码代表的意思:
0:文件上传成功。
1:超过了文件大小php.ini中即系统设定的大小。
2:超过了文件大小
MAX_FILE_SIZE 选项指定的值。
3;:文件只有部分被上传。
4:没有文件被上传。
5:上传文件大小为0。

另外,查询PHP参考手册关于move_uploaded_file函数的介绍如下:

move_uploaded_file(PHP 4 >= 4.0.3, PHP 5)move_uploaded_file — 将上传的文件移动到新位置说明bool move_uploaded_file ( string $filename , string $destination )本函数检查并确保由 filename 指定的文件是合法的上传文件(即通过 PHP 的 HTTP POST 上传机制所上传的)。如果文件合法,则将其移动为由 destination 指定的文件。 这种检查显得格外重要,如果上传的文件有可能会造成对用户或本系统的其他用户显示其内容的话。 参数filename上传的文件的文件名。 destination移动文件到这个位置。 返回值成功时返回 TRUE。 如果 filename 不是合法的上传文件,不会出现任何操作, move_uploaded_file() 将返回 FALSE。 如果 filename 是合法的上传文件,但出于某些原因无法移动,不会出现任何操作, move_uploaded_file() 将返回 FALSE。此外还会发出一条警告。 

范例

Example #1 Uploading multiple files

<?php$uploads_dir = &#39;/uploads&#39;;foreach ($_FILES["pictures"]["error"] as $key => $error) {    if ($error == UPLOAD_ERR_OK) {        $tmp_name = $_FILES["pictures"]["tmp_name"][$key];        $name = $_FILES["pictures"]["name"][$key];        move_uploaded_file($tmp_name, "$uploads_dir/$name");    }}?> 
原因终于找到了,是因为我上传了一个超过32768Bytes即32KB大小的Penguins.jpg文件导致出现$_FILES['screenshot']['error']为2的错误,并且$_FILES['screenshot']['tmp_name']为空,move_uploaded_file($_FILES['screenshot']['tmp_name'], $target)函数调用时返回FALSE,if (move_uploaded_file($_FILES['screenshot']['tmp_name'], $target)) { 
  ...
 }代码块没有执行。



     

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 Current Status: A Look at Web Development TrendsPHP's Current Status: A Look at Web Development TrendsApr 13, 2025 am 12:20 AM

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

PHP vs. Other Languages: A ComparisonPHP vs. Other Languages: A ComparisonApr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and FunctionalityPHP vs. Python: Core Features and FunctionalityApr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP: A Key Language for Web DevelopmentPHP: A Key Language for Web DevelopmentApr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP: The Foundation of Many WebsitesPHP: The Foundation of Many WebsitesApr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

Beyond the Hype: Assessing PHP's Role TodayBeyond the Hype: Assessing PHP's Role TodayApr 12, 2025 am 12:17 AM

PHP remains a powerful and widely used tool in modern programming, especially in the field of web development. 1) PHP is easy to use and seamlessly integrated with databases, and is the first choice for many developers. 2) It supports dynamic content generation and object-oriented programming, suitable for quickly creating and maintaining websites. 3) PHP's performance can be improved by caching and optimizing database queries, and its extensive community and rich ecosystem make it still important in today's technology stack.

What are Weak References in PHP and when are they useful?What are Weak References in PHP and when are they useful?Apr 12, 2025 am 12:13 AM

In PHP, weak references are implemented through the WeakReference class and will not prevent the garbage collector from reclaiming objects. Weak references are suitable for scenarios such as caching systems and event listeners. It should be noted that it cannot guarantee the survival of objects and that garbage collection may be delayed.

Explain the __invoke magic method in PHP.Explain the __invoke magic method in PHP.Apr 12, 2025 am 12:07 AM

The \_\_invoke method allows objects to be called like functions. 1. Define the \_\_invoke method so that the object can be called. 2. When using the $obj(...) syntax, PHP will execute the \_\_invoke method. 3. Suitable for scenarios such as logging and calculator, improving code flexibility and readability.

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尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment