PHP file_exists and save locally - php

I'm having a script that checks remote server for a file, and if it is already available locally it should use that one. If it isn't available locally, then download the image to the server. However, I'm struggling with the script overwriting images that I already have locally. If it's already available locally, the script shouldn't do anything with the file - just display it.
In some cases, the script tries to download a image that I already have - and the filesize for the file it overwrites becomes 0kb even though the file worked perfectly earlier.
What am I doing wrong here?
<?php
$url = "http://www.myserver.com/image123.jpg";
$filename = basename($url);
if(!file_exists(images/$filename))
{
// File doesn't exsist, download it!
$image = file_get_contents("$url");
file_put_contents("images/$filename", $image);
$image = "images/$filename";
} else {
// We already got this file, display it!
$image = "images/$filename";
}
echo $image;
?>

<?php
$url = "http://www.myserver.com/image123.jpg";
$filename = basename($url);
$path = "images/$filename";
if( !file_exists($path) ) {
$image = file_get_contents($url);
file_put_contents($path, $image);
}
echo $path;
?>

Related

PHP: When I save JPG image the file extension is always missing

I wrote a tiny script to create previews of all JPG images in a directory and save them into another directory. But the file extension .jpg is always missing. I really do not understand why.
foreach( glob(dirname(__FILE__)."/../../img/plakate/full/*.jpg") as $img ){
// key
$key = basename($img,'.jpg').PHP_EOL;
// save preview
$thumb = new Imagick($img);
$thumb->setImageCompression(Imagick::COMPRESSION_JPEG);
$thumb->setImageCompressionQuality(10);
$thumb->resizeImage(50,0,Imagick::FILTER_LANCZOS,1);
$thumb->writeImage("lib/img/plakate/preview/{$key}.jpg");
$thumb->destroy();
}
I also tried this which results in the same:
foreach( glob(dirname(__FILE__)."/../../img/plakate/full/*.jpg") as $img ){
// key
$key = basename($img,'.jpg').PHP_EOL;
// save preview
$thumb = new Imagick($img);
$thumb->setImageCompression(Imagick::COMPRESSION_JPEG);
$thumb->setImageCompressionQuality(10);
$thumb->resizeImage(50,0,Imagick::FILTER_LANCZOS,1);
$thumb->setImageFormat('jpeg');
file_put_contents ("lib/img/plakate/preview/{$key}.jpg", $thumb);
$thumb->destroy();
}
As I see everything works fine – only the file extension is missing. :(
Your code $key = basename($img,'.jpg').PHP_EOL; has a PHP_EOL at the end, saying that the line ends here, "discarding" anything after it when assembling your filename.
Change $key = basename($img,'.jpg').PHP_EOL; to $key = basename($img,'.jpg'); to have your file extension appended.
you can simply use it instead of basename,
$explodedPath = explode(DIRECTORY_SEPARATOR, $img);
$fileName = $explodedPath[count($explodedPath) - 1];
or pathinfo
$pathParts = pathinfo($img);
$fileName = "{$pathParts['filename]}{$pathParts['extension']}"

PHP serving image from outside of webroot

Today I was working on my website's function.php in an area that had nothing to do with serving images. I have a php script which gets images from outside of the webroot and serves them based on $_GET for the moment. One minute it was working and then the next it was not. I have no idea what happened. I chalked it up to MAC Sierra's BS server management but moving everything to a LINUX server made no difference.
<?php
include('includes/functions.php');
$path = $privatePath;
$uid = getUserProfileImage();
$img = $_GET['img'];
$file = $path."/img/users/".$uid."/".$img;
$fallback = "img/site/login.png";
//DETERMINE TYPE
$var = explode ('.', $img);
$ext = array_pop($var);
$allowed['gif'] = 'image/gif';
$allowed['png'] = 'image/png';
$allowed['jpg'] = 'image/jpeg';
$allowed['jpeg'] = 'image/jpeg';
if(file_exists($file) && $ext != '' && isset($allowed[strToLower($ext)])) {
$type = $allowed[strToLower($ext)];
} else {
$file = $fallback;
$type = 'image/png';
}
header('Content-Type: '.$type);
//header ("Content-Disposition: inline; filename=\"{$img}\");
header("Content-length: ".(string)(filesize($file)));
//echo file_get_contents($file);
readfile($file);
exit();
?>
This code was working just fine a from one min to the next. I have checked the permissions of the folder and verify that it is owned by www-data. Firefox reveals that the image has an error. Usually I had that error message when I was echoing something before the output buffer. But now it is for who knows what reason.
The RAW Data output in Firefox is as such when reading the image:
CgoKCv/Y/+EeQUV4aWYAAElJKgAIAAAADAAAAQMAAQAAAAACAAABAQMAAQAAAAACAAACAQMAAwAAAJ4AAAAGAQMAAQAAAAIAAAASAQMAAQAAAAEAAAAVAQMAAQAAAAMAAAAaAQUAAQAAAKQAAAAbAQUAAQAAAKwAAAAoAQMAAQAAAAIAAAAxAQIAHgA ...
And that goes on for a bit. I have resaved the image and about everything else that I can think of. I have even deleted all work done from prior when the script worked and no change. Anyone got any ideas? Or is there more error that I can log to see the problem and get a hint?

Image is not showing while copying from one folder to another

I am trying to copy an image from one folder to another using PHP.
Image is moving fine, but when I am opening the image, the image is not showing.
Any ideas?
Thank you.
Below is my code.
if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'image_copy') {
$image = $_POST['image'];
//name of file to be copied
$img = $image;
//read the file
$fp = fopen('files/post/' . $img, 'r') or die("Could not contact $img3");
$page_contents = "";
$new_text = fread($fp, 100);
$page_contents = $new_text;
//This moves you from the current directory user to the images directory in the new user's directory
chdir("files/profile");
//name of your new file
$newfile = $image;
//create new file and write what you read from old file into it
$fd = fopen($newfile, 'w');
fwrite($fd, $page_contents);
//close the file
fclose($fd);
exit;
}
I have made it some other way using file get content and put content .
$image = $_POST['image'];
$dir_to_save = "files/profile/";
if (!is_dir($dir_to_save)) {
mkdir($dir_to_save);
}
file_put_contents($dir_to_save . $image, file_get_contents('files/post/' . $image));
But i am unable to do in move method of php.

How to save images from list image url in csv

I want to save images from url to my directory and its image name after downloaded into a csv.
I write the following code which store images. but its not working as I want.
in below code $img is variable which fetch url from csv.
suppose I have 1000+ products in csv and every products have image url like
www.example.com/images/image1.jpg
so I want to download this image to my local directory/server directory and store its image name after download to csv file so I can add only image name into database tables.
set_time_limit(1000);
while($url = $response->fetch()) {
$my_image = file_get_contents($img);
$my_file = fopen('/csvfiles/','w+');
fwrite($my_file,$my_image);
fclose($my_file);
}
The some solution I found on other similar questions is
$file = file_get_contents($img);
file_put_contents("/csvfiles/Tmpfile.zip", fopen($img, 'r'));
But it is not applicable in my condition or not working.
Any help would be appreciated.
Edit New -
As marked as duplicate I want to add some more info here -
As I have all products info in csv formats and while importing the products I also want to download images from its url. And it is not possible to download 1000+ product image manually. I checked the above solution but it is not applicable in this situation. As in above solution they download image from only particular page and rename it directly. so it is different scenario here.
New Code - I also tried this code still not working
$content = file_get_contents("http://www.google.co.in/intl/en_com/images/srpr/logo1w.png");
$fp = fopen("/csvfiles/image.jpg", "w");
fwrite($fp, $content);
fclose($fp);
Try with the following code.
set_time_limit(1000);
while ($url = $response->fetch()) {
$my_image = file_get_contents($img);
// check stricly that you have content of image
if ($my_image !== false) {
// download the image and store in the database.
$my_file = fopen('/csvfiles/', 'w+');
fwrite($my_file, $my_image);
fclose($my_file);
}
}
You need a filename as well, not only a directory:
// download the inage from the internet:
$my_image = file_get_contents($url);
// get filename from url:
$filename = basename($url);
$path = '/csvfiles/' . $filename;
// save image to that file:
$my_file = fopen($path,'w+');
fwrite($my_file, $my_image);
fclose($my_file);
// save $filename to DB
Hi below code works for me .. hope it will help someone..
Thanks #Gavriel and #Alankar
if(!empty($img)){
$my_image = file_get_contents($img);
file_get_contents(filename)
$filename = $data[0] . ".jpg";
echo $filename. "\n";
if(!file_exists($filename))
{
$my_file = fopen($filename,'w+');
file_put_contents($filename, $my_image);
echo $filename . "\n";
}
}
$image = "/uploads/" . $filename;
echo $image . "\n";
Here $img store url of image. which is fetch from csv file.
Here data[0] is csv column which is used to store image name uniquely . so we can use file_exists(); otherwise whenever I run my script again and again it store images again and store it by random temp name.

PHP: How would you check if the result string of file_get_contents() is a JPG image?

I am using file_get_contents() to pull some images from a remote server and I want to confirm if the result string is a JPG/PNG image before further processing, like saving it locally and create thumbs.
$string = file_get_contents($url);
How would you do this?
I got from this answer the starting bits for a JPG image. So basically what you could do is to check whether the starting bits are equal or not:
$url = 'http://i.stack.imgur.com/Jh3mC.jpg?s=128&g=1';
$jpg = file_get_contents($url);
if(substr($jpg,0,3) === "\xFF\xD8\xFF"){
echo "It's a jpg !";
}
You can use getimagesize()
$url = 'http://www.geenstijl.nl/archives/images/HassVivaCatFight.jpg';
$file = file_get_contents($url);
$tmpfname = tempnam("/tmp", "FOO");
$handle = fopen($tmpfname, "w");
fwrite($handle, $file);
$size = getimagesize($tmpfname);
if(($size['mime'] == 'image/png') || ($size['mime'] == 'image/jpeg')){
//do something with the $file
echo 'yes an jpeg of png';
}
else{
echo 'Not an jpeg of png ' . $tmpfname .' '. $size['mime'];
fclose($handle);
}
I just tested it so it works. You need to make a temp file becouse the image functions work with local data and they only accept local directory path like 'C:\wamp2\www\temp\image.png'
If you do not use fclose($handle); PHP will automatically delete tmp after script ended.
You can use
exif_imagetype()
to evaluate your file. Please do check the php manual.
Edited :
Please note that PHP_EXIF must be enabled. You can read more about it here
Maybe standart PHP function exif_imagetype() http://www.php.net/manual/en/function.exif-imagetype.php

Categories