Updating new image still showing the old image - php

(I wanted to upload a new image with the same name as previous.
All code is working well...
but when i try to fetch image it show the previous image)
Any Solution????
Mysql Table
My Code
<?php
include "nav.php";
$id = $_GET['id'];
$id = base64_decode($id);
$q = "select * from slider where id =".$id;
include "js.php";
include "db.php";
$r = mysqli_query($con,$q);
$row = mysqli_fetch_assoc($r);
?>
<div style = "width:70%;margin-left:13%;">
<form method = "post" enctype="multipart/form-data">
<br>
<center>
<input type = "text" value="<?php echo $row["text"];?>" name = "title" placeholder="Title" style = "width:100%;" required>
<br>
<br>
<input type="file" name = "m" class="form-control-file" accept="image/x-png,image/gif,image/jpeg" id="exampleFormControlFile1" required>
<input class = "btn btn-primary" type = "submit" name = "submit" value="Submit">
</center>
</form>
</div>
<?php
if(isset($_POST["submit"])){
$t =$_POST['title'];
$allow = array('jpg');
$temp =explode(".",$_FILES['m']['name']);
$extension= end($temp);
$newfilename=$row['id'] .".".$extension;
if($extension=="jpg")
{
$upload_file=$newfilename;
move_uploaded_file($_FILES['m']['tmp_name'] , "slider/".$upload_file);
}
else
{
echo "<script>alert('Image should be in jpg');</script>";
exit();
}
$q = "update slider set text= '".$t."' where id= ".$row['id'];
$r = mysqli_query($con,$q);
header('location:slider.php');
exit();
}
?>
'''
Here how can i use unlink funtion????
or can any one me the code to delete the old image and create and upload a new image with the same name

if you need to update the image in ftp but with the same name in database, first fetch the data from the database for that row and store the value of the image in a variable like this :
// write your sql query here
$upload_file=$old_file_name; // value should be fetch from database.
then unlink the image from the ftp using:
unlink('/path/imagename.png'); // set your path and change the name and extension
once you unlink the image upload the new image and remove while uploading it. so it can remove existing file from ftp and upload new image with old name.

here is the solution .....
(It will delet the old pic and upload the new one in folder....)
<?php
//delet the previous img
unlink("slider/" . $oldimage);
// If upload button is clicked ...
if (isset($_POST['submit'])) {
// Get image name
$title=$_POST['title'];
$filename = $_FILES['image']['name'];
$filetmpname = $_FILES['image']['tmp_name'];
//folder where images will be uploaded
$folder = 'slider/';
//function for saving the uploaded images in a specific folder
move_uploaded_file($filetmpname, $folder.$filename);
//inserting image details (ie image name) in the database
$sql = "UPDATE slider SET image='$filename',text='$title' where id=$id";
$qry = mysqli_query($con, $sql);
if( $qry) {
echo "</br>image uploaded";
}header('Location:slider.php');
}
?>
got uploading idea from here
https://medium.com/#mauricemuteti2015/how-to-upload-and-insert-image-into-mysql-database-using-php-and-html-32633a06d372

Related

Simultaneous file upload to the same directory

For part of my web app, I'm attempting to upload 1 file under 2 different names. The first name is the original file name that the user specified. This is to be used for reference later on in my app. The second name is an altered name (simply adding in a counter variable). For uploading a single file using move_uploaded_file($name, $path), it works like a charm. When I attempted to call one move_uploaded_file(...) after the other, only the first function would upload a file. The second function would not return an error message.
After looking online, it seemed that this could be accomplished with a loop. I placed the names and the paths in an array, loop through it with a foreach loop but only the first file is uploaded.
Below are the files and their relevant portions as some are lengthy.
mainPage.php applies a header across all of my pages.
verifyFile.php is the file that does the uploading as well as verifying the bulk processing to check that the file is valid.
workPage.php
<?php
session_start();
require("mainPage.php");
?>
<link rel = "stylesheet" type = "text/css" href = "CSS/workpageCSS.css" />
<div id = "pageContainer">
<form enctype = "multipart/form-data" action = "verifyFile.php" method = "post">
<table border = "0" cellpadding = "2" cellspacing = "5">
<tr>
<td>
<label for = "fileName">Select file to upload</label>
</td>
<td>
<input type = "file" name = "file" id = "fileName" placeholder = "Choose file path" autofocus = "autofocus" required = "required" />
</td>
</tr>
<tr>
<td></td>
<td><input type = "submit" value = "Load file" /></td>
</tr>
</table>
</form>
</div>
Portion of verifyFile.php that uploads the file.
Attempt 1:
<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', '1');
$dupFile = appendFileName(basename($_FILES['file']['name']));
$origToUpload = basename($_FILES['file']['name']);
$targetPath = ("uploads/".$dupFile);
$origTargetPath = "uploads/".$origToUpload;
if(move_uploaded_file($_FILES['file']['tmp_name'], $targetPath)) {
#echo("Successfully uploaded ".basename($_FILES['file']['name']));
} else {
echo("Failed 1<br />");
}
/*move_uploaded_file($_FILES['file']['tmp_name'], $origTargetPath); Does not upload but no errors are generated */
?>
Attempt 2
<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', '1')
$filesToUpload = array($targetPath, $origTargetPath);
foreach($filesToUpload as $toUpload) {
if(move_uploaded_file($_FILES['file']['tmp_name'], $toUpload)) {
echo("worked!"); /* first time is successful and $targetPath is loaded onto my server */
} else {
echo("neg"); /* nothing is uploaded and returns neg */
}
}
?>
$origTargetPath and $targetPath are both valid since if I reverse them in my array, only the first file is correctly uploaded.
For additional information, I'm using Apache via XAMPP.
When you call move_upload_file, php will move the file from the file temporary location, to the one you specified. So you can't move the file twice.
What you are looking for is the copy function. In your case (first attempt):
copy($targetPath, $origTargetPath);
You could also consider symlink

Need Help To Solve Images Disppeared After Again Form Submiitted?

i have multiple image upload options in the form and they are working fine and update file name in the mysql database columns?
when i uploads image1 then image move on to the server and also it is showing next to html table columns now problem is that when i upload image with file option2 after form submit then image1 which is on the next to the image1 file option will be disappeared and in the mysql database image1 columns will be blank?
Multiple Images Uploading Functions
$id=$_REQUEST['id'];
if(isset($_POST['submit']))
{
if (!empty($_FILES['image']['name']))
{
$rnd_1 = rand(11111,99999);
$file_name= $rnd_1.'_'.$_FILES['image']["name"];
$file_path = "uploads/";
$image = new imgMark();
$image->font_path = "arial.ttf";
$image->font_size = 25;
$image->water_mark_text = "© www.edge.pk";
$image->color = 'CC003E';
$image->opacity = 50;
$image->rotation = 0;
if($image->convertImage('image', $file_name, $file_path))
$demo_image = $image->img_path;
}
if (!empty($_FILES['image1']['name']))
{
$rnd_1 = rand(11111,99999);
$file_name= $rnd_1.'_'.$_FILES['image1']["name"];
$file_path = "uploads/";
$image = new imgMark();
$image->font_path = "arial.ttf";
$image->font_size = 35;
$image->water_mark_text = "© www.edge.pk";
$image->color = 'CC003E';
$image->opacity = 50;
$image->rotation = 0;
if($image->convertImage('image1', $file_name, $file_path))
$demo_image2 = $image->img_path;
}
if (!empty($_FILES['image2']['name']))
{
$rnd_1 = rand(11111,99999);
$file_name= $rnd_1.'_'.$_FILES['image2']["name"];
$file_path = "uploads/";
$image = new imgMark();
$image->font_path = "arial.ttf";
$image->font_size = 35;
$image->water_mark_text = "© www.edge.pk";
$image->color = 'CC003E';
$image->opacity = 50;
$image->rotation = 0;
if($image->convertImage('image2', $file_name, $file_path))
$demo_image3 = $image->img_path;
}
Update Query
UPDATE products SET
image='$demo_image',addimage1='$demo_image2',addimage2='$demo_image3'
WHERE id='$id'
}
Select Images Query
$query1=mysql_query("select images,addimages1,addimages2 from products
where id='$id' ")or die("query");
$row2=mysql_fetch_array($query1);
<form method="post" enctype="multipart/form-data">
Image Upload Option1
<input type="file" name="image" id="image" />
<img src="<?php echo $image['image'] ?>" width="150" height="150" />
Image Upload Option2
<input type="file" name="image1" id="image1"/>
<img src="<?php echo $image['addimage1'] ?>" width="150" height="150" />
Image Upload Option3
<input type="file" name="image2" id="image2"/>
<img src="<?php echo $image['addimage2'] ?>" width="150" height="150" />
<input type="submit" class="bg" name="submit" />
</form>
The problem lays here:
UPDATE products SET
image='$demo_image',addimage1='$demo_image2',addimage2='$demo_image3'
WHERE id='$id'
}
From what I understood you first submit the form where you upload the first image and then you submit the form again where you upload the second image. The reason of this is that during your second upload the variable $demo_image will be blank because you are not sending any value of the input "image" during the resubmit. See here:
$demo_image = $image->img_path;
$image->img_path is blank, therefore $demo_image will be blank (or NULL? - not sure) as well.
There are many solutions of this problem. You can retrieve data from you db to the form and then resubmit, or test if your variables are blank (or NULL?) and then having different UPDATE commands for different variations, or retrieving data from MySQL just before you run UPDATE and many more.
I'd pick retrieving "old" data from MySQL and then just test if their NULL. If they are not NULL in MySQL, you will just resubmit the same data to your db. Like this:
if ($demo_image_from_db!=NULL) $demo_image = $demo_image_from_db;
It is possible that there is also a MySQL native function for updating only when NULL - I've heard of COALESCE but I don't exactly know how to use it - that would be definitely the simplest way to do it.

Cannot Update Image In PHP&MYSQL

hi guys i am working on a project where i have a student_edit.php file which updates the students
details all my data is updated successfully but there is one problem when i update lets say only two fields and not all then image is blanked and my fields updated successfully.
what i am doing is that i am showing student picture and besides it i have another input fields to browse image to update image. What i want is simple that if i am not updating image instead i update other fields image should be still there and not become blank.
Necessary code snippets is like that:
<?php
$file_name = $_FILES['picture']['name'];
$tmp_name = $_FILES['picture']['tmp_name'];
if (copy($tmp_name, "images/" . $file_name)) {
$picture = "images/" . $file_name;
}
if (!isset($_POST['picture'])) {
$res = mysql_query("UPDATE student SET `id`='$id',`branch_id`='$branch_id',`class_id`='$class_id',`section_id`='$section_id',`roll_number`='$roll_number',`student_name`='$student_name',`father_name`='$father_name',`dob`='$dob',`student_address`='$student_address',`gender`='$gender',`status`='$status',updated=now() WHERE id='$id'") or die(mysql_error());
}
else {
$res = mysql_query("UPDATE student SET `id`='$id',`branch_id`='$branch_id',`class_id`='$class_id',`section_id`='$section_id',`roll_number`='$roll_number',`student_name`='$student_name',`father_name`='$father_name',`dob`='$dob',`student_address`='$student_address',`gender`='$gender',`status`='$status',`picture`='$picture',updated=now() WHERE id='$id'") or die(mysql_error());
}
?>
and their is picture area where i call pics
<p>
<label for="picture"><strong>Picture:</strong> </label>
<img src="<?php echo $rec['picture'];?>" width="100" height="100"/>
<input name="picture" type="file" value="">
</p>
and their is picture area where i call pics
<p>
<label for="picture"><strong>Picture:</strong> </label>
<img src="<?php echo $rec['picture'];?>" width="100" height="100"/>
<input name="picture" type="file" value="">
</p>
Just a quick guess by looking at your code, you are not escaping the value of $picture when you place it in the database, which could be why the image value in the database is not updating.
Also, don't use if(!isset($_POST['picture'])), but try if (!isset($_FILES['picture']) || (isset($_FILES['picture']) && $_FILES['picture']['name'] == ""). The $_POST super global won't work, because files are sent via the $_FILES super global.
Putting it all together:
$file_name = $_FILES['picture']['name'];
$tmp_name = $_FILES['picture']['tmp_name'];
if (!isset($_FILES['picture']) || (isset($_FILES['picture']) && $_FILES['picture']['name'] == "")) {
$res = mysql_query("UPDATE student SET `id`='$id',`branch_id`='$branch_id',`class_id`='$class_id',`section_id`='$section_id',`roll_number`='$roll_number',`student_name`='$student_name',`father_name`='$father_name',`dob`='$dob',`student_address`='$student_address',`gender`='$gender',`status`='$status',`picture`='$picture',updated=now() WHERE id='$id'") or die(mysql_error());
} else {
copy($tmp_name, "images/" . $file_name)
$picture = mysql_real_escape_string("images/".$file_name);
$res = mysql_query("UPDATE student SET `id`='$id',`branch_id`='$branch_id',`class_id`='$class_id',`section_id`='$section_id',`roll_number`='$roll_number',`student_name`='$student_name',`father_name`='$father_name',`dob`='$dob',`student_address`='$student_address',`gender`='$gender',`status`='$status',updated=now() WHERE id='$id'") or die(mysql_error());
}
Also, I REALLY recommend that you use the MySQLi extension: http://php.net/manual/en/book.mysqli.php
The above code is totally untested, but should work.

How to serve multiple images which reside above the www root within a single page?

I am hoping to offer users a user submitted image gallery. I have written a upload script which saves the file above the www root. I know I can serve the file by specifying the page header and then using readfile, however I am planning to throw the images within a table to be displayed with other information and dont think the header/readfile is the best solution. I am thinking maybe symlinks but I am not sure.
What is the best method to achieve this?
You'll need a script like getimage.php which sends the image headers and echo's out its contents. Then in your HTML, you just utilize it as the <img src=''> in your HTML. The only purpose of getimage.php is to retrieve and output the image. It remains separate from whatever PHP you use to generate the HTML sent to the browser.
Additionally, you can check if the user has a valid session and permission to view the image in getimage.php and if not, send a some kind of access-denied image instead.
The contents of getimage.php are small and simple:
// Check user permissions if necessary...
// Retrieve your image from $_GET['imgId'] however appropriate to your file structure
// Whatever is necessary to determine the image file path from the imgId parameter.
// Output the image.
$img = file_get_contents("/path/to/image.jpg");
header("Content-type: image/jpeg");
echo($img);
exit();
In your HTML:
<!-- as many as you need -->
<img src='getimage.php?imgId=12345' />
<img src='getimage.php?imgId=23456' />
<img src='getimage.php?imgId=34567' />
It then becomes the browser's job to call getimage.php?imgId=12345 as the path to the image. The browser has no idea it is calling a PHP script, rather than an image in a web accessible directory.
If the script is running on a Unix server, you might try to create a symlink in your web root that links to the directory outside of your web root.
ln -s /webroot/pictures /outside-of-webroot/uploads
If you're using an Apache server you could also have a look at mod_alias.
I've heard that there are a few issues when using mod_alias and configuring it through .htaccess. Unfortunately I don't have any experience with mod_alias whatsoever.
Something that always has worked well for me is to have users upload their images directly into my mysql db. The PHP will encode into base64 and store into a blob. Then you do something similar to what michael said to retrieve and display the image. I've included some code from a project I was working on in 2008. I wouldn't copy it exactly if it's a method you're interested in using since it's old code.
This is the PHP to upload and store into a DB. Obviously replace your info and connect to your own DB.
<?php
include("auth.php");
// uploadimg.php
// By Tyler Biscoe
// 09 Mar 2008
// Test file for image uploads
include("connect.php");
include("include/header.php");
$max_file_size = 786432;
$max_kb = $max_file_size/1024;
if($_POST["imgsubmit"])
{
if($_FILES["file"]["size"] > $max_file_size)
{
$error = "Error: File size must be under ". $max_kb . " kb.";
}
if (!($_FILES["file"]["type"] == "image/gif") && !($_FILES["file"]["type"] == "image/jpeg") && !($_FILES["file"]["type"] == "image/pjpeg"))
{
$error .= "Error: Invalid file type. Use gif or jpg files only.";
}
if(!$error)
{
echo "<div id='alertBox'> Image has been successfully uploaded! </div>";
$handle = fopen($_FILES["file"]["tmp_name"],'r');
$file_content = fread($handle,$_FILES["file"]["size"]);
fclose($handle);
$encoded = chunk_split(base64_encode($file_content));
$id = $_POST["userid"];
echo $_FILES["file"]["tmp_name"];
$default_exist_sql = "SELECT * FROM members WHERE id='".$id."'";
$default_result = mysql_query($default_exist_sql);
$results = mysql_fetch_array($default_result);
if(!$results["default_image"])
{
$insert_sql = "UPDATE members SET default_image = '$encoded' WHERE id='". $id ."'";
mysql_query($insert_sql);
}
$sql = "INSERT INTO images (userid, sixfourdata) VALUES ('$id','$encoded')";
mysql_query($sql);
}
else
{
echo "<div id='alertBox'>". $error . "</div>";
}
}
?>
<br />
<font class="heading"> Upload images </font>
<br /><br />
<form enctype = "multipart/form-data" action = "<?php $_SERVER['PHP_SELF']; ?>" method = "post" name = "uploadImage">
<input type = "hidden" name="userid" value = "<?php echo $_GET["userid"]; ?>" >
<input id="stextBox" type="file" name="file" size="35"><br />
<input type="submit" name="imgsubmit" value="Upload">
</form>
<?php include("include/footer.php"); ?>
This next one displays the file:
<?php
// image.php
// By Tyler Biscoe
// 09 Mar 2008
// File used to display pictures
include("connect.php");
$imgid = $_GET["id"];
$result = mysql_query("SELECT * FROM images WHERE imgid=" . $imgid . "");
$image = mysql_fetch_array($result);
echo base64_decode($image["sixfourdata"]);
echo $image["sixfourdata"];
?>
Then:
<img src="image.php?id=your_img_id">

Getting an image from a database using PHP

first time using stack overflow.
I have followed the following 2 part youtube tutorial on uploading/storing an image in a MYSQL database. I have followed the instructions but my image is not appearing for me. I use connect.php to connect to the database, this appears to be working fine. It seems the problem is with get.php as when I test echoing any images from it I always get no image.
used phpmyadmin to create the database and am using xampp.
here is the link to the youtube tutorials
http://www.youtube.com/watch?v=CxY3FR9doHI
http://www.youtube.com/watch?v=vFZfJZ_WNC4&feature=fvwrel
Included are the files
<html>
<head>
<title>Upload an image</title>
</head>
<body>
<form action="index.php" method="POST" enctype="multipart/form-data">
File:
<input type="file" name="image"> <input type="submit" value="Upload">
</form>
<?php
include 'connect.php';
//file properties
$file = $_FILES['image']['tmp_name'];
if(!isset($file))
echo "Please select an image.";
else{
$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.";
else{
if(!$insert = mysql_query("INSERT INTO store VALUES('','$image_name','$image')"))
echo"Problem uploading image";
else{
$lastid = mysql_insert_id();
echo "image uploaded.<p />your image:<p /><img src=get.php?id=$lastid>";
}
}
}
?>
</body>
</html>
Here is get.php
<?php
include 'connect.php';
$id=stripslashes($_REQUEST('id'));
$image = mysql_query("SELECT * FROM store WHERE id=$id");
$image = mysql_fetch_assoc($image);
$image=$image('image');
header("content-type: image/jpeg");
?>
And finally connect
<?php
// connect to database
$db_host="localhost";
$db_username="root";
$db_pass="";
$db_name="test";
#mysql_connect("$db_host","$db_username","$db_pass") or die("Could not connect to mysql");
mysql_select_db("$db_name")or die("Cant find database");
?>
Your get.php doesn't echo $image.
Also $image=$image('image'); should be $image=$image['image'];, and $_REQUEST('id') should be $_REQUEST['id'].
P.S. Don't use addslashes to prevent against SQL injections. Use mysql_real_escape_string.
You never echo the image data in get.php, so you're serving a blank 0-byte image.
You are missing a line after the header output
header("content-type: image/jpeg");
echo $image;
Very quick glance, in get.php change:
$image=$image('image');
to
$image=$image['image'];
mysql_fetch_assoc() converts the results into an array.
You better of bas64_encoding an decoding that way none ansi chars wont create a problem.
base64_encode(file_get_contents($_FILES['image']['tmp_name']));
This is wrong as array is [] not ()
include 'connect.php';
$id=stripslashes($_REQUEST('id'));
$image = mysql_query("SELECT * FROM store WHERE id=$id");
$image = mysql_fetch_assoc($image);
$image=$image['image'];
header("content-type: image/jpeg");
echo base64_decode($image);
Piece of code I use in a site of mine:
<?php
ob_start();
require_once("db.php.lib");
DBLogin();
$sql = "select pic_user_id, pic_full_data as bindata, pic_full_mime as mime, pic_full_size as size from pics where pic_name = '".urldecode($_GET["pic_name"])."'";
$result = DBExec($sql);
if ($result)
{
$row = DBGetNextRow($result);
if ($row)
{
header("Content-type: ".$row["mime"]);
header("Content-length: ".$row["size"]);
ob_clean();
echo $row["bindata"];
ob_end_flush();
}
}
?>
It looks like you're leaving out the actual output of the image data, and the length might be required by some browsers...

Categories