我得到了未定义的索引:pdf php中的文件错误

时间:2014-03-20 18:30:51

标签: php pdf file-upload

<?php
$allowedExts = array("pdf");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "application/pdf") &&
($_FILES["file"]["size"] < 20000000) 
&& in_array($extension, $allowedExts)))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 20000000) . " kB<br>";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";

if (file_exists("upload/" . $_FILES["file"]["name"]))
  {
  echo $_FILES["file"]["name"] . " already exists. ";
  }
else
  {
  move_uploaded_file($_FILES["file"]["tmp_name"],
  "upload/" . $_FILES["file"]["name"]);
  echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
  }
  }
  }
  else
  {
  echo "Invalid file";
  }
  ?>

我是php的新手,正在学习pdf上传。有人可以知道我的代码有什么问题。我一直在研究。非常感谢你

  <form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post"
  enctype="multipart/form-data">
  <label for="file">Filename:</label>
  <input type="file" name="file" id="file"><br>
  <input type="submit" name="submit" value="Submit">
  </form>

这是我的表格,请有人帮助我,我现在有点困惑。

1 个答案:

答案 0 :(得分:0)

问题是,您发布的是实际生成html的同一文件。

因此,当您第一次生成html时,您没有任何已发布的值,因此脚本会向您抛出此错误。

试试这个:

<?php
if(isset($_FILES['file']){
    upload_file();
}else{
?>
<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file"><br>
<input type="submit" name="submit" value="Submit">
</form>

<?php    
}
function upload_file(){
$allowedExts = array("pdf");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "application/pdf") &&
($_FILES["file"]["size"] < 20000000) 
&& in_array($extension, $allowedExts)))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 20000000) . " kB<br>";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";

if (file_exists("upload/" . $_FILES["file"]["name"]))
  {
  echo $_FILES["file"]["name"] . " already exists. ";
  }
else
  {
  move_uploaded_file($_FILES["file"]["tmp_name"],
  "upload/" . $_FILES["file"]["name"]);
  echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
  }
  }
  }
  else
  {
  echo "Invalid file";
  }
}
  ?>