How would i not update a image from my files and database? - php

I run into this problem sometimes with the update form which contains files to upload to a database.
now to explain :I have a submit form with two input Fields. The first input is the name of the image , and the second one is the image itself. The form is submitted to upload.php as you can see the code
upload.php
if(isset($_POST['submit'])){
include 'connection.php';
$imageName=$_POST['imageName'];
$image=$_FILES['image'];
$imageTmpName=$image['tmp_name'];
$imageName=$image['name'];
$imageExt=explode('.',$imageName);
$imageExt=strtolower(end($imageExt));
$newImageName=uniqid('',true).'.'.$imageExt;
$path='C:/xampp/htdocs/test/img/'.$newImageName;
if(move_uploaded_file($imageTmpName,$path)){
echo 'file moved';
}
$query="INSERT INTO imagedata(imageName,image) VALUES ('$imageName','$newImageName')";
if(mysqli_query($conn,$query)){
echo 'data posted to database';
}
}
You can see from the code that I am moving the image temporary name to my path and in the same time I'm and storing the new image name into the database.
I am using the same principle update the image name and the image itself in a new form that is submit to update.php as show below:
if(isset($_POST['update'])){
include 'connection.php';
$uImageName=$_POST['uimageName'];
$uImage=$_FILES['uImage'];
$uImageTmpName=$Image['tmp_name'];
$uImageName=$uImage['name'];
$uImageExt=explode('.',$uImageName);
$uImageExt=strtolower(end($uImageExt));
$uNewImageName=uniqid('',true).'.'.$uImageExt;
$uPath='C:/xampp/htdocs/test/img/'.$uNewImageName;
if(move_uploaded_file($uImageTmpName,$uPath)){
echo 'file updatet';
}
$query="UPDATE imagedata SET imageName='$uImageName',image='$uNewImageName'";
if(mysqli_query($conn,$query)){
echo 'data updatet to database';
}
}
Remember that I am querying database and echo the values inside the input field values itself.Now the problem occurs in the update.php file, whenever i update the image name without uploading any new image, it will update the database with a blank image and return that to my update form.
So what i want to do is whenever i want to update the database without an image from my update form, i want the previous uploaded image to remain the same. Or if i want a new image to be uploaded to the database then i want the database to be updated with the new image and also to delete the old image that i have previous uploaded.
I want to thank you for your help with this

Simple way to keep old image if new image not selected!
Here is the easy way, create a hidden input and echo your old image name in value, and keep new image value empty as follows:
<input type="hidden" name="YourOldFile" value="YourOldFileName">
<input type="file" name="YourNewFile" value="">
Then do if statement in PHP part:
if(!empty($POST['YourNewFile'])) {
$newFile = $_POST['YourNewFile'];
// Then do your update query with uploading new image here and delete old image from the server.
} else {
$YourOldFileName = $_POST['YourOldFile'];
//Then do your query here with oldname and do not delete image from server.
}
Note: you can do same for insert and update, and you need to set where clause for update query.
UPDATE :
Displaying with or without image extention is a different question because its a part of your upload code, and how you save and display.
So, your codes in page looks like this :
include 'connection.php';
if(!empty($_FILES['uImageName'])) {
// Then do your update query with uploading new image here and delete old image from the server.
if(isset($_POST['update'])){
$uImageName=$_FILES['uimageName'];
//Your upload code doesnt look right coded to me, I would use an upload class, You can search for how to upload image
// I use verot upload class its very simple.
$uImageTmpName=$Image['tmp_name'];
$uImageName=$uImage['name'];
$uImageExt=explode('.',$uImageName);
$uImageExt=strtolower(end($uImageExt));
$uNewImageName=uniqid('',true).'.'.$uImageExt;
$uPath='C:/xampp/htdocs/test/img/'.$uNewImageName;
if(move_uploaded_file($uImageTmpName,$uPath)){
echo 'file updated';
}
$query="UPDATE imagedata SET imageName='$uImageName'";
if(mysqli_query($conn,$query)){
echo 'data updatet to database';
}
}
} else {
$YourOldFileName = $_POST['YourOldFile'];
//Then do your query here with oldname and do not delete image from server.
//Solution 1. You can update image column with your old image name.
$query="UPDATE imagedata SET image='$YourOldFileName'";
//Solution 2. You can update all other columns without image column dont update image column and dont include image column in your query.
$query="UPDATE imagedata SET yourColumnName='$DataYouWantToInsert'";
if(mysqli_query($conn,$query)){
echo 'data updatet to database';
}
}
<form>
/*Your inputs here*/
<input type="hidden" name="YourOldFile" value="YourOldFileName">
<input type="file" name="YourNewFile" value="">
/*Your buttons*/
</form>
Read comments in code.

Related

Trying to display images from a filesystem in php

Today i am looking for help. This is my first time asking so sorry in advance if I make a few mistakes
I am trying to code a small web application that will display images.Originally I used the blob format to store my images in a database, however from researching on here People suggest to use a file system. My issue is I cannot display an image. It could be a very small error or even a bad reference to a files location however I cannot make it work.
This is a small project that I hope to be able to improve on and hopefully create into a sort of photo gallery. I am running this application on a localhost.
I am having an issue with displaying images from a filesystem.
// index.php
<form action="process.php" method="post" enctype="multipart/form-data">
<input type="file" name="image" />
<input type="submit" name="submit" value="Upload" />
</form>
My form then leads to a process page where the request is dealt with.
<?php
// process.php
// connect to the database
include 'connection.php';
// take in some file data
$filename =$_FILES['image']['name'];
// get the file extension
$extension = strtolower(substr($filename, strpos($filename, '.')+1));
// if the file name is set
if(isset($filename)){
// set save destination
$saved ='images/';
// rename file
$filename = time().rand().".".$extension;
$tmp_name=$_FILES['image']['tmp_name'];
// move image to the desired folder
if(move_uploaded_file($tmp_name, $saved.$filename)){
echo "Success!";
// if success insert location into database
$insert="INSERT INTO stored (folder_name,file_name) VALUES('$saved', '$filename')";
// if the query is correct
if($result=mysqli_query($con,$insert)){
echo "DONE";
echo"</br>";
// attempt to print image
echo "<img src=getimage.php?file_name=$filename>";
}
}
}
else{
echo "Please select a photo!!";
}
?>
Now as you can see I have an < img > tag. To try and learn, I was trying to just display the recently uploaded image. To try and do this I created a getimage file.
<?php
//getimage.php
// set the page to display images
header("Content-Type: image/jpeg");
include "connection.php";
// get requested filename
$name = ($_GET['file_name']);
$query = "SELECT * FROM stored WHERE file_name=$name";
$image = mysqli_query($con,$query);
$row = mysqli_fetch_array($image,MYSQLI_ASSOC);
$img = $row['file_name'];
echo $img;
?>
My database structure is as follows:
database name = db_file.
table name = stored.
columns = folder_name, file_name
Again, this is just a small project so I know I will have to alter the database if I wish to create a larger more efficient application.
It seems you use the database lookup to get just the file name, but you already have the file name. Try adding the folder name, create a valid path.
change
$img = $row['file_name'];
to
$img = $row['folder_name'] . '/' . $row['file_name'];
check your <img>tag to see if the correct url is present. You may or may not need the '/', it depends on how you stored the folder name. You may need to add the domain name. There is just not enough information know what is needed.
Your <img> should look like this
<img href="http://www.yourdomain.com/folder name/file name">
in the end

How to delete an old upload file and upload a new file for an entry in PHP?

I am making an edit form where the user can edit item details and change the item image. The item details get updated in the database fine but the item image does now change. Below is my code...
if($_POST['item_img']){
$old_img = "img/items/$item_id.jpg";
$default_img = "img/items/default.jpg";
if (file_exists($old_img)) {
unlink($old_img);
$filename = $item_id.'.jpg';
move_uploaded_file ($_FILES["item_img"]["tmp_name"],"img/items/".$filename)
}elseif(file_exists($default_img)) {
unlink($default_img);
$filename = $item_id.'.jpg';
move_uploaded_file ($_FILES["item_img"]["tmp_name"], "img/items/".$filename);
}
}
I think it is my if($_POST['item_img']) statement that is causing this issue. What could I change the loop to.
The first nested if statement checks if there is an image attached, and the second if statement checks if a default image is attached. In both cases it deletes the old image and sets a new image with the "item_id" as its name.
Below is the code for my for upload field:
<form class="stock" method="post" enctype="multipart/form-data" action="">'
<input type="file" name="item_img">
</form>
Change it
$_POST['item_img']
To
$_FILES["item_img"]["tmp_name"]

How to populate input type file value from database in PHP? [duplicate]

This question already has an answer here:
Echo the value inside html input type=file
(1 answer)
Closed 8 days ago.
I am writing the code for editing a form that contains an input file field. I am getting all the values pulled from database for different field types but the file type input does not show its value.
I have a code that looks like this:
<input class="picturebox" id="logo" name="userfile" value="<?php echo $discount_details->picture_name;?>" />
But actually in rendered view value attribute is null for userfile field.
How do I load the value of input type when someone is editing the form and does not want to alter the picture entered earlier by him upon edit.
you can give the value attribute to input file type
if you want to show the file content while updating form you can show it in separate tag
like:
<input type="file" /> <span><?php echo $row[column_name]?></span>
here you should consider one thing
if the use is selected new file to upload you can update the column else the use not selected any thing just updated other content without file you should update the column name with old file name.
$file = $_FILES['file']['name'];
if($file!="") {
move_uploaded_file($_FILES['file']['tmp_name'],'/image/'.$file);
} else {
$file = $oldfile;
}
You can just make value field empty and show your old image at just up of that input field(or below).then check after submitting form, if $_POST['userfile'] is empty don't update table.picture_name.
The simple trick is that ; give an id to the tag
<input type="file" name="file" /> <span name="old" value="<?=$row[column_name]?>"><?php echo $row[column_name]?></span>
Then in PHP make it like this:
$oldfile = $_POST['old'];
$file = $_FILES['file']['name'];
if($file!="") {
move_uploaded_file($_FILES['file']['tmp_name'],'/image/'.$file);
} else {
$file = $oldfile;
}
you can write this way
Step 1: Fetch your image in a variable. like this $pimg = $result['pimage'];
Step 2: write html code for add file. <input type="file" name=""image">
Step3: in PHP fetch the file if image upload by user. like this $pimage = $_FILES['images']['name'];
Step 4: now check if the user uploaded the file or not.
if(empty(file name)){
if yes then update image it.
}else{
if no then priviously uploaded image use it.
}

PHP: Properly storing image names in MySQL DB

I am storing images name inside on MySQL database. Everytime I perform an upload, I have it return a link back with the image name attached which then I extract the image name and saved to the database. I have corrections to some critical flaws but I am still facing issues of having blank spaces/ duplicate names inserted into my database even though I have established checkpoints.
How can I avoid duplication/blank spaces of file names?
Is there a better approach in storing names in DB?
Location of image inside webserver:
http://www.example.com/imageupload/uploads/medium/50038dc14afb7.jpg
Link in the browser:
http://www.example.org/imageupload/index.php?i=50038dc14afb7.jpg
PHP
<?
$images = retrieve_images();
insert_images_into_database($images);
function retrieve_images()
{
$images = explode(',', $_POST['i']);
return $images;
}
function insert_images_into_database($images)
{
if(!$images) //There were no images to return
return false;
$db = dbConn::getConnection();
foreach($images as $image)
{
$sql = "INSERT INTO `urlImage` (`image_name`) VALUES ( ? )";
$prepared = $db->prepare($sql);
$prepared->execute(array($image));
}
}
?>
First, the blank name issue can perharps be fixed by checking $_POST['i']:
if (!isset($_POST['i'])) {
echo "No image to upload!";
die();
}
Have you tried redirecting after uploading the image?
// When image is uploaded
header("Location: http://example.org/imageupload/index.php");
die();
you can change the image name at the time of upload,
rand() is the function, which return random value, so you can avoid the duplicate image name,
the date time option will return always new date time, so you can diffidently get unique image name
Ex.$imageName.rand().$extention;
OR
Ex. $date = new DateTime(now);
$date = $date->format('Y_m_d_H_i_s');
$imageName.$date.$extention;
a couple of things:
To make sure you have unique file names, use tempnam() (
http://php.net/manual/en/function.tempnam.php )
To avoid page reload issue, post the upload form to a different page, which redirects to a
different page (or the previous form page) after it finishes doing the upload.
This is unrelated to your question but your SQL prepared statement should be outside of the loop.

uploading image to mysql using php

I am new to php and trying to upload an image file in mysql database using php.I tried various tutorial but it didnot work for me.
Code Snippet:-
<?php
//connect to database. Username and password need to be changed
mysql_connect("localhost", "root", "");
//Select database, database_name needs to be changed
mysql_select_db("yelldb");
if (!$_POST['uploaded']){
//If nothing has been uploaded display the form
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post"
ENCTYPE="multipart/form-data">
Upload:<br><br>
<input type="file" name="image"><br><br>
<input type="hidden" name="uploaded" value="1">
<input type="submit" value="Upload">
</form>
<?php
}else{
//if the form hasn't been submitted then:
//from here onwards, we are copying the file to the directory you made earlier, so it can then be moved
//into the database. The image is named after the persons IP address until it gets moved into the database
//get users IP
$ip=$_SERVER['REMOTE_ADDR'];
//don't continue if an image hasn't been uploaded
if (!empty($image)){
//copy the image to directory
copy($image, "./temporary/".$ip."");
//open the copied image, ready to encode into text to go into the database
$filename1 = "./temporary/".$_SERVER['REMOTE_ADDR'];
$fp1 = fopen($filename1, "r");
//record the image contents into a variable
$contents1 = fread($fp1, filesize($filename1));
//close the file
fclose($fp1);
//encode the image into text
$encoded = chunk_split(base64_encode($contents1));
//insert information into the database
mysql_query("INSERT INTO servicelist (ImgData)"."VALUES ('$encoded')");
//delete the temporary file we made
//unlink($filename1);
}
}
?>
We don't save out the whole image in our database usually. We go through inserting the permanent of picture in our database. Use this php function
move_uploaded_file(file,newloc)
This will move from your temporary directory to permanent directory. Then, get path from there and insert that to the database.
Typically, you wouldn't save an entire image into an SQL database. Instead, you store the on disk path or some other 'pointer' to the actual file.
Change your code to read something like the following:
//don't continue if an image hasn't been uploaded
if (isset($_POST['image'])){
$image = $_POST['image'];
//copy the image to directory
$path = "/some/path";
move_uploaded_file($image,$path);
//store the name and path. PS: you will want to validate your input, and look
//at using prepared statements.
//Concentating values like this is NOT safe, or ideal
$location = $path . "/" . $image
mysql_query("INSERT INTO servicelist (ImgData) VALUES (" . $location . ")");
}
If however, you still wish to store the image in the SQL database, look into the blob storage type, not encoded text.
PHP move_uploaded_file

Categories