我尝试在PHP中创建上传脚本。我收到此错误消息:
Notice: Undefined index: file in path\upload\index.php on line 3
这是我的表格(非常基本):
<form action="upload" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="fileUpload">
<input type="submit" value="Upload Image" name="submitt">
</form>
这是我的(不工作)上传脚本:
<?php
$name = $_FILES['file']['name'];
$temp_name = $_FILES['file']['tmp_name'];
if(isset($name)){
if(!empty($name)){
$location = '../data/';
if(move_uploaded_file($temp_name, $location.$name)){
echo 'File uploaded successfully';
}
}
} else {
echo 'You should select a file to upload !!';
}
?>
这是我的php.ini配置:
; Whether to allow HTTP file uploads.
; http://php.net/file-uploads
file_uploads=On
; Maximum allowed size for uploaded files.
; http://php.net/upload-max-filesize
upload_max_filesize=40M
; Maximum number of files that can be uploaded via a single request
max_file_uploads=20
; Maximum size of POST data that PHP will accept.
; Its value may be 0 to disable the limit. It is ignored if POST data reading
; is disabled through enable_post_data_reading.
; http://php.net/post-max-size
post_max_size=50M
那我做错了什么。我查看了之前提出的所有问题,但未找到答案。
编辑1:
签出this并更改我的代码后问题仍然存在。
<?php
if (isset($_POST['submitt'])) {
if (isset($_FILES['file']) && isset($_FILES['file']['name']) && isset($_FILES['file']['tmp_name'])) {
$name = $_FILES['file']['name'];
$temp_name = $_FILES['file']['tmp_name'];
if(!empty($name)){
$location = '../data/';
if(move_uploaded_file($temp_name, $location.$name)){
echo 'File uploaded successfully';
}
} else {
echo 'You should select a file to upload !!';
}
}
}
?>
编辑2:
我发现了问题:用upload
替换操作upload/index.php
解决了问题。我在我的本地机器上使用XAMPP来测试我的代码。由于XAMPP本身的Apache配置不正确,这是一个错误。
答案 0 :(得分:0)
在“上传”逻辑中,您需要确保在声明值之前已提交表单。否则,它试图用一个尚不存在的值设置变量;
<?php
//ensures the form was submitted before declaring variable values
if (isset($_POST['submitt']) {
$name = $_FILES['file']['name'];
$temp_name = $_FILES['file']['tmp_name'];
if(isset($name)){
if(!empty($name)){
$location = '../data/';
if(move_uploaded_file($temp_name, $location.$name)){
echo 'File uploaded successfully';
}
}
} else {
echo 'You should select a file to upload !!';
}
}
?>
其次,更改您的表单代码,以便“操作”是自己的(在这种情况下,我们将action=""
留空):
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="fileUpload">
<input type="submit" value="Upload Image" name="submitt">
</form>
答案 1 :(得分:0)
当用户提交表单并且没有选择文件来上传您的全局变量(数组)时,$_FILES
将没有项目file
,因此您有此错误,并且您必须检查是否密钥可用,如下:
if (isset($_FILES['file']) && isset($_FILES['file']['name']) && isset($_FILES['file']['tmp_name'])) {
// Now you have strict and robust code!
$name = $_FILES['file']['name'];
$temp_name = $_FILES['file']['tmp_name'];
// Rest of your code ...
}