php put_file_contents location problems, duplicate files - php

The code below fetches a jpg image from a server. if the length is larger than 1, we assume to have successfully grabbed the file. Then it proceeds to create a folder for the user if it isnt already there. (this part works)
from there, it should save the file in the /media/downloads/username location
instead it is going to /media/downloads/
I've looked at my concatenation a few times now, but I don't see where the issue is. I SEE that the filename is coming out with the username attached to the front, so I imagine its just a concatenation error.
Once this is fixed, I have a bigger issue- because I am using rand, when I cycle the script it just gives me duplicates. how can I prevent the duplicate images?!
if (strlen($data) > 1) {
$prePath = 'media/download/from_'.$sender.'_to_'.$recipient.'_id_'.$snapid.'.jpg';
if (!file_exists('media/download/'.$username)) {
mkdir('media/download/'.$username, 0777, true);
}
if (file_exists($prePath)){
$finalPath = 'media/download/'.$username.'/from_'.$sender.'_to_'.$recipient.'_id_'.$snapid.rand(0,100).'.jpg';
}
else {
$finalPath = 'media/download/'.$username.'/from_'.$sender.'_to_'.$recipient.'_id_'.$snapid.rand(0,100).'.jpg';
}
//echo "<img src='$data'></img>";
file_put_contents($finalPath, $data);
echo " <img src='".$finalPath."' alt='Smiley face' height='100' width='100'> ";
}

Related

Image (src) not refreshing after file-upload -> image [duplicate]

This question already has answers here:
PHP force refresh image
(5 answers)
Closed 2 years ago.
Having an image 'update' problem, whereby the image does not change after new file upload. the SRC attribute is designed to remain same; each uploaded file overwrites the previous one.
Let me elaborate::
I have a simple webpage, say Home.php and the page shows an image 'IMAGE1.jpg' where the image tag's src = "directory456/IMAGE1.jpg", understandably.
This homepage allows the user to change the image, through a file upload button Input type="file" (as we all know) located inside a "form". The form POSTS all the file data to another php file "Upload_File_Check.php".
Inside "Upload_File_Check.php", simple actions are performed:
(1) Check file size <2.0 MB,
(2) Check file "type" ($_FILES['filename']['type']) is one of {image/jpeg image/gif image/png}, and
(3) depending on whichever, utilizes the imagecreatefrom(gif/png/bmp)() function in PHP, to convert them ALL to jpg,
(4) ALL uploaded files are saved as "directory456/IMAGE1.jpg" using same file name hence overwriting the previous file sitting the in the directory. This way, knowing that the image's name will always be IMAGE1.jpg, I will not need to store/retrieve that from database. (comments welcome on this practice).
However, once the user clicks on the "Upload" button, and checks in "Upload_File_Check.php" are completed successfully, I would have thought that since "Home.php" is reloaded (? not sure about this), the image tag would get refreshed and now show the new image which has just been uploaded (SRC has remained same src="directory456/IMAGE1.jpg")?. The old image is showing, only upon manual page reload does the new image show.. how can I get the image tag to now refresh and load recent image pointed to ?
Code for Home.php:
<FORM method='post' action='Upload_File_Check.php' enctype='multipart/form-data'>
<INPUT type='file' name='filename_' size='10'>
<INPUT type='submit' value='upload'>
</FORM><?PHP echo $_SESSION['UPLOAD_FILE_ERR'];?>
Code for Upload_File_Check.php:
<?PHP
if($_FILES['filename_']['error'] > 0)
{ $_SESSION['UPLOAD_FILE_ERR'] .= "ERROR: ". $F_error;
header("location: HOME.PHP");}
else
{ $F_name = $_FILES['filename_']['name'];
$F_tmpnm = $_FILES['filename_']['tmp_name'];
$F_type = $_FILES['filename_']['type'];
$F_size = $_FILES['filename_']['size'];
if (!$F_tmpnm) // if file not chosen
{ $_SESSION['UPLOAD_FILE_ERR'] .= "ERROR - must have a file. "; }
if (!(($F_type == "image/bmp")||($F_type == "image/png")||($F_type == "image/jpeg")||($F_type == "image/gif")))
{ $_SESSION['UPLOAD_FILE_ERR'] .= "INVALID - only BMP JPG PNG GIF files allowed "; }
if ($F_size > 2097152)
{ $_SESSION['UPLOAD_FILE_ERR'] .= "File must be < 2.0MB "; }
if (($_SESSION['UPLOAD_FILE_ERR']) !== "")
{ header("HOME.PHP"); }
else
{ $F_destpath = "directory456/";
$F_destname = "IMAGE1.jpg";
move_uploaded_file($F_tmpnm, ($F_destpath . $F_name));
//convert MOVED file to jpg.
switch($F_type)
{ case "image/png":
$Converted_image=imagecreatefrompng($F_destpath . $F_name); break;
case "image/bmp":
$Converted_image=imagecreatefrombmp($F_destpath . $F_name); break;
case "image/gif":
$Converted_image=imagecreatefromgif($F_destpath . $F_name); break;
case "image/jpeg": break;
}
imagejpeg($Converted_image, $F_destpath . $F_destname , 90);
}
header("location: HOME.PHP");
}
?>
How do I get the IMAGE tag to refresh and point to the new image.. Would greatly appreciate your help...
New bie here, would also welcome all comments on the way I have programmed the stuff below.. what are best practices, what are faster (more efficient) methods, etc..
This question is a duplicate of PHP force refresh image.
The image isn't refreshing because the browser is caching the older file. To solve, just add a cache-busting query string to the URL in your img src. Unix timestamps work well for this. Note, however, that this will force the image to reload every time the page is loaded.
<img src="IMAGE1.jpg?t=<?php echo time() ?>">

Is that correct way that this code i using (remove file/unlink) in php

I want to ask you guys about my code in my php update form.
I use unlink($file_Path) to Remove my image file in my folder & my server and that work fine!
So I wonder when using "unlink($file_Path)" to removing an image, In my php page it show me an "Image File Icon " when there was no picture (The image file was removed) But it show me like that (Image file Icon) Because, I though It still has a some value (my value = "../filename.jpg")
so I put "value=" "/" (None Value to Reset a Value)
example :
<input type="hidden" name="newSubimage1" value=""/>
and that work fine when I use with "!empty($ro.."
example :
if (isset($row['subimage1']) && !empty($row['subimage1']))
{
echo "<img src='../images/images_products/".$row['subimage1']."'>";
} else {
echo "No Image Here"; }
`
to not show an "Image File Icon"
Is that a correct way ? that I used to Removing file / Not display an Image File Icon or you has any easy way or the best way that you want to suggest me.
thanks
$image_file_ext = array('jpg', 'png', 'bmp');
$file_ext = pathinfo($row['subimage1'],PATHINFO_EXTENSION);
if (isset($row['subimage1']) && !empty($row['subimage1']) && in_array($file_ext, $image_file_ext))
{
echo "<img src='../images/images_products/".$row['subimage1']."'>";
} else {
echo "No Image Here";
}

php string comparison not working for image metadata

I am extracting image metadata using php. The logic of my below code is that if the user uploads the default file with metadata(UserComment)=ASCIIsd11, he/she will get an error.
<?php
$exif_s = exif_read_data('e42889ed00.jpg');
$phtchk = $exif_s["UserComment"];
print $phtchk;
print strcmp($phtchk, "ASCIIsd11");
if(strcmp($phtchk, "ASCIIsd11") == 0){ echo "You have not uploaded your own photo"; exit;}
else
{
echo"You have uploaded it.";
}
?>
print $phtchk; returns ASCIIsd11
print strcmp($phtchk, "ASCIIsd11"); returns -1
and the last echo statement "You have uploaded it" is printed. Actually I am expecting strcmp() to return 0. Kindly help.
Do var_dump(phtchk); instead of print $phtchk;
Perhaps you don't see some extra-chars (eg: \n).
If it concerns the collation, you should see:
UTF-8 characters not displaying properly from JPEG IPTC data in PHP

Image pathname from mysql php doesn't display the image

So after I store a pathname of an image file in mysql php, I am having difficulty retrieving that image to display. In other words, when I do an "inspect element" the "src" value is set. However, the image doesnt display and all that is left is a square box on the page. I tried using a default profile picture that is already set for the user, just to check if its a php assigning value problem. But its not. I also checked the file contents physically and all the files are uploaded fine. The only problem is getting it to display.
Here's how I do it.
Php for checking file upload
error_reporting(E_ALL);
if($_SERVER["REQUEST_METHOD"]=="POST"&&isset($_POST["savePersonalInfo"]))
{
if(isset($_FILES["ppFile"]))
{
$name=$_FILES["ppFile"]["name"];
$tempName=$_FILES["ppFile"]["tmp_name"];
$size=$_FILES["ppFile"]["size"];
$type=$_FILES["ppFile"]["type"];
if(($type=="image/jpg"||$type=="image/jpeg"||$type=="image/pjpeg")&&( ($size>0&&$size<=4000000000))
{
$dir="C:/xampp/htdocs/hcUsers/".$_SESSION['pin']."/profilePictures";
$realPath=$dir."/".$name;
if(is_dir($dir))
{
move_uploaded_file($tempName,$realPath);
$_SESSION["ppPath"]=$realPath;
$fileQuery="UPDATE `current users` SET `ppPath`='$realPath' WHERE `id`='".$_SESSION['pin']."' " ;
checkConnect(mysql_query($fileQuery),"query of $fileQuery");
}
else
{
mkdir($dir,0777,true);
move_uploaded_file($tempName, $realPath);
$_SESSION["ppPath"]=$realPath;
$fileQuery="UPDATE `current users` SET `ppPath`='$realPath' WHERE `id`='".$_SESSION['pin']."' " ;
checkConnect(mysql_query($fileQuery),"query of $fileQuery");
}
}
else
{
print "Error".$_FILES["ppFile"]["error"];
}
}
?>
Php for retrieving the image pathname and displaying the image
<?php
session_start();
connectDatabase();
$query="SELECT * FROM `current users` WHERE `email`='".$_SESSION['email']."' AND ` `password`='".$_SESSION['password']."' ";
$result=mysql_query($query);
checkConnect($result,"query of $query");
$row=mysql_fetch_assoc($result);
$_SESSION["pin"]=$row["id"];
$imgPath="http://www.metalmusicarchives.com/images/covers/avariel-no-end-in-sight(demo)-20110719103608.jpg";
if($row["ppPath"]!="")
{
$imgPath=$row["ppPath"];
$_SESSION["ppPath"]=$imgPath;
}
?>
<p><img src="<?php echo $imgPath ?>" alt="" type="image/jpeg" class="profilePic" >
In the end the 'src' value is set but the image won't display.
Please help.
This is a part of your code:
$dir="C:/xampp/htdocs/hcUsers/".$_SESSION['pin']."/profilePictures";
$realPath=$dir."/".$name;
if(is_dir($dir))
{
move_uploaded_file($tempName,$realPath);
$_SESSION["ppPath"]=$realPath;
$fileQuery="UPDATE `current users` SET `ppPath`='$realPath' WHERE `id`='".$_SESSION['pin']."' " ;
This way, when retreiving ppPath from the database and trying to display it in a browser, the src of the image will point to C:/xampp/etc. That won't work, since your visitors don't have access to that directory. Neither do you, from a browser's perspective. Change it to a relative URL.
Furthermore I see a lot of duplicate code and you're abusing session variables, but that's offtopic.

auto hyper-link

I am trying to auto generate pages.
What I am trying to do is make a upload form for an image upload that's displayed in a gallery.
I have this but I then want each image to have a page hyper-link auto made for each image where the image can be seen bigger with buying information that's also been uploaded to a MySQL table not 100% with codeigniter I am still luring please look at the site I am trying to build at http://www.fresherdesign.co.uk/PIFF/index.php/main/gallery
This is a direct link to the gallery that I would link to make the page's from, currently they just open a direct link to the image on its own
Any help would be awesome thanks to everyone in advance
Alan Morton
If you want the actual images to be uploaded (and not stored in the database - note that db storage is slightly more difficult to accomplish than your standard upload), you can create a field in the database for the image's location; that is how you are going to correspond your image data with your page content.
Now, if you want a hyperlink to automatically be made, I suggest querying the database of all "Active" entries (again, could be another field unless you simply delete old entries). Each entry should have a unique ID associated with it. This way, when you give the list, simply include a tag similar to
while($row = mysql_fetch_array($query_result)){
// Change this to whatever formatting you need
print '<!-- Whatever content for link -->';
}
Now that's just your loop to get the results. The actual page now should query the database based on the ID given. The query should grab the page content from the database. Something like this would work
<?php
if(!isset($_GET['id'])){
die("Please use a valid link!");
}
$q = mysql_query("SELECT * FROM YOUR_DB_TABLE WHERE ID='".mysql_real_escape_string($_GET['id'])."' LIMIT 1;");
if(!$q || mysql_num_rows($q) < 1){
die("A MySQL Error Occurred: ".mysql_error());
}
while($row = mysql_fetch_array($q)){
// Again, adjust this accordingly
print "Data column 1: ".$row['DataRow1']."<br />".
"Data Column 2: ".$row['DataRow2']."<br />".
"<img src='".$row['ImageLocation']."' />";
}
?>
Now, I haven't tested this exact code, however all of it should work as is. But you will need to adjust it appropriately to fit your requests; but this is one way to accomplish what you're looking for.
Precondition
You'll need to have the directory name in which things are stored, relative to where your php page is located. Obviously, you have this already to create the page. I will assume it is stored in the $dir variable.
Code
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
echo "<a href='http://www.mydomain.com/".$dir."/".$file."'>";
echo "<img src='http://www.mydomain.com/".$dir."/".$file."' />";
echo "</a>";
}
}
Output
This will provide you a list of images that link to the image file itself.
Possible Modifications
1) You may want to only show some of the files in the directory, or a certain amount: Use the if block added here to do that:
if ($handle = opendir($dir)) {
//set $strThatSpecifiesImages to whatever you want;
//for the example, I'm saying that we only want to show files with "gal_image" in the filename
$strThatSpecifiesImages = "gal_image";
$maxFilesToShow = 10; //set this to whatever you want; example max is 10
$count = 0;
while (($count < $maxFilesToShow) && (false !== ($file = readdir($handle))) {
if (strpos($file, $strThatSpecifiesImages) > -1) {
echo "<a href='http://www.mydomain.com/".$dir."/".$file."'>";
echo "<img src='http://www.mydomain.com/".$dir."/".$file."' />";
echo "</a>";
$count++;
}
}
}
2) You might also want to change how things are displayed, so that you don't just have the full image shown here every time. Do this by modifying things in the echo blocks that are outputting HTML. You can have the browser resize the images, or just change it completely so that the links use text instead, or something else.

Categories