2017-08-30 135 views
0

我想上传一个图像在我的数据库,但它不会工作。PHP文件上传图像不能正常工作

这里是上传图片的代码。

<?php 
    $con = mysqli_connect("localhost", "root", "", "test"); 
    mysqli_select_db("test", $con); 

    $username = $_POST['username']; 
    $password = $_POST['password']; 
    $dob = $_POST['dob']; 
    $no = $_POST['no']; 

    if(isset($_POST['submit'])) { 

     if(getimagesize($_FILES['image']['tmp_name']) == FALSE) { 
      echo "Please select an image."; 
     } 

     else { 
      $target_dir = "uploads/"; 
      $target_file = $target_dir . basename($_FILES["image"]["name"]); 
      $uploadOk = 1; 
      $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION); 

      // Check file size 
      if ($_FILES["image"]["size"] > 500000) { 
       echo "Sorry, your file is too large."; 
       $uploadOk = 0; 
      } 

      // Check if file already exists 
      if (file_exists($target_file)) { 
       echo "<p>Sorry, file already exists.</p>"; 
       $uploadOk = 0; 
      } 

      // Check if $uploadOk is set to 0 by an error 
      if ($uploadOk == 0) { 
       echo "<p>Sorry, your file was not uploaded.</p>"; 
      } 

      // if everything is ok, try to upload file 
      else { 

       if (move_uploaded_file($_FILES["image"]["tmp_name"], $target_file)) { 
        $name = basename($_FILES["image"]["name"]); 
        $image = "uploads/".basename($_FILES["image"]["name"]); 
        echo "<p>".$name. " has been uploaded.</p>"; 
        header("location: image.php"); 

        $qry = "INSERT INTO images (id, name, image, username, password, dob, no) VALUES (NULL, '".$name."', '".$image."', '".$username."', '".$password."', '".$dob."', '".$no."')"; 
        $result = mysqli_query($con, $qry); 

        //$sql = "INSERT INTO images (username) VALUES ('$username')"; 
        //$result = mysqli_query($con, $sql); 

       } 

       else { 
        echo "<p>Sorry, there was an error uploading your file.</p>"; 
       } 
      } 
     } 
    } 
?> 

它总是说,抱歉,上传文件时出现错误。

这是服务器日志中的错误。

PHP的警告:move_uploaded_file()以:无法 '的/ tmp/phpRGn6S7' 移动到 '上传/截图,从2017年8月9日16-57-58.png' 在 的/ var/www/html等/practice1/images2.php第45行上,引用者: http://localhost/practice1/image.php

我新在PHP文件上传。 会真的很感激,如果有人可以帮助。 在此先感谢。

+0

任何进一步的细节上给了错误? php/apache错误日志中显示了什么?文件大小是否超过最大文件上传大小的php设置?它正在写入的文件夹是否可由apache用户写入? – flauntster

+0

你能描述一下你面临的问题吗? – DSK

+0

你有'enctype'设置在你的html表单中吗? 'enctype =“multipart/form-data”' –

回答

2

在Windows和Linux上,move_uploaded_file()函数与的作用不同。 在Linux上,你需要把完整路径是这样的:

$target_dir = "/var/www/html/practice1/uploads/"; 

或者单独PROJECT_DIR并上传DIR像这样:

$project_dir = '/var/www/html/practice1/'; 
$target_dir = $project_dir . 'uploads/'; 
+0

谢谢!不知道因为我转移到Linux和只是一个新手使用它。 –

1

我认为这个问题是在这里:

$target_dir = "uploads/"; 

你宁愿使用这样的:

$target_dir = PROJECT_DIR . "uploads/"; 

随着宗旨,以最终了到上传目录的绝对路径。

+0

我试过但它将不起作用 –

+0

但是,您的错误信息是否更改? –

+0

没有相同的错误。 :( –