[英]How to upload an image to a database using php script?
这是我上载的代码..但是它不起作用..我使用了file_get_contents函数。
</head>
<body>
<form action="upload1.php" method="POST" enctype="multipart/form-data">
File:
<input type="file" name="image"/>
<input type="submit" value="Upload image" />
</form>
<?php
//connect to the database
$con = mysql_connect("localhost","root", "");
if(!$con)
{
die('Could not connect to the database:' . mysql_error());
echo "ERROR IN CONNECTION";
}
mysql_select_db("imagedatabase", $con);
//file properties
echo $file = $_FILES['image']['tmp_name'];
echo '<br />';
if(!isset($file))
echo "Please select an image";
else
{
$image = file_get_contents($_FILES['image']['tmp_name']);
echo $image_name = addslashes($_FILES['image']['name']); echo '<br \>';
echo $image_size = getimagesize($_FILES['image']['tmp_name']);
if($image_size == FALSE)
echo "That's not an image";
else
{
$insert = mysql_query("INSERT INTO images (image) VALUES ($image)",$con);
if(!$insert)
echo "Problem uploding the image. Please check your database";
else
{
$last_id = mysql_insert_id();
echo "Image Uploaded. <p /> Your image: <p /><img src=display.php? id=$last_id>";
}
}
}
mysql_close($con);
?>
</body>
</html>
检索/显示的代码就是这种方式。
<?php
//connect to the database
mysql_connect("localhost","root", "") or die(mysql_error());
mysql_select_db("mydb") or die(mysql_error());
//requesting image id
$id = addslashes($_REQUEST['id']);
$image = mysql_query("SELECT * FROM images WHERE id = $id");
$image = mysql_fetch_assoc($image);
$image = $image['image'];
header("Conten-type: image/jpeg");
echo $image;
mysql_close($connect);
?>
我创建了一个名为“ imagedatabase”的数据库和一个表
在数据库中存储图像是一个坏主意。 将其路径存储在数据库中,通过.htaccess关闭包含图像的目录,然后在硬盘上使用它。
为什么不应该在DB中存储文件?
如果您将使用DB存储图像,则将具有:
您应该在上传过程中将文件保存在某个文件夹中,并将文件名保存在数据库中,以便稍后可以从数据库中调用文件名并将其链接为要下载的超链接,我正在使用以下代码上传图像在名为files的文件夹中,并将文件名保存在数据库中。 最后,我在变量$ newname中有文件名
if ($_FILES['file']['name']) {
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 500000)
&& in_array($extension, $allowedExts)
) {
if ($_FILES["file"]["error"] > 0) {
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
} else {
$ext = end(explode(".", $_FILES["file"]["name"]));
$filename = current(explode(".", $_FILES["file"]["name"]));
$newname = $filename . '_' . time() . '.' . $ext;
move_uploaded_file($_FILES["file"]["tmp_name"],
"files/" . $newname);
}
} else {
echo "<div class='alert alert-success'>Image type or size is not valid.</div>";
}
}
将图像直接上传到数据库不是一个好主意。 而是将照片上传到文件夹中,然后仅将照片名称插入数据库中,然后在以后需要时调用它。 您可以根据需要尝试以下代码。
为了使代码适合您,您必须执行以下步骤:
在代码内部将“ your_photo”替换为您的输入名称(这种情况我想是“ image”)
创建一个要在其中上传图像的文件夹,然后在->> $ newname =“ support / images / profile /”中进行更改,在此处写下您的图像文件夹名称
编写正确的数据库查询。 并记住图像名称将自动创建,并且该名称保留在此变量-> $ image_name内。 将名称插入数据库时,只需使用$ image_name作为值。
上传脚本:
<?
// If Everything is good- process the form - write the data into the database
$photo=$this->input->post('your_photo');
if($photo==NULL){$image_name='0';}// if no photo is selected the default value of the photo would be 0
//photo upload starts
$errors=0;
if($_FILES['your_photo']){
$image=$_FILES['your_photo']['name'];
if($image) {
define ("MAX_SIZE","100");
function getExtension($str) {
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext; }
//reads the name of the file the user submitted for uploading
$image=$_FILES['your_photo']['name'];
//if it is not empty
if ($image)
{
//get the original name of the file from the clients machine
$filename = stripslashes($_FILES['your_photo']['name']);
//get the extension of the file in a lower case format
$extension = getExtension($filename);
$extension = strtolower($extension);
//if it is not a known extension, we will suppose it is an error and will not upload the file,
//otherwise we will do more tests
if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif"))
{
//print error message
$msg="Sorry! Unknown extension. Please JPG,JPEG,PNG and GIF only ";
$errors=1;
}
else
{
//get the size of the image in bytes
//$_FILES['image']['tmp_name'] is the temporary filename of the file
//in which the uploaded file was stored on the server
$size=filesize($_FILES['your_photo']['tmp_name']);
//compare the size with the maxim size we defined and print error if bigger
if ($size < MAX_SIZE*1024)
{
//we will give an unique name, for example the time in unix time format
$image_name=time().'.'.$extension;
//the new name will be containing the full path where will be stored (images folder)
$newname="support/images/profile/".$image_name;
//we verify if the image has been uploaded, and print error instead
$copied = copy($_FILES['your_photo']['tmp_name'], $newname);
if (!$copied)
{
$msg="Sorry, The Photo Upload was unsuccessfull!";
$errors=1;
}
}
else
{
$msg="You Have Exceeded The Photo Size Limit";
$errors=1;
}
}}}
/*Image upload process ends here- If any problem occurs it will display error message via the $msg,
otherwise it will upload the image to the image folder. To insert the photo into database $image_name has been used*/
}
if(($_FILES['your_photo'])&& ($errors))/* If any photo is selected and any problem occurs while uploading it will
display an error message, otherwise transfer the data to Mod_addstudent model */
{
echo $msg;
}
else {
//Insert into database.Just use this particular variable "$image_name" when you are inserting into database
$sql="INSERT INTO your_table (field1, your_image_field) VALUES ('','$image_name')";
}
?>
然后查看图片:
<?php
// Retrieve information from Database First and then ..
if (empty($your_photo))
{ $image_location="images/avatar.jpg";} //if there is no image in database
else {$image_location="images/$your_photo";} // if there is any image in database
?>
<img src="<?php echo base_url(); ?><?php echo $image_location ;?>" width="150" height="170" />
首先检查您是否确实能够成功将文件上传到服务器。 遵循本教程:
http://www.tizag.com/phpT/fileupload.php
这将帮助您排除整个旅程的一半,但我强烈建议您检查日志中是否存在实际错误,如果需要其他帮助,请明确指出它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.