save image to mysql with php - php

i created this form to add my images to mysql database,and i think i did it right-cause it saves something :D - but it wont show me the image, what should i do to "SEE" the image from mysql?!
this is my form php:
$tmp_name=$_FILES['file']['tmp_name'];
if (isset($_POST['submit'])) {
if ((($_FILES['file']['type']) == "image/jpeg")
|| ($_FILES['file']['type']) == "image/gif"
|| ($_FILES['file']['type']) == "image/pjpeg"
&& ($_FILES['file']['size']) > 200000) {
$tmp_name=$_FILES['file']['tmp_name'];
// i also tried addslasheds
$image = mysql_real_escape_string(file_get_contents($_FILES['file']['tmp_name']));
if ($_FILES['file']['error'] > 0) {
echo "return code : " . $_FILES['FILES']['error'];
}else{
if (file_exists($_FILES['file']['name'])) {
echo "your file is already exists!";
}else{
Query("INSERT INTO image(image) VALUES ('".$tmp_name."')");
echo "FILES has been stored";
}
}
}
}else{
echo "invalid file";
}?>
and my code to show the image is:
<?php
require 'lib.php';
$request=Query('SELECT * FROM image');
while ($row = mysql_fetch_array($request)) {
echo $row['image'];
}?>

Inserting the temporary name into your database won't accomplish anything because it is just that, temporary. You need to save the image somewhere on your server using move_uploaded_file() and then save the new permanent name to your database so that you can use it in html image tags later.
$filename = "myimage.jpg";
$path = "/var/www/images/".$filename;
$link = "http://domain.com/images/".$filename;
move_uploaded_file($FILES['file']['tmp_name'], $path);
$image = mysql_real_escape_string($link);
if ($_FILES['file']['error'] > 0) {
echo "return code : " . $_FILES['FILES']['error'];
}else{
Query("INSERT INTO image(image) VALUES ('".$image."')");
echo "FILES has been stored";
}
Then when you retrieve your image:
<?php
require 'lib.php';
$request=Query('SELECT * FROM image');
while ($row = mysql_fetch_array($request)) {
echo '<img src="'.$row['image'].'" />";
}?>

Related

delete image from server folder

Here is code of uploading image in my localhost/file/img folder and also inserting image path and name in my table.
<?php
if (isset($_POST['submit']))
{
$file_id = $_POST['file_id'];
if (count($_FILES['upload']['name']) > 0)
{
for ($i = 0; $i < count($_FILES['upload']['name']); $i++)
{
$tmpFilePath = $_FILES['upload']['tmp_name'][$i];
if ($tmpFilePath != "")
{
$shortname = $_FILES['upload']['name'][$i];
$filePath = "img/" . $_FILES['upload']['name'][$i];
if (move_uploaded_file($tmpFilePath, $filePath))
{
$files[] = $shortname;
$query = "insert into images(id,img_name) values('$file_id',' $filePath')";
mysqli_query($con, $query);
}
}
}
}
echo "<h1>Uploaded:</h1>";
if (is_array($files))
{
echo "<ul>";
foreach($files as $file)
{
echo "<li>$file</li>";
}
echo "</ul>";
}
}
?>
Table Images with attribute img_name type is LONGBLOB
now its totally working fine but when i am deleting image from database its getting error that image name is not found. here is code of sending image id and image name using a href
<ul>
<a href="index.php?img_id=<?php echo urlencode($id); ?>&img=<?php echo urlencode($img); ?>"
style="color:red; margin-left:18px;" onclick="return confirm('Are you sure you want to delete this?')" >Delete
</a>
</ul>
now here is code of want i want to delete from my database and also from my localhost folder named img .
<?php
if (isset($_GET['img_id'], $_GET['img']))
{
$id = $_GET['img_id'];
$img = $_GET['img'];
$query = "delete from images where id='$id' and image='$img'";
if (mysqli_query($con, $query))
{
unlink($img);
echo '<script language="javascript">';
echo 'alert("Image Deleted successfully")';
echo '</script>';
}
else
{
echo '<script language="javascript">';
echo 'alert("image does not exist")';
echo '</script>';
}
}
?>
now showing warning that img/image_name.jpg not found.Help me please .
I think your delete query is wrong
if(isset($_GET['img_id'] , $_GET['img'])){
$id=$_GET['img_id'];
$img=$_GET['img'];
$query="delete from images where id='$id' and image='$id'";
}
$query="delete from images where id='$id' and image='$img'";
In this query you check Id and Image field with same $id variable
try this :
<?php
if (isset($_FILES['image']['name'])) {
$name = $_FILES['image']['name'];
$tmpname1 = $_FILES['image']['tmp_name'];
$exten = explode(".", $_FILES['image']['name']);
$exten = $exten[1];
if ($exten != '') {
$image_name = "img" . time() . "." . $exten;
}
move_uploaded_file($tmpname1, FCPATH . 'assets/admin/uploads/' . $image_name);
$query = "insert into images(id,img_name) values('your_id',' $image_name')";
mysqli_query($con, $query);
//see your code
/*
$id=$_GET['img_id'];
$img=$_GET['img'];
$query="delete from images where id='$id' and image='$id'";
*/
you pass the same id value for image. you should try this-
$query="delete from images where id='$id' and image='$img'";
}

How to upload ONLY images in database

I want to upload ONLY pictures , in the database using php.
What I tried is,
<?php
if (isset($_POST['Upload'])) {
$con = mysql_connect("localhost", "root", "");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("iis", $con);
$image = $_FILES["product_image"]["name"];
$imageType = mysql_real_escape_string($_FILES["product_image"]["type"]);
if (substr($imageType, 0, 5) == "image") {
if (!file_exists("product_images")) {
mkdir("product_images");
}
if ($_FILES["product_image"]["error"] > 0) {
$error = "ERROR Return Code :" . $_FILES["product_image"]["error"] . "<br />";
} else {
move_uploaded_file($_FILES["product_image"]["tmp_name"], "product_images/" . $_FILES["product_image"]["name"]);
}
}
$UserName = $_SESSION['id'];
$product_image = ("product_images/" . $_FILES["product_image"]["name"]);
mysql_query("INSERT INTO `feedbackzxc` VALUES ('', '$UserName', '$product_image')");
echo "Image Uploaded!";
} else {
echo "Only images are allowed";
}
?>
But when I upload a file other than images it doesn't show the error message. How can I make it show error message if a file other than an image is uploaded?
Your else block where the message Only images are allowed is shown must be located after the if block that check this: substr($imageType,0,5) == "image"
if(substr($imageType,0,5) == "image"){
if(!file_exists("product_images"))
{
mkdir("product_images");
}
if($_FILES["product_image"]["error"] > 0)
{
$error = "ERROR Return Code :" . $_FILES["product_image"]["error"] . "<br />";
}
else
{
move_uploaded_file($_FILES["product_image"]["tmp_name"], "product_images/".
$_FILES["product_image"]["name"]);
}
}
else
{
echo "Only images are allowed";
}

Display all images from database (php)

I use this code to upload images in the database:
<?php
//Store the upload form
$UploadForm = " <form id='idForm' action='upload.php' method='post' enctype='multipart/form-data'>
<input type='file' name='image'/><br/><br/>
<input id='BTN' type='submit' value='Upload'/><br/><br/>
</form>";
//if logged in show the upload form
if($userid && $username){
echo $UploadForm;
// Connect to database
$con = mysqli_connect('***', '***', '***', '***_dbimage');
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//file properties
if(isset($_FILES['image'])){
$file = $_FILES['image']['tmp_name'];
}
//if image selected
if(isset($file) && $file != ""){
$image = addslashes(file_get_contents($_FILES['image']['tmp_name']));
$image_name = addslashes($_FILES['image']['name']);
$image_size = getimagesize($_FILES['image']['tmp_name']);
if($image_size == FALSE){
echo "That's not an image!";
header( "refresh:2;url=upload.php" );
}
else{
$qry = mysqli_query($con,"SELECT * FROM store WHERE name='$image_name'");
$Nrows = $qry->num_rows;
if( $Nrows == 0){
if(!$insert = mysqli_query($con,"INSERT INTO store VALUES ('','$image_name','$username','$image')")){
echo "We had problems uploading your file!";
header( "refresh:2;url=upload.php" );
}
else{
echo "Image $image_name uploaded!";
header( "refresh:2;url=upload.php" );
}
}
else{
echo "There is already an image uploaded with the name $image_name<br/>";
}
}
}
else{
echo "Please select an image";
}
mysqli_close($con);
}
else{
echo "You have to be logged in to upload!";
}
?>
And this code to display all images from the database:
// Connect to database
$con = mysqli_connect('***', '***', '***', '***_dbimage');
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$res = mysqli_query($con,'SELECT * FROM store');
while($row = $res->fetch_array()){
$image = $rows['image'];
echo "<img src='".$image."' />";
}
And I get something like tons of random symbols like diamonds with question marks in them and letters instead of my image. The scripts are not made by me. I just watched some tutorials and combined them and it seems that I didn't "combined" them properly. What am I doing wrong?
LATER EDIT:
HTML:
<img src="getImage.php?id=26"/>
PHP (getImage.php):
$con = mysqli_connect('***', '***', '***', '***_dbimage');
if(isset($_GET['id']))
{
$id = mysql_real_escape_string($_GET['id']);
$query = mysql_query("SELECT * FROM store WHERE id=$id");
while($row = mysql_fetch_assoc($query))
{
$imageData = $row['image'];
}
header("content-type:image/jpeg");
echo $imageData;
}
else
{
echo "Error!";
}
?>
Still can't get it to work! Help please!
I finaly did it!
This is the upload script:
<?php
//Store the upload form
$UploadForm = " <form id='idForm' action='upload.php' method='post' enctype='multipart/form-data'>
<input type='file' name='image'/><br/><br/>
<input id='BTN' type='submit' value='Upload'/><br/><br/>
</form>";
//if logged in show the upload form
if($userid && $username){
echo $UploadForm;
// Connect to database
$con = mysqli_connect('***', '***', '***', '***_dbimage');
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//file properties
if(isset($_FILES['image'])){
$file = $_FILES['image']['tmp_name'];
}
//if image selected
if(isset($file) && $file != ""){
$image = mysqli_real_escape_string($con,file_get_contents($_FILES['image']['tmp_name']));
$image_name = addslashes($_FILES['image']['name']);
$image_size = getimagesize($_FILES['image']['tmp_name']);
if($image_size == FALSE){
echo "That's not an image!";
header( "refresh:2;url=upload.php" );
}
else{
$qry = mysqli_query($con,"SELECT * FROM store WHERE name='$image_name'");
$Nrows = $qry->num_rows;
if( $Nrows == 0){
if(!$insert = mysqli_query($con,"INSERT INTO store VALUES ('','$image_name','$username','$image')")){
echo "We had problems uploading your file!";
header( "refresh:2;url=upload.php" );
}
else{
echo "Image $image_name uploaded!";
header( "refresh:2;url=upload.php" );
}
}
else{
echo "There is already an image uploaded with the name $image_name<br/>";
}
}
}
else{
echo "Please select an image";
}
mysqli_close($con);
}
else{
echo "You have to be logged in to upload!";
}
?>
Here is the diplay script:
$con = mysqli_connect('***', '***', '***', '***_dbimage');
$query = mysqli_query($con,"SELECT id FROM store");
while($row = mysqli_fetch_assoc($query))
{
$IDstore = $row['id'];
echo "<img src='getImage.php?id=".$IDstore."'/>";
}
And the "getImage.php":
<?php
$con = mysqli_connect('***', '***', '***', '***_dbimage');
if(isset($_GET['id']))
{
$id = mysqli_real_escape_string($con,$_GET['id']);
$query = mysqli_query($con,"SELECT * FROM store WHERE id=$id");
while($row = mysqli_fetch_assoc($query))
{
$imageData = $row['image'];
}
header("content-type:image/jpeg");
echo $imageData;
}
else
{
echo "Error!";
}
?>
I hope it will help someone cause it's ready to use now. :)

"Blog Post" show from Mysql Database wtih Image

How can I show my all "blog post" with images? Example:
Mysql table:
post_id | user_id | subject | message | image | img_name.
What is the php code to display all my posts with images in the index page? I used the following code but it doesn't display images, it shows only data. I would like to see something like this:
image | message is here
image | message is here
image | message is here
I used 3 pages
add_post.php(Html form)
add_post_process.php(process the add_post.php)
index.php (which shows my all post)
add_post_process.php:
<?php
include "db.php";
#$file = addslashes($_FILES['image']['tmp_name']);
$lastid= mysql_insert_id();
#$img = addslashes(file_get_contents($_FILES['image']['tmp_name']));
$img_name = addslashes($_FILES['image']['name']);
#$img_size = getimagesize($_FILES['image']['tmp_name']);
$upload_path = './blogpostimg/';
$post_id = addslashes($_POST['post_id']);
$user_id = addslashes($_POST['user_id']);
$subject = addslashes($_POST['subject']);
$message = addslashes($_POST['message']);
$cat_id = addslashes($_POST['cat_id']);
$cat_name = addslashes($_POST['cat_name']);
$comment_count = addslashes($_POST['comment_count']);
$ch_img = addslashes($_FILES['image']['name']);
$query = "SELECT img_name FROM blog_post WHERE img_name = '$ch_img';";
$result = mysql_query($query) or die (mysql_error());
if(isset($subject, $message))
{
$errors = array();
if(empty($subject) && empty($message) && empty($file))
{
$errors[] ='all field required';
}
else
{
if(empty($subject))
$errors[] = 'Subejct requried';
if (empty($message))
$errors[] = 'message required';
if(empty($file))
$errors[] ="SORRY, you have to be upload a image";
elseif($img_size == FALSE)
{
$errors[] ="That's not an image";
}
else
{
if(mysql_num_rows($result) != 0)
$errors[] = " You have to change this image name, already exit in our database";
}
}
if(!empty($errors))
{
foreach($errors as $error)
{
echo "<ul>";
echo "<strong><font color=red><li>$error</li></font></strong><br/>";
echo "</ul>";
}
}
else
{
if(!move_uploaded_file($_FILES['image']['tmp_name'],$upload_path . $img_name))
{
die('File Not Uploading');
}
else
{
$lastid = mysql_insert_id();
$query = mysql_query("INSERT INTO blog_post VALUES ('', '', '$subject',
'$img','$img_name','$message','$cat_id','$cat_name','',NOW() )");
if($query)
echo "Successfully uploaeded your post";
else
{
echo "Something is wrong to Upload";
}
}
}
}
?>
index.php
<?php
include "db/db.php";
$upload_path = "/secure/content/blogpostimg";
$sql= mysql_query("SELECT * FROM blog_post");
while ($rel = mysql_fetch_assoc($sql))
{
$id = $rel['post_id'];
$sub = $rel['subject'];
$imgname = $rel['img_name'];
$img = $rel ['image'];
$msg = $rel['message'];
$date = $rel['date'];
echo "<h1>". "$sub" ."</h1>". "<br/>";
echo "$imgname" ."<br/>";
echo '<img src="$upload_path " />';
echo "$msg" . "<br/>";
echo "$date" . "<br/>";
echo "<hr/>";
echo "<br/>";
}
?>
The mysql table structure is
post_id(int)
User_id(int)
subject(varchar)
image(blob)
img_name(varchar)
message(text)
change
echo '<img src="$upload_path " />';
to
echo '<img src="' . $upload_path . '/' . $img . '" />';
that should do the trick..
I don't now if it matters in performanceways.. but howcome you use blob instead of a varchar.. 255 characters for a filename should be enough.
In your index.php you have <img src="$upload_path" />. Instead of $upload_path, src needs to be the URL to your image.
I just noticed that you are storing the image itself in the database. There is no need to do this if you move it to a publicly accessible directory, e.g. /var/www/images/myimage.jpg

PHP upload script

Using this upload script and it was working ok a week ago but when i checked it today it fails. I have checked writ privileges on the folder and it is set to 777 so don't think that is the problem. Anyone have a idea of what the problem can be?
this is the error
Warning: move_uploaded_file() [function.move-uploaded-file]:
Unable to access replays/1275389246.ruse in
/usr/home/web/wno159003/systemio.net/ruse.systemio.net/scripts/upload.php on line 95
my script is
<?php
require($_SERVER['DOCUMENT_ROOT'].'/xxxx/xxxx');
$connection = #mysql_connect($db_host, $db_user, $db_password) or die("error connecting");
mysql_select_db($db_name, $connection);
$name = basename($_FILES['uploaded']['name']);
$comment = $_POST["comment"];
$len = strlen($comment);
$username = $_POST["username"];
$typekamp = $_POST["typekamp"];
$date = time();
$target = "replays/";
$target .= basename($_FILES['uploaded']['name']);
$maxsize = 20971520; // 20mb Maximum size of the uploaded file in bytes
// File extension control
// Whilelisting takes preference over blacklisting, so if there is anything in the whilelist, the blacklist _will_ be ignored
// Fill either array as you see fit - eg. Array("zip", "exe", "php")
$fileextensionwhitelist = Array("ruse"); // Whilelist (allow only)
$fileextensionblacklist = Array("zip", "exe", "php", "asp", "txt"); // Blacklist (deny)
$ok = 1;
if ($_FILES['uploaded']['error'] == 4)
{
echo "<html><head><title>php</title></head>";
echo '<body bgcolor="#413839" text="#ffffff">
<p><B>info</b></p>';
die("No file was uploaded");
}
if ($_FILES['uploaded']['error'] !== 0)
{
echo "<html><head><title>php</title></head>";
echo '<body bgcolor="#413839" text="#ffffff">
<p><B>info</b></p>';
die("An unexpected upload error has occured.");
}
// This is our size condition
if ($_FILES['uploaded']['size'] > $maxsize)
{
echo "<html><head><title>php</title></head>";
echo '<body bgcolor="#413839" text="#ffffff">
<p><B>info</b></p>';
echo "Your file is too large.<br />\n";
$ok = 0;
}
// This is our limit file type condition
if ((!empty($fileextensionwhitelist) && !in_array(substr(strrchr($_FILES['uploaded']['name'], "."), 1), $fileextensionwhitelist)) || (empty($fileextensionwhitelist) && !empty($fileextensionblacklist) && in_array(substr(strrchr($_FILES['uploaded']['name'], "."), 1), $fileextensionblacklist)))
{
echo "<html><head><title>php</title></head>";
echo '<body bgcolor="#413839" text="#ffffff">
<p><B>info</b></p>';
echo "This type of file has been disallowed.<br />\n";
$ok = 0;
}
// Here we check that $ok was not set to 0 by an error
if ($ok == 0)
{
echo "<html><head><title>php</title></head>";
echo '<body bgcolor="#413839" text="#ffffff">
<p><B>info</b></p>';
echo "Sorry, your file was not uploaded. Refer to the errors above.";
}
// If everything is ok we try to upload it
else
{
if($len > 0)
{
$target = "replays/".time().'.'."ruse";
$name = time().'.'."ruse";
$query = "INSERT INTO RR_upload(ID, filename, username, comment, typekamp, date) VALUES (NULL, '$name', '$username','$comment', '$typekamp' ,'$date')";
if (file_exists($target))
{
$target .= "_".time().'.'."ruse";
echo "<html><head><title>php</title></head>";
echo '<body bgcolor="#413839" text="#ffffff">
<p><B>info</b></p>';
echo "File already exists, will be uploaded as ".$target;
}
mysql_query($query, $connection) or die (mysql_error());
echo "<html><head><title>php</title></head>";
echo '<body bgcolor="#413839" text="#ffffff">
<p><B>info</b></p>';
echo (move_uploaded_file($_FILES['uploaded']['tmp_name'], $target))
? "The file ".basename( $_FILES['uploaded']['name'])." has been uploaded. \n"
: "Sorry, there was a problem uploading your file. <br>";
echo "<br>Variable filename: ".$name;
echo "<br>Variable name: ".$username;
echo "<br>Variables comment: ".$comment;
echo "<br>Variables date: ".$date;
echo "<br>Var typekamp; ".$typekamp;
echo "<br>Var target; ".$target;
}
else
{
echo "<html><head><title>php</title></head>";
echo '<body bgcolor="#413839" text="#ffffff">
<p><B>info</b></p>';
echo"you have to put in comment/description";
}
}
?>
Assuming the "replays" directory is in the document root, does the warning persists if you replace this line :
$target = "replays/";
by this one :
$target = $_SERVER['DOCUMENT_ROOT']."replays/";
?

Categories