Table of Contents
PHP上传文件时无法上传成功,$_FILES['screenshot']['tmp_name']为空
Guitar Wars - Add Your High Score
范例
Home php教程 php手册 PHP上传文件时无法上传成功,$_FILES['screenshot']['tmp_name']为空

PHP上传文件时无法上传成功,$_FILES['screenshot']['tmp_name']为空

Jun 13, 2016 am 09:28 AM
document

PHP上传文件时无法上传成功,$_FILES['screenshot']['tmp_name']为空

最近在学习《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中配置我参考了博文Zend Studio 10.5 与 XDebug 调试| Zend Debugger 说明 Drupal 源代码 (一)

我的addscore.php的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;];
    
//     echo "name: $name <br />";
//     echo "score: $score <br />";
//     echo "screenShot: $screenshot <br />";

    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;</p>&#39;;
		echo &#39;<p><< Back to high scores</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 />
  
</body> 
</html>
Copy after login

在使用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}}
Copy after login

截图如下:


然后我查询$_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。此外还会发出一条警告。 
Copy after login

范例

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");
    }
}
?> 
Copy after login
原因终于找到了,是因为我上传了一个超过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 of this Website
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

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)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to recover expired WeChat files? Can expired WeChat files be recovered? How to recover expired WeChat files? Can expired WeChat files be recovered? Feb 22, 2024 pm 02:46 PM

Open WeChat, select Settings in Me, select General and then select Storage Space, select Management in Storage Space, select the conversation in which you want to restore files and select the exclamation mark icon. Tutorial Applicable Model: iPhone13 System: iOS15.3 Version: WeChat 8.0.24 Analysis 1 First open WeChat and click the Settings option on the My page. 2 Then find and click General Options on the settings page. 3Then click Storage Space on the general page. 4 Next, click Manage on the storage space page. 5Finally, select the conversation in which you want to recover files and click the exclamation mark icon on the right. Supplement: WeChat files generally expire in a few days. If the file received by WeChat has not been clicked, the WeChat system will clear it after 72 hours. If the WeChat file has been viewed,

Photos cannot open this file because the format is not supported or the file is corrupted Photos cannot open this file because the format is not supported or the file is corrupted Feb 22, 2024 am 09:49 AM

In Windows, the Photos app is a convenient way to view and manage photos and videos. Through this application, users can easily access their multimedia files without installing additional software. However, sometimes users may encounter some problems, such as encountering a "This file cannot be opened because the format is not supported" error message when using the Photos app, or file corruption when trying to open photos or videos. This situation can be confusing and inconvenient for users, requiring some investigation and fixes to resolve the issues. Users see the following error when they try to open photos or videos on the Photos app. Sorry, Photos cannot open this file because the format is not currently supported, or the file

Preparing for removal takes a long time in Windows 11/10 Preparing for removal takes a long time in Windows 11/10 Feb 19, 2024 pm 07:42 PM

In this article, we will introduce how to solve the problem of "Ready to delete" prompt when deleting files or folders in Windows system. This prompt means that the system is performing some background operations, such as checking file permissions, verifying whether the file is occupied by other programs, calculating the size of the item to be deleted, etc. We will provide you with some workarounds to ensure that you can successfully delete your files without waiting too long. Why does Windows take so long to delete files? The time it takes Windows to prepare a file for deletion is affected by a variety of factors, including file size, storage device speed, and background processes. A long or stuck "Preparing to delete" prompt may indicate insufficient system resources, disk errors, or file system issues. exist

Can Tmp format files be deleted? Can Tmp format files be deleted? Feb 24, 2024 pm 04:33 PM

Tmp format files are a temporary file format usually generated by a computer system or program during execution. The purpose of these files is to store temporary data to help the program run properly or improve performance. Once the program execution is completed or the computer is restarted, these tmp files are often no longer necessary. Therefore, for Tmp format files, they are essentially deletable. Moreover, deleting these tmp files can free up hard disk space and ensure the normal operation of the computer. However, before deleting Tmp format files, we need to

How to transfer files from Quark Cloud Disk to Baidu Cloud Disk? How to transfer files from Quark Cloud Disk to Baidu Cloud Disk? Mar 14, 2024 pm 02:07 PM

Quark Netdisk and Baidu Netdisk are currently the most commonly used Netdisk software for storing files. If you want to save the files in Quark Netdisk to Baidu Netdisk, how do you do it? In this issue, the editor has compiled the tutorial steps for transferring files from Quark Network Disk computer to Baidu Network Disk. Let’s take a look at how to operate it. How to save Quark network disk files to Baidu network disk? To transfer files from Quark Network Disk to Baidu Network Disk, you first need to download the required files from Quark Network Disk, then select the target folder in the Baidu Network Disk client and open it. Then, drag and drop the files downloaded from Quark Cloud Disk into the folder opened by the Baidu Cloud Disk client, or use the upload function to add the files to Baidu Cloud Disk. Make sure to check whether the file was successfully transferred in Baidu Cloud Disk after the upload is completed. That's it

Upload failed, file cannot be empty, inconsistent error Upload failed, file cannot be empty, inconsistent error Feb 19, 2024 pm 01:21 PM

Discorde is a popular file sharing platform, but users may encounter errors such as upload failure and file cannot be empty when uploading files. Although there is no clear explanation yet, these errors may appear randomly, preventing certain files from being uploaded, or even preventing the re-uploading of previously sent files. Fixed Upload Failed, File Cannot Be Empty Inconsistency Error It can be frustrating to get a File Cannot Be Empty error when an upload fails. Here are some suggested solutions that we hope will help. Available for iOS and Android users Verifying files Compressing files before sharing them Update/Reinstall Inconsistency 1] Available for iOS and Android users In iPhone and Android users, for file upload fails with error

What to do if the 0x80004005 error code appears. The editor will teach you how to solve the 0x80004005 error code. What to do if the 0x80004005 error code appears. The editor will teach you how to solve the 0x80004005 error code. Mar 21, 2024 pm 09:17 PM

When deleting or decompressing a folder on your computer, sometimes a prompt dialog box &quot;Error 0x80004005: Unspecified Error&quot; will pop up. How should you solve this situation? There are actually many reasons why the error code 0x80004005 is prompted, but most of them are caused by viruses. We can re-register the dll to solve the problem. Below, the editor will explain to you the experience of handling the 0x80004005 error code. Some users are prompted with error code 0X80004005 when using their computers. The 0x80004005 error is mainly caused by the computer not correctly registering certain dynamic link library files, or by a firewall that does not allow HTTPS connections between the computer and the Internet. So how about

What is hiberfil.sys file? Can hiberfil.sys be deleted? What is hiberfil.sys file? Can hiberfil.sys be deleted? Mar 15, 2024 am 09:49 AM

Recently, many netizens have asked the editor, what is the file hiberfil.sys? Can hiberfil.sys take up a lot of C drive space and be deleted? The editor can tell you that the hiberfil.sys file can be deleted. Let’s take a look at the details below. hiberfil.sys is a hidden file in the Windows system and also a system hibernation file. It is usually stored in the root directory of the C drive, and its size is equivalent to the size of the system's installed memory. This file is used when the computer is hibernated and contains the memory data of the current system so that it can be quickly restored to the previous state during recovery. Since its size is equal to the memory capacity, it may take up a larger amount of hard drive space. hiber

See all articles