【问题标题】:File upload php mysql文件上传 php mysql
【发布时间】:2012-03-19 06:10:49
【问题描述】:

我正在尝试使用 php 将文件上传到服务器,但我需要一些帮助。

我有一个 html 表单来提交书名和图书图片。书名将存储在数据库中(见下文),图像将存储在服务器上。

id、书名和日期正在存储在数据库中,但图像未上传。请帮我解决一下。

谢谢。

数据库表“书”

id int(11), book_name varchar(255), date_added date

add_book.php

<?php

$book_name = $_POST['book'];

// insert fields to database
$sql_query = mysql_query("INSERT INTO books (book_name, date_added) VALUES ('$book_name', now()");  


// get id for that row
$id = mysql_insert_id();

// rename the book to that id followed by the format .jpg

$new_book_name = "$id.jpg";

// define upload path
$upload_path = "../book_images/";

// move the uploaded file to the upload path with the new name
move_uploaded_file($_FILES['upload']['tmp_name'], $upload_path . $new_book_name);

?>

<form action="add_book.php" method="post" enctype="multipart/form-data" name="bookform"     id="bookform">

Book name: <input name="book" type="text" id="book" value=""/> <br />
Book image: <input type="file" name="upload" id="upload" />

<input name="submit" type="submit" value="Add book" />
</form>

【问题讨论】:

  • 上传时会出现很多问题。与其盲目地尝试复制文件,不如先检查 $_FILES['upload']['error']。

标签: php mysql html file-upload


【解决方案1】:

在任何 PHP 开发人员开始调试任何东西之前,我总是建议在每个问题中将 error_reporting(E_ALL);ini_set("display_errors", 1); 设置在脚本的最顶部。这将告诉您关于什么语句/变量/常量的哪一行出了什么问题

无论如何,您应该检查文件是否上传的有效性、其类型和其他此类参数。您还应该通过添加相对于当前工作目录的相对路径来存储它

 if(isset($_FILES["upload"])&&$_SERVER["REQUEST_METHOD"]=="POST")
 { 
   $name=$_FILES["upload"]["name"];

   $tempName=$_FILES["upload"]["tmp_name"];

   $size=$_FILES["upload"]["size"];

   $type=$_FILES["upload"]["type"];

   $realPath="bookName/Imagename/".$name;

   if(($type=="image/jpg"||$type=="image/jpeg"||$type=="image/png"))
   {   
      if(is_dir($fullDirectory))  //if directory exists, then simply move it
       {
        move_uploaded_file($tempName, $realPath);   
       }
       else  //if directory doesn't exist then make one and then move the file
       {
        mkdir($fullDirectory,0777,true);

        move_uploaded_file($tempName, $realPath);

       }
    }
    else
    {
     print $_FILES["upload"]["error"];
    }
  }

【讨论】:

    【解决方案2】:

    这里有问题:

     $new_book_name = "$id.jpg";
    

    您应该从这里的 POST 获取文件名$_FILES["upload"]["name"]。并使用此文件名添加 $id:

    $new_book_name = $id."-".$_FILES["upload"]["name"];
    

    还要检查您上传目录“../book_images/”中的权限。

    【讨论】:

      猜你喜欢
      • 2015-04-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-18
      • 1970-01-01
      • 2016-02-18
      • 2011-12-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多