delete image from server folder - php

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'";
}

Related

Adding images to folder and save their name in database using php

I am trying to upload 2 files in a folder and save their name and image path in database, here is my html code:
<input class="field2" type="file" name="file[]" multiple="multiple" />
and my php code is :
$i=0;
$count=0;
foreach ($_FILES['file']['name'] as $filename)
{
if(file_exists('upload/'.$filename))
{
echo "That File Already Exisit";
break;
}
else
{
$target='upload/';//folder path
$tmp=$_FILES['file']['tmp_name'][$count];
$count=$count + 1;
$i=$i+1;
$target=$target.basename($filename);
move_uploaded_file($tmp,$target);
$sql = "UPDATE `fleet` SET `image$i`='$target',`image_name$i`='$filename' WHERE id='$id' ";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
}
}
the issue is image is not getting stored in a folder, i have create a folder named upload, but nothing works foe me
You can try this code:
<?php
$i=0;
$count=0;
foreach ($_FILES['file']['name'] as $filename)
{
$upload_dir = $_SERVER['DOCUMENT_ROOT'] . "/upload/";
if(file_exists($upload_dir.$filename))
{
echo "That File Already Exist";
break;
}
else
{
$tmp = $_FILES['file']['tmp_name'][$count];
$count++;
$i++;
$target = $upload_dir.basename($filename);
if (is_dir($upload_dir) && is_writable($upload_dir)) {
move_uploaded_file($tmp,$target);
$sql = "UPDATE `fleet` SET `image$i`='$target',`image_name$i`='$filename' WHERE id='$id' ";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
} else {
echo 'Upload directory is not writable, or does not exist.';
}
}
If you have:
Upload directory is not writable, or does not exist.
You should to a chmod or/and a chown command to give the permissions to write on the upload_dir.
instead of storing name in data base i am storing it in txt file(as per requirement)
<?php
if (isset($_FILES["uploaded_file"]["name"])) {
$imagename=$_POST['imagename'];
$name = $_FILES["uploaded_file"]["name"];
$tmp_name = $_FILES['uploaded_file']['tmp_name'];
$error = $_FILES['uploaded_file']['error'];
if (!empty($name)) {
$location = './uploads/';
if ( ! is_dir($location)) {
mkdir($location);
}
if (move_uploaded_file($tmp_name, $location.$name)){
echo 'Uploaded';
$fp = fopen($_SERVER['DOCUMENT_ROOT'] . "/myText.txt","a+");
fwrite($fp,$imagename);
fclose($fp);
}
} else {
echo 'please choose a file';
}
}
?>

Old picture is missing

So I have "staff" table in database i.e. StaffName, StaffAddress and StaffProfilePicture etc. Updating works fine on name, address but not the picure. The old picture seems to be missing from the database eventhough I don't upload a new one.
if(isset($_POST['submit'])){
$target_dir = "images/staff/";
$target_dir = $target_dir . basename($_FILES["new_profilepicture"]["name"]);
$uploadOk=1;
if (file_exists($target_dir . $_FILES["new_profilepicture"]["name"])) {
//echo "Sorry, file already exists.";
$uploadOk = 0;
}
if ($uploadOk==0) {
//echo "Sorry, your file was not uploaded.";
}
else {
if (move_uploaded_file($_FILES["new_profilepicture"]["tmp_name"], $target_dir)) {
$imageup = $target_dir;
//echo "<img src='" . $imageup . "' />";
} else {
//echo "Sorry, there was an error uploading your file.";
}
}
$_var1 = $_POST['new_name'];
$_var2 = $_POST['new_email'];
$_var3 = $_POST['new_password'];
$_var4 = $_POST['new_contactno'];
$_var5 = $_POST['new_icno'];
$_var6 = $_POST['new_address'];
$_var7 = $_POST['new_status'];
$_var8 = $imageup;
$query1 = $mysqli->query("UPDATE staff
SET StaffName='$_var1', StaffEmail='$_var2', StaffPassword='$_var3', StaffContactNo='$_var4', StaffICNo='$_var5', StaffAddress='$_var6', StaffStatus='$_var7', StaffProfilePicture='$_var8'
WHERE StaffID='$staffID'");
$success = mysql_query($query1);//is mysql query working?
if($success){
//$oldprofilepicture = $staff['StaffProfilePicture'];
//if(file_exists($oldprofilepicture)){
//unlink($oldprofilepicture);//delete now
echo "success";
header('location:staff_profile.php');
die;
}else{
echo "failed";
}
}
Below is the HTML form for the picture
<tr>
<td width="170">Old Profile Picture:</td>
<td><img src="<?php echo $profilepicture ?>" width="100" height="80" /><br><br>
<input type="file" name="new_profilepicture" />
</tr>
How can I make the old/existed picture stay?
On your query you have:
StaffProfilePicture='$_var8'
so it still updates the database and since $imageup is empty/undefined so is $_var8 and it will update the database with empty value.
So add an if condition:
$_var8 = $imageup;
if($_var8 != '') {
$query1 = $mysqli->query("UPDATE staff SET StaffName='$_var1', StaffEmail='$_var2', StaffPassword='$_var3', StaffContactNo='$_var4', StaffICNo='$_var5', StaffAddress='$_var6', StaffStatus='$_var7', StaffProfilePicture='$_var8' WHERE StaffID='$staffID'");
} else {
$query1 = $mysqli->query("UPDATE staff SET StaffName='$_var1', StaffEmail='$_var2', StaffPassword='$_var3', StaffContactNo='$_var4', StaffICNo='$_var5', StaffAddress='$_var6', StaffStatus='$_var7' WHERE StaffID='$staffID'");
}
or you can do it other ways but that's where your problem is that you're losing your old image. Hope it helps.
Cheers.

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. :)

save image to mysql with 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'].'" />";
}?>

"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

Categories