[英]File upload php mysql
我正在嘗試使用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>
在任何PHP開發人員開始調試任何內容之前,我總是建議在每個設置了error_reporting(E_ALL);
問題中進行建議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"];
}
}
Spme的東西在這里是錯誤的:
$new_book_name = "$id.jpg";
您應該從POST此處$_FILES["upload"]["name"]
獲取文件名。 並添加$ id與此文件名:
$new_book_name = $id."-".$_FILES["upload"]["name"];
還要在您的上傳目錄“ ../book_images/”中檢查權限。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.