我目前正在为我的最后一年大学项目建立一个网站,这需要一个照片上传功能。目前,当用户上传照片时,照片存储在远程服务器的文件夹中。我需要将图像放入数据库中,所以我想知道是否有人对如何执行此操作以及将代码放置在以下代码中将上载的内容发送到数据库的位置有任何建议,我还需要它当每个用户上传图像时,它们全部显示供所有人查看,而不是当前显示,一次只显示一个图像,当页面刷新时,图像消失。希望一切都有意义,任何帮助都会非常感激。谢谢。
<?php include_once("home_start.php"); ?>
<h1>Upload your images here:</h1>
<div id="fileselect" style="border-bottom:thin #000000 solid; border- collapse:collapse">
<form id="frmSimple" action="home.php" method="post" enctype="multipart/form-data">
Select file to upload:
<input type="file" id="filename" name="filename" size="10" /><br />
<input type="submit" id="submit" name="submit" value=" Upload " />
</form>
</div>
<div id="feedback">
<?php
// Determine whether a file was uploaded
if ($_FILES) {
// Put file properties into variables
$name = $_FILES['filename']['name'];
$size = $_FILES['filename']['size'];
$tmp_name = $_FILES['filename']['tmp_name'];
// Determine whether file is png, jpg or other
switch($_FILES['filename']['type']) {
case 'image/jpeg': $ext = "jpg"; break;
case 'image/png': $ext = "png"; break;
//default: ext = ''; break;
}
//validate against file type
// if $ext is empty string (therefore null or false) image is not a jpg or png
if($ext){
// validate against file size
if($size < 1000000){
// Create a safe name for the file and store in a safe location
$n = "$name"; // Could add .$ext to enforce file type
$n = ereg_replace("[^A-Za-z0-9.]","",$n); // Remove all except alphanumeric characters and
$n = strtolower($n); // Convert to lower case (platform independence)
$n = "uploaded_images/$n"; // Add folder to force safe location
move_uploaded_file($tmp_name, $n); // Move to the safe location and give it the safe
echo "<p>Uploaded image '$name' as '$n': </p>";
echo "<img src='$n' />";
}
else echo "<p>'$name' is too big - 50KB max (50000 bytes).</p>";
}
else echo "<p>'$name' is an invalid file - only jpg and png accepted.</p>";
}
else echo "<p>No image has been uploaded.</p>";
?>
</div>
<?php include_once("home_end.php"); ?>
答案 0 :(得分:0)
我强烈建议不要这样做。相反,将照片存储在一个文件夹中并从数据库中引用它们的位置(即指向它们在文件系统上的位置的字符串)。
但是,如果您倾向于将其存储在数据库中,则需要:
再次 - 这是一个糟糕的想法。不要这样做 - 将它保存到文件系统。
另外,以下一行:
move_uploaded_file($tmp_name, $n);
没有任何文件类型检查或文件完整性,使得将shell上传到你的盒子变得微不足道。
答案 1 :(得分:0)
成功上传文件后获取上传的图片路径。
$file_type='jpg'; //if you are using more than one type write a switch case
$file_size = filesize($file);
$fp = fopen($file,'r');
$content = fread($fp,$file_size);
$content = addslashes($content); //content is a binary data of the image
fclose($fp);
将图像保存在数据库中。使用您想要$ file_name,$ file_type,$ file_size和content的任何字段编写插入查询。我假设您能够成功连接到数据库。
mysql_query("INSERT INTO Images (id,file_name,file_type,file_size,content)
VALUES ('bird', 'jpg',340kb,'binarydata')");