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 'appvars.php'; require_once 'connectvars.php'; if (isset($_POST['submit'])) { // Grab the score data from the POST $name = $_POST['name']; $score = $_POST['score']; $screenshot = $_FILES['screenshot']['name']; 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['screenshot']['tmp_name'], $target)) { // Connect to the database $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) or die('Error Connecting to MySQL Database!'); // Write the data to the database $query = "INSERT INTO guitarwars VALUES (0, NOW(), '$name', '$score','$screenshot')"; mysqli_query($dbc, $query) or die('Error querying database;'); // Confirm success with the user echo '<p>Thanks for adding your new high score!</p>'; echo '<p><strong>Name:</strong> ' . $name . '<br />'; echo '<strong>Score:</strong> ' . $score; echo '<img src="/static/imghwm/default1.png" data-src="/img/2014/07/09/143017574.jpg" class="lazy" alt="Score image" /></p>'; echo '<p><a href="index.php"><< Back to high scores</a></p>'; // Clear the score data to clear the form $name = ""; $score = ""; $screenshot = ""; mysqli_close($dbc); } } else { echo '<p class="error">Please enter all of the information to add your high score.</p>'; } }?> <hr /> <form method="post" enctype="multipart/form-data" action="<?php echo $_SERVER['PHP_SELF']; ?>"> <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参考手册关于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 = '/uploads';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)) {
...
}代码块没有执行。

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 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 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 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

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.

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.

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.

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.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

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
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
Powerful PHP integrated development environment

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Zend Studio 13.0.1
Powerful PHP integrated development environment