Image won't change when replaced - php

I have a piece of code to upload a picture and save it in a folder and the path in a databaseand show it on the webpage. Funny enough, upon uploading the picture for the first time, the image will show on the webpage and with change when I upload a new picture. But when I close the page, reopen it another day and decide to change the picture, the one of the webpage won't change even if i refresh the page but the one in the folder will change.
Here's my code
<?php
$sql2 = "SELECT Picture_HD FROM detailss WHERE Idn_nom = '$Indnum'";
require('connect.php');
$addr = "";
$addr = mysqli_query($conn, $sql2);
if ($addr) {
$locat = $addr->fetch_row();
$locat = (string)$locat[0];
} else {
$locat = "Pictures/default1.png";
}
mysqli_close($conn);
echo "<div id = 'Img'>";
echo "<img src = '" . $locat . "' alt = 'Passport picture/Headshot' style = 'width:80px; height:80px;'/>";
echo "</div>";
?>

Your browser is caching the image.
If you want to prevent the browser to cache the image just add a random parameter at the end of the url.
echo "<img src = '" . $locat . "?t=" . time() . "' alt = 'Passport picture/Headshot' style = 'width:80px; height:80px;'/>";

If your image is changing in your folder but you are seeing the old one on the webpage it's likely a caching issue, clear your browser cache (ctrl+f5 plus this is kinda broken so doesn't always work - so best to go into browser settings to do it, or open a private window after ctrl+f5) and if not the clear server level cache.

The best way to do this is to delete the existing image right before uploading the new one with the same file name
// define variables used for file name from session variable username the directory and extension by exploding the file name from the post method from a form with a metadata type
//set new file name to username from session variable
$filename = $_SESSION['username']
// set directory of files
$dir = "img/";
// set extension variable to file extension after posted from form
$ext=strtolower(end(explode('.',$_FILES['importimg']['name'])));
// new file upload name with existing extension
$upload_file = $dir . $filename . "." . $ext;
// delete file
// find all files with the same name any extension using variable defined above etc .txt, .php, .gif, .jpg, etc. then delete it
foreach (glob("img/$filename.*") as $deletefile) {
// unlink is used to delete the file and delete the cache of the file
unlink($deletefile);
}
// upload image
// upload file with type posted from metadata in form and upload it as your new file name using upload_file variable
if (move_uploaded_file($_FILES['importimg']['tmp_name'], $upload_file)) {
// successful upload of file add code for msg or sql query etc name to users table and redirect to profile page
echo "Successfully uploaded your file.";
} else {
// upload error show message
echo "There was an error uploading your file.";
}
Enjoy

Related

create clickable link in php

I am working with wordpress -> contact form 7 and saving the data with contact form 7 to database extension plugin.
The plugin has filters to modify data before saving into database. ([Like This Page])1
now i wanted to save the file into different folder on the server and output link to that file into the admin panel. i used the filter like this.
function cfdbFilterSaveFile($formData) {
// CHANGE THIS: CF7 form name you want to manipulate
$formName = 'DemoReport';
// CHANGE THIS: upload field name on your form
$fieldName = 'Report';
// CHANGE THIS: directory where the file will be saved permanently
$uploaddir = '/home2/username/public_html/example.com/report/wp-content/uploads/reports/';
$urlDir = 'http://example.com/report/wp-content/uploads/reports/';
if ($formData && $formName == $formData->title && isset($formData->uploaded_files[$fieldName])) {
// make a copy of data from cf7
$formCopy = clone $formData;
// breakdown parts of uploaded file, to get basename
$path = pathinfo($formCopy->uploaded_files[$fieldName]);
// directory of the new file
$newfile = $uploaddir . $path['basename'];
// check if a file with the same name exists in the directory
if (file_exists($newfile)) {
$dupname = true;
$i = 2;
while ($dupname) {
$newpath = pathinfo($newfile);
$newfile = $uploaddir . $newpath['filename'] . '-' . $i . '.' . $newpath['extension'];
if (file_exists($newfile)) {
$i++;
} else {
$dupname = false;
}
}
}
// make a copy of file to new directory
copy($formCopy->uploaded_files[$fieldName], $newfile);
// save the path to the copied file to the cfdb database
$formCopy->posted_data[$fieldName] = $newfile;
$path = pathinfo($newfile);
$filelink = '<a href=' . $urlDir . $path['basename'] . '>' . $path['basename'] . '</a>';
$formCopy->posted_data[$fieldName . '-url'] = $filelink;
// delete the original file from $formCopy
unset($formCopy->uploaded_files[$fieldName]);
return $formCopy;
}
return $formData; }
add_filter('cfdb_form_data', 'cfdbFilterSaveFile');
Now with this code the file is saved into the folder on the server as expected but i am not able to output the clickable link to the saved file in the admin panel tables. In place of clickable links the full url is there. As in the screenshot.
ScreenShot
The output is coming as full URL (as marked 1 in screenshot), while i want the url to output as a link to the file (something like 2 in screenshot). I tried to use echo() and sprintf but got php syntex error.
Thanks for the suggestions. I have found alternate way to output links. What I have to do is output the form submission data on a webpage and convert links clickable by javascript as suggested by #Ovidash ... That is a acceptable workaround for my issue. Thanks for all the suggestions.

PHP Image Hashing in directory and database

I am still having trouble hashing my pictures when I upload them . I have this code :
$target_dir = "images/uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
hash_file('sha256', $target_file );
// Check if image file is a actual image or fake image
if(isset($_POST["change"])) {
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file);
$sql = "UPDATE users SET userPic = '".$_FILES['fileToUpload']['name']."' WHERE username = '" . $username . "'";
$check = $conn->query($sql);
if($check !== false) {
echo "<a href = profile.php> Profile pciture has been changed </a>" .
$check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
} else {
echo"did not change";
}
and I am getting this error :
Warning: hash_file(images/uploads/english_royal_family_tree.jpg): failed to open stream: No such file or directory
I have been trying for more than a week . No one is really helping and people just keep on voting down my question and aren't giving any help . Can someone please help me ?
Firstly, hash_file() is expecting a file to already exist and you're trying use that method before the file gets uploaded; that's why your code failed and threw you that error.
What you need to do is to see if that file exists and then hash it.
If this is really want you want to do, then you can base yourself on the following and remember to store the renamed file while retaining its original extension; there are links at the end of the answer.
Note: As I mentioned in comments, you need to hash the file and not the whole destination folder and the file. That would be impossible to retrieve.
Echo the variable for what was assigned to hash_file(). You will also get your hash name (only) shown minus its extension.
Check for errors and make sure the folder has been granted proper permissions.
<?php
// check for errors
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$file_name = $_FILES['fileToUpload']['name'];
$sent_file = move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file);
if (file_exists("images/uploads/" . $_FILES["fileToUpload"]["name"]))
{
echo $the_file = $_FILES["fileToUpload"]["name"] . " exists.";
// its new location and hashing the filename only.
$var = hash_file('sha256', $the_file );
echo $var;
// store your renamed file here in your database
// using the assigned $var variable.
}
Also check for errors on the query with mysqli_error($conn).
However, you're going to end up with problems here to show that image, since now and for example in using "file.jpg" will produce the following hash:
cf80cd8aed482d5d1527d7dc72fceff84e6326592848447d2dc0b0e87dfc9a90
I don't know how you plan on showing the image(s), but it will no longer keep the .jpg extension.
In order to retain the image's file extension, you basically need to rename the uploaded file(s).
Here are a few good references on Stack (that I've had success with in the past) that you can look at and implement it in your code. :
How to rename uploaded file before saving it into a directory?
Rename uploaded file (php)
There is indeed no better way to learn, IMHO.
Edit:
This is an excerpt from a script I wrote recently. Base yourself on the following.
Note: You shouldn't use hashing methods such as anything from the SHA family or MD5 as the file name, since those produce the same hash and has no uniqueness to them.
Important: If people upload from a mobile device, most of them have "image.jpg" as the default name, so it needs to be renamed and given a unique method.
Using the date and time is one way. You can also add uniqid() to it by assigning a variable to it and append to the new file name, or a combination of MD5 and uniqid() is a good bet.
You will need to do a few modifications to it of course. The $year variable is something I used but you can get rid of those instances and replace them with your own.
$year = date("Y");
$pdf_file = $_FILES['fileToUpload']["name"];
$uploaded_date = date("Y-m-d_h-i-s_A"); // this could be another unique method.
$target_dir = "../upload_folder/" . $year . "/";
$ext = explode('.',$_FILES['fileToUpload']['name']);
$extension = $ext[1];
$newname = $ext[0].'_'.$uploaded_date;
$full_local_path = $target_dir.$newname.'.'.$extension;
$new_full_name = $newname.'.'.$extension;
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $full_local_path)) {
echo "The file ". $newname . " has been uploaded.";
echo "<hr>";
$file_link = "/upload_folder/$year/$new_full_name";
// other code such as saving to a database...
}

PHP file show download link after renamed upload

Hello my PHP script i have set up uploads files via a html form.
I'm hoping to show a download link / open file link after the upload but the problem is a section of the PHP script I'm using renames the file on upload
//Create full filename including path
if ($random_name_enable = true) {
// Generate random filename
$tmp = str_replace(array('.', ' '), array('', ''), microtime());
if (!$tmp || $tmp == '') {
$out['error'][] = "File must have a name";
}
$newname = $tmp . '.' . $ext;
} else {
$newname = $name . '.' . $ext;
}
enter code here
This results in me not knowing how show a download link with the renamed uploaded file via the php solution below
The upload webpage / site is located at https://beta.filez.ml
as you can see if you try to upload a basic image is does not show the renamed download link, I need to figure out a way to get the PHP script to show a link after the rename of the upload shown below.
The Full PHP file is here for anyone interested in picking it apart
https://gist.github.com/burnsyboo/b9a9512807fc031dc9a7
Why not use Ajax? when upload is done, echo new file name that you generated, ajax takes that name and then append anchor with href with file name that you got from php and add download attribute to anchor so it downloads file when pressed
http://www.w3schools.com/tags/att_a_download.asp
Solution was to just above the $newname variable add global $newname; then at the top of the page i did $newname "";
Then where the success message was displayed i did this
$message = "<style>.php-success { color: darkgreen; font-weight: 400; font-size: 20px; }</style><p class='php-success'>File successfully Uploaded<br><br>Click here to open</p>";

Display the uploaded image after uploading on the web page

I am trying to display the image that i have uploaded and moved to the desired location. Here is the code below.
if(isset($_FILES['image']))
// image upload from upload.html
{
session_start();
$_SESSION['str'];
$_SESSION['img'];
$image = basename($_FILES["image"]["name"]);
move_uploaded_file($_FILES['image']['tmp_name'], $_SESSION['str'].'_5'.$_SESSION['img']);
//I am trying to display the uploaded pic
echo '<img src= "$image"/>';
}
The image is stored at the location $_SESSION['str']. How can i display this uploaded image.
You're using the wrong path to show the image. You're using the orginal name of the image $_FILES["image"]["name"] that was uploaded and then you use the move_uploaded_file function to move and save the file as $_SESSION['str'].'_5'.$_SESSION['img'] so that doesn't match (can't see how your session variables are created).
Also, is the location where you save the uploaded file to accessable by the client side? Move the file in the public area of your web application.
Update
I now understand from your comment that you want to save the file in a private location and then show that file in a <img> element in some HTML template.
I changed the example code to embed the uploaded image into the HTML with base64.
You can use this function for creating the embed code. I took it from the answer from this question How to embed images...
function dataUri($file, $mime)
{
$contents = file_get_contents($file);
$base64 = base64_encode($contents);
return 'data:' . $mime . ';base64,' . $base64;
}
So then you can use it like:
session_start();
// absolute path including the path to the public folder
$image_dest_path = './public/img/' . $_SESSION['str'] . '_5' . $_SESSION['img'];
// move file to server location
move_uploaded_file($_FILES['image']['tmp_name'], $image_dest_path);
// imbed the image into the HTML.
echo '<img src= "' . dataUri($image_dest_path, 'image/jpg') . '"/>';
First of you say the location is stored in $_SESSION['str'] but you try to place an image with the value of basename($_FILES["image"][""name]).
Second; you should be using session_start() at the top of your page.
Third; in order to use a variable in a string, you need to use double quotes (") in stead of single quotes ('). Like so:
echo "<img src='$_SESSION['str']">;
But I'd use this:
echo '<img src="'. $_SESSION['str'] .'" >';
Also, are you sure you're not getting any errors? If you don't see any try placing this at the top of your file:
error_reporting(E_ALL);
ini_set('display_errors', 1);
iam assuming that $_SESSION['str'] session variable is the path till the folder where the image is stored
Use the below code, give the complete url of the image:
echo "<img src = '".$_SESSION['str'].DIRECTORY_SEPARATOR.$image."'"." />";
how to call the node js method in angular js?

How to delete a file from upload folder

I am trying to delete a photo from upload folder when i press delete all records are deleted except the picture in upload folder here is my delete, how to i code the snippet to delete from upload folder
//trigger
<?php
echo '<td><a href="delete.php?staff_id=' . $row['staff_id'] . '"><input type="button" onclick="confirmDelete(event)" value="delete">';
// check if the 'staff_id' variable is set in URL, and check that it is valid
if (isset($_GET['staff_id']) && is_numeric($_GET['staff_id']))
{
// get staff_id value
$staff_id = $_GET['staff_id'];
// delete the entry
$result = mysql_query("DELETE FROM development WHERE staff_id=$staff_id") or die(mysql_error());
}
In your delete.php script you would need a line like this :
unlink( "path_to_your_upload_directory/".$staff_id.".jpg" );
If you have various file extensions : One way to achieve it is to first save the filename with extension in an appropriate database table when the user/staff uploads the file . Retrieve the same and use it when deleting the file :
$filename_with_extension = 'retrieve this from database table where it is stored';
unlink( "path_to_your_upload_directory/".$filename_with_extension );
unlink() function in PHP. You have to provide full path to that file in parameter.
NOTE: Do not give http:// path.
Use unlink function. This will remove a file from the specified directory
if(isset($_GET['staff_id'])&&is_numeric($_GET['staff_id']))
{
$Staff_Id = mysql_real_escape_string($_GET['staff_id']);
if($Staff_Id != '.' || $Staff_Id != '..')
{
$extension = '.jpg';
if(unlink('uploads/'.$Staff_Id.$extension))
{
$result = mysql_query("DELETE FROM development WHERE staff_id=$staff_id")or die(mysql_error());
}
}
}

Categories