将图像上传到SQL时出现问题

时间:2016-08-23 10:29:59

标签: php html

我在PHP中遇到这些错误:

  

警告:file_get_contents():第97行的C:\ xampp \ htdocs \ myDocs \ mainProject \ upload_page.php中的文件名不能为空

  

警告:getimagesize():第99行的C:\ xampp \ htdocs \ myDocs \ mainProject \ upload_page.php中的文件名不能为空   那不是图像。

这是我的代码:

<div class = "splash container-fluid">
          <form action = "upload_page.php" method = "POST" enctype="multipart/form-data">
         File:
         <input type= "file" name = "image"> <input type= "submit" value = "Upload">

      </form>
         </div>

          <?php
          //connect to database

          mysql_connect("localhost", "root", "") or die(my_sql_error());          
          mysql_select_db("natureall")or die(my_sql_error());        


          //file properties
          $file = $_FILES['image']['tmp_name'];

          if (!isset($file))
          echo "Please select an image";

           else{
              addslashes($image =  file_get_contents($_FILES['image']['tmp_name']));
                $image_name = ($_FILES['image']['name']);
               $image_size = getimagesize($_FILES['image']['tmp_name']);

           }

           if($image_size == FALSE)
               echo "That is not an image";
           else{
              if(! $insert = mysql_query("INSERT INTO photos VALUES ('', 'image_name', '', 'image')"))
                  echo "Problem uploading image";
               else{
                   $lastid = mysql_insert_id();
                   echo "Image uploaded.<p/>Your image:<p/><img src = get.php?id=$lastid";
               }
           }



          ?>

if (!isset($file))
          echo "Please select an image";

部分在选择图像之前不会生成回声,应该不应该。如何在浏览图像之前设置它?

感谢大家的帮助!我快到那里了。数据库中有新记录,但图像名称不仅仅是文本'image_name',而blob只有5b,所以这不对。我从一个Android应用程序添加了这个数据库,其中图像存储在目录中,但我还没有弄清楚如何从网页上做到这一点。这是我的代码,因为它现在支持所有的帮助,尤其是@Martin:

<?php
          //connect to database

          mysql_connect("localhost", "root", "") or die(my_sql_error());          
          mysql_select_db("natureall")or die(my_sql_error());        


          //file properties   


         if($_FILES['image']['error'] == 1){
    echo "The uploaded file exceeds the upload_max_filesize directive in php.ini.";
}
        elseif ($_FILES['image']['error'] == 2){
    echo "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form";
}
        elseif ($_FILES['image']['error'] == 3){
    echo "The uploaded file was only partially uploaded.";
}
         elseif ($_FILES['image']['error'] == 4){
    echo " No file was uploaded.";
}
        elseif ($_FILES['image']['error'] == 5){
    echo " Don't know this one.";
}
        elseif ($_FILES['image']['error'] == 6){
    echo " Missing a temporary folder. Introduced in PHP 5.0.3.";
}
        elseif ($_FILES['image']['error'] == 7){
    echo " Failed to write file to disk. Introduced in PHP 5.1.0. ";
}
         elseif ($_FILES['image']['error'] == 8){
    echo "  A PHP extension stopped the file upload. PHP does not provide a way to ascertain which extension caused the file upload to stop; examining the list of loaded extensions with phpinfo() may help. Introduced in PHP 5.2.0.  ";
}

else {
    //no error so uploaded something, 
    // therefore $_FILES['image']['tmp_name'] is a valid file.
   $image =  addslashes(file_get_contents($_FILES['image']['tmp_name']));


                $image_name = ($_FILES['image']['name']);

               $image_size = getimagesize($_FILES['image']['tmp_name']);

           }

           if($image_size == FALSE){
               echo "That is not an image";
           }
           else{
              if(! $insert = mysql_query("INSERT INTO photos VALUES ('', 'image_name', '', 'image')")){
                  echo "Problem uploading image";

              }
               else{
                   $lastid = mysql_insert_id();{
                   echo "Image uploaded.<p/>Your image:<p/><img src = get.php?id=$lastid";

                   }
               }
           }


          ?>

4 个答案:

答案 0 :(得分:1)

问题是你:$ _FILES [&#39; image&#39;] [&#39; tmp_name&#39;]
你必须检查数组是否确实存在。

//file properties
if(isset($_FILES['image']['tmp_name']))
{
$file = $_FILES['image']['tmp_name'];
...

然后致电

file_get_contents($file)

这应该会为您提供文件

答案 1 :(得分:0)

试试这样:

<?php
      //connect to database

      mysql_connect("localhost", "root", "") or die(my_sql_error());          
      mysql_select_db("natureall")or die(my_sql_error());        


      //file properties
      if (!isset($_FILES['image'])) {
          echo "Please select an image";
      } else {
            $file = $_FILES['image']['tmp_name'];
            $image = addslashes(file_get_contents($file));
            $image_name = ($_FILES['image']['name']);
           $image_size = getimagesize($_FILES['image']['tmp_name']);
           if ($image_size === FALSE) {
                 echo "Not an image";
           } else {
                 if(! $insert = mysql_query("INSERT INTO photos VALUES ('', 'image_name', '', 'image')"))
              echo "Problem uploading image";
           else{
               $lastid = mysql_insert_id();
               echo "Image uploaded.<p/>Your image:<p/><img src = get.php?id=$lastid";
           }
       }
       }

答案 2 :(得分:0)

//file properties
      $file = $_FILES['image']['tmp_name'];

     if (!isset($file))
      echo "Please select an image";

不不不不

您在这里做的是将$file设置为某个值,然后询问它是否已设置。即使上传失败,您也会设置为某些内容

你应该做的是properly checking for PHP upload errors

因此:

if($_FILES['image']['error'] == 4){
    echo "File is empty";
}
elseif ($_FILES['image']['error'] !== 0){
    echo "Some other error";
}
else {
    //no error so uploaded something, 
    // therefore $_FILES['image']['tmp_name'] is a valid file.
   $image =  file_get_contents($_FILES['image']['tmp_name']);
}

您有其他一些问题

          addslashes($image =  file_get_contents($_FILES[]...));
  • addslashes($image = file_get_contents(...)您在这里取消关注addslashes。您忘记了结束括号并在file_get_cotents添加了一个额外的括号。一种类型,基本上。

  • 引用相同的行;你正在=的错误一侧设置addslashes。你有这个混乱,虽然不推荐,正确的语法是:

      $image = addslashes(file_get_content($_FILES['image']['tmp_name']))
    
  • 您是否知道上面是否正在为文件的数据内容添加斜杠,而不是文件名字符串?这几乎肯定是错误的,肯定是非常糟糕的做法

  • 您使用的是 DEPRECATED 数据库连接套件,这非常危险,应立即更新。 Read more here

  • 始终将您的if语句用大括号括起来,这是逻辑和清晰度的好习惯。一个没有大括号后跟多行else语句的行语句只是要求代码错误。

  • 您似乎总是将自己混淆在数据文件名字符串和数据文件内容之间。
  • 为什么要将文件 data 保存到数据库?这是非常低效的,简单地保存文件名(如您所做)和文件保存的位置地址(~URL)并将文件存储在服务器上的此目录中更容易。

有些文件上传非常好:

PHP file upload manual guideHow can i get the content of uploaded file in php?

编辑:更多信息帮助

因此,您已将某些数据保存到您的数据库,但图像名称未正确保存。解决此问题的最佳方法是设置自己的图像名称,例如$image_name=date("ymdhis")。这是因为不同的操作系统具有不同的编码文件路径和文件名的方式,因此,如果您的图像名称为“image_101 oh yeah.jpg”,则可能会导致其他文件系统出现无法识别空格的问题。

如果图像名称很长(例如某些系统上的长度超过64个字符),文件系统也可能存在问题。

如上所述,一个好的解决方案是设置自己的名称,或者清除给定的名称:

$image_name = preg_replace("/[^0-9a-z.]/i","",$_FILES['image']['name']);
//This means that $image_name can only contain dot, a-z or 0-9 (case insensitive) basic ascii characters. 
//meaning this new name will be compatible with all OS.

另一个重要方面是使用PHP Error Logging来正确显示可帮助您调试代码的警告和错误。

如果您尝试将无效数据类型保存到MySQL列类型(例如将VARCHAR数据保存到INT列等),则需要进一步研究。

您需要实现MYSQL_已被弃用且不应使用!!!

答案 3 :(得分:0)

非常感谢所有帮助我的人,特别是@Martin和W3学校。经过几个小时的敲打我的头,这是我的解决方案的样子。它还没有显示任何内容,但它正在将图像上传到目录并将详细信息输入到称为照片的表格中。使用mysqli @Martin: - )。

<?php
$target_dir = "C:/xampp/htdocs/myDocs/mainProject/res/images/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== false) {
        echo "File is an image - " . $check["mime"] . "."."<br>";
        $uploadOk = 1;
    } else {
        echo "File is not an image."."<br>";
        $uploadOk = 0;
    }
}
// Check if file already exists
if (file_exists($target_file)) {
    echo "Sorry, file already exists."."<br>";
    $uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 4000000) {
    echo "Sorry, your file is too large."."<br>";
    $uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "PNG" && $imageFileType != "jpeg"
&& $imageFileType != "gif" && $imageFileType != "JPEG" && $imageFileType != "JPG") {
    echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed."."<br>";
    $uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded."."<br>";
// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded."."<br>";
    } else {
        echo "Sorry, there was an error uploading your file."."<br>";
    }
}

if($uploadOk >0){
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "natureall";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);

// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully"."<br>";

        $name = basename( $_FILES["fileToUpload"]["name"]);
        $path = $target_file;




$sql = ("INSERT INTO photos (name, path) VALUES('$name', '$path')");


if ($conn->query($sql) === TRUE) {
    echo "New record created successfully"."<br>";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}


mysqli_close($conn); 
echo "Connection closed"."<br>";
    }

else{
    echo "Problem with image upload, entry to database not made."."<br>";
}


?>
相关问题