我被这个问题困扰了整整3天。当我上传一个图像到php它给了我一个错误未定义的索引:文件。
我读了很多其他的问题,我确保我有enctype="multipart/form-data"在我的表单标签,我确保每个图像名称有名称="file[]",但没有运气,但当我尝试做html和php在一个单一的文件,一切工作完美。但是当我从html中分离php时,它就停止工作了。
不应该有任何问题在php方面,因为我可以得到它的工作,如果html是在php。
Html <form enctype="multipart/form-data" id="submitform" class="form-horizontal" action="submitlisting.php" method='post' >
<p id="result"></p>
<span class="btn btn-file"><input type="file" name="file[]" id="file[]"></span>
<a href="#" id="remove" class="btn fileupload-exists" data-dismiss="fileupload">Remove</a>
<button id="submit" type="submit" value="Submit" name="submit" class="btn btn-success" style="width:100px;">Submit</button>
</div>
</div>
</form>
Php: <?php
ini_set('display_errors', 1); error_reporting(E_ALL);
ob_start();
session_start();
include 'connect.php';
$username=$_SESSION['username'];
$userid=$_SESSION['id'];
for($i=0;$i<count($_FILES["file"]["name"]);$i++)
{
$supported_image = array(
'gif',
'jpg',
'jpeg',
'png');
$path = $_FILES["file"]["name"][$i];
$ext = strtolower(pathinfo($path, PATHINFO_EXTENSION));
if ((!in_array($ext, $supported_image) )&&($_FILES["file"]["size"][$i] > 1000000))
echo "Picture[$i]". "either empty or File format incorrect, You can change the pictures later<br>";
else{
if ($_FILES["file"]["error"][$i] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"][$i] . "<br>";
}
else
{
echo "Upload: " . $_FILES["file"]["name"][$i] . "<br>";
echo "Size: " . ($_FILES["file"]["size"][$i] / 1024) . " kB<br>";
echo "Temp file: " . $_FILES["file"]["tmp_name"][$i] . "<br>";
echo "<br>";
if (file_exists("rentaid.info/Bootstraptest/rent" . $_FILES["file"]["name"][$i]))
{
die($_FILES["file"]["name"][$i] . " already exists please add another file, or change the name ");
}
else
{
$photo=$_FILES["file"]["name"][$i];
move_uploaded_file($_FILES["file"]["tmp_name"][$i],
"Bootstraptest/rent/$photo");
echo $photo."  added</br>";
mysqli_query($con,"INSERT INTO listingpic (pic,listingid,userid) VALUES
('$photo','$form_insert_id','$userid');") or die(mysqli_error());
echo"Listing added";
}
}
}}
}
?>
它在$File第一次进入php时调用错误,在for循环条件for($i=0;$i<count($_FILES["file"]["name"]);$i++)
调试问题通常会使问题消失。
在php文件中输入以下行:
echo '<pre>';
print_r($_FILES);
echo '</pre>';
这将输出表单中的任何内容。
另外,一个好的编程实践是首先检查从表单获得的值。如果有人没有将文件加载到表单中怎么办?然后,尝试遍历文件将导致错误。
if(isset($_FILES['file'])) {
// do whatever
}
最后,将以下内容更改为实际路径,相对于根-/
action="submitlisting.php"
action="/submitlisting.php"
您很可能在浏览器中打开表单。假设使用一些本地虚拟主机,如'mytest.com'或'localhost' -您的表单在'mytest.com/myform.php'打开,窗体处理程序在'mytest.com/submitlisting.php',窗体的动作属性应该是'/submitlisting.php'。如果脚本在其他地方-将该路径放在那里,相对于站点的根目录。
编辑:
尝试将MAX_FILE_SIZE添加到表单中作为隐藏输入。
要做到这一点,编辑你的HTML部分:<form ...>
<input type="hidden" name="MAX_FILE_SIZE" value="2000000">
...
<input type="file" ..>
在任何实际文件输入字段之前隐藏输入