這是一個簡單的方法來做到這一點。我給你我的腳本 的index.html 但要小心:
- 不推薦,因爲它是昂貴的數據庫來存儲文件
- 修復任何SQL注入vurnelabilities。我自己不知道該怎麼做。你可以進行研究並修復它。
- 還檢查了這裏Storing Images in DB - Yea or Nay?
然而代碼工作,如果它不是一個大規模應用,並沒有SQL注入攻擊可能發生相當不錯。
<html>
<body>
<form method="post" enctype="multipart/form-data" action="doupload.php">
<input type="hidden" name="MAX_FILE_SIZE" value="2000000">
<input name="userfile" type="file" id="userfile">
<input name="upload" type="submit" id="upload" value=" Upload ">
</form>
</body>
</html>
doupload.php
<?php
include("config.php");
$fileName = $_FILES['userfile']['name'];
$tmpName = $_FILES['userfile']['tmp_name'];
$fileSize = $_FILES['userfile']['size'];
$fileType = $_FILES['userfile']['type'];
$fp = fopen($tmpName, 'r');
$content = fread($fp, filesize($tmpName));
$content = addslashes($content);
fclose($fp);
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
}
$query = "INSERT INTO upload set name='".$fileName."', size='".$fileSize."', type='".$fileType."', content='".$content."'";
mysql_query($query) ;
?>
getuploaded.php
<?php
// select records from database if exists to display
include("config.php");
$query1 = "SELECT id, name FROM upload";
$result1 = mysql_query($query1) or die('Error, query failed');
if(mysql_num_rows($result1)>0)
{
while(list($id, $name) = mysql_fetch_array($result1))
{
?>
<a href="download.php?id=<?php echo $id;?>"><?php echo $name;?></a> <br>
<?php
}
}
?>
的download.php
<?php
//header("Content-type: $type");
include("config.php");
$id = $_GET['id'];
$query = "SELECT name, type, size, content " .
"FROM upload WHERE id = '$id'";
$result = mysql_query($query) or die('Error, query failed');
list($name, $type, $size, $content) = mysql_fetch_array($result);
header("Content-length: $size");
header("Content-type: $type");
header("Content-Disposition: attachment; filename=$name");
echo $content;
?>
的config.php
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die('Error connecting to mysql');
$dbname = 'uploadfile';
mysql_select_db($dbname);
?>
Createing表
CREATE TABLE upload (
id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(30) NOT NULL,
type VARCHAR(30) NOT NULL,
size INT NOT NULL,
content MEDIUMBLOB NOT NULL,
PRIMARY KEY(id)
);
粘貼PHP錯誤日誌中變得越來越快回答 – vaichidrewar 2013-04-27 19:05:01
你應該應對文件到服務器,然後就在數據庫的路徑可能會有所幫助。 – Sumoanand 2013-04-27 19:07:14
爲什麼不把它存儲在服務器上,只是在db中存儲文件名/路徑? – member8888 2013-04-27 19:05:23