Save image from url to local System in php - php

Hi I am using the below code to download image from url but its not working when i am using this code
<?php
$imageUrl = 'https://cwsimages.ingramtest.com/cdsImages/imageloader?id=pBbFysOWRLJoSy4l4lbc+yLblU6JMuhKpze3XsQNO+njA3/XYRYbXSEYYsSqKXoiGD07duAyOSVXNUVLvxDqlMx15WtRQWJn3xC/twmM2s62tw+XgriCmEXBHawun03pQLBHXLuEQhNmCb8MC3ZMNH7pe5O76s18u/mgplf8YtU=';
#$rawImage = file_get_contents($imageUrl);
if($rawImage)
{
file_put_contents("images/".'dummy1.png',$rawImage);
echo 'Image Saved';
}
else
{
echo 'Error Occured';
}
?>
but if i changed the $imageUrl with this
$imageUrl = 'http://www.samsung.com/in/common/img/home/S2_pc.png';
it works, please suggest what is wrong in first url or can't we store image from https url

The problem is that the "images" you are using in the file_put_contents is not getting the path that where to save the file. try to make the images folder along with php file which having this code and see its working.
<?php
$imageUrl = 'https://cwsimages.ingramtest.com/cdsImages/imageloader?id=pBbFysOWRLJoSy4l4lbc+yLblU6JMuhKpze3XsQNO+njA3/XYRYbXSEYYsSqKXoiGD07duAyOSVXNUVLvxDqlMx15WtRQWJn3xC/twmM2s62tw+XgriCmEXBHawun03pQLBHXLuEQhNmCb8MC3ZMNH7pe5O76s18u/mgplf8YtU=';
#$rawImage = file_get_contents($imageUrl);
if($rawImage)
{
file_put_contents("images/".'dummy1.png',$rawImage);
echo 'Image Saved';
}
else
{
echo 'Error Occured';
}
?>

try copy
$imageUrl = 'http://www.samsung.com/in/common/img/home/S2_pc.png';
if (!file_exists('folder_name'))
{
mkdir('folder_name', 0777, true);
}
$img_path="folder_name/S2_pc.png";
copy($imageUrl , $img_path);
echo $img_path;

Related

Simple test for file_exist fails

Simplest bit of test code:-
<?php
if (file_exists('https://mywebsite/testarea/test.html')) {
echo 'File exists';
} else {
echo 'Not found';
}
?>
I run this test from my localhost (wamp). Why does this not find the file? I've double checked that it exists in the path specified. Help please.
You can use file_get_contents()
if (file_get_contents('https://mywebsite/testarea/test.html')) {
echo 'File exists';
} else {
echo 'Not found';
}
Or just built this with the help of How to check if a file exists from a url
$ch = curl_init('https://mywebsite/testarea/test.html');
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($code == 200) {
echo 'File exists';
} else {
echo 'Not found';
}
file_exists() checks whether a file or directory exists in same system where your script is running.
<?php
$filename = '/path/to/foo.txt';
if (file_exists($filename)) {
echo "The file $filename exists";
} else {
echo "The file $filename does not exist";
}
?>
If you are look for a file in remote place via http than use get_header()
<?php
$url = 'https://mywebsite/testarea/test.html';
$array = get_headers($url);
$string = $array[0];
if(strpos($string,"200")) {
echo 'url exists';
} else {
echo 'url does not exist';
}
?>
You need to use Path to the file or directory . See file_exists manual : https://www.php.net/manual/en/function.file-exists.php
and for file functions wrapper support : https://www.php.net/manual/en/wrappers.php
For your case something like,
<?php
if (file_exists('./testarea/test.html')) {
echo 'File exists';
} else {
echo 'Not found';
}
?>
On windows, use //computername/share/filename or \computername\share\filename to check files on network shares.
You are passing a file's url that is hosted somewhere else on a remote server rather than on your computer that's why it's not able to locate it.
If you have the same file in your localhost folder or anywhere on your computer where wamp has read access, it will pass through the check smoothly.
However, if you want to check if a specific url exists, then you might want to have a look at get_headers function:
$headers = get_headers('https://mywebsite/testarea/test.html');
if($headers && strpos($headers[0], 200)) {
echo 'URL exists';
} else {
echo 'URL does not exist';
}

Can't make the file_exists function work in PHP

I'm facing a problem.
I have actually this code:
// Check if image exist for the hotel
$src = '../assets/app/images/hotel-logos/007.jpg';
if(file_exists($src)) {
$src = $src;
}
else {
$src = '../assets/app/images/hotel-logos/default.jpg';
}
echo '<center><img src="'.$src.'" width="200"></center>';
This code check for an image existence.
But each time I have the fallback image default.jpg whereas I should have 007.jpg.
I check my path and it works. My 007.jpg image is into the same directory as my default.jpg image.
I already test with if(#getimagesize($src)) { ... }. The same.
Why ?
Even that your file is placed at some directory, doesn't mean that the current path of the PHP process is the same. Use the absolute path instead:
// Check if image exist for the hotel
$src = '../assets/app/images/hotel-logos/007.jpg';
if(!file_exists(__DIR__.'/'.$src)) {
$src = '../assets/app/images/hotel-logos/default.jpg';
}
echo '<center><img src="'.$src.'" width="200"></center>';
I think you are over doing it make it simpler might solve your issue Try This:
<?php
$src = '../assets/app/images/hotel-logos/007.jpg';
if (!file_exists($src)) {
$src = '../assets/app/images/hotel-logos/default.jpg';
}
echo '<center><img src="'.$src.'" width="200"></center>';
?>
Ok, I get it working by using:
$_SERVER['DOCUMENT_ROOT']
// Check if image exist for the hotel
$src = '../assets/app/images/hotel-logos/007.jpg';
if(!file_exists($_SERVER['DOCUMENT_ROOT'].'/assets/app/images/hotel-logos/007.jpg')) {
$src = '../assets/app/images/hotel-logos/default.jpg';
}
echo '<center><img src="'.$src.'" width="200"></center>';

delete image in folder and his ''mini'' size in same time

I've made a folder "../img/travaux/villa" that contain my image, so when i upload image i made a script that create a "mini" copy of this image inside a new folder "../img/travaux/villa/mini", with the same name.
now i want make a button for delete my image, but i also want that delete the "mini" image in the same time how can i make it ?
this is my code for show and delete the image, but that doesn't delete the mini image:
<?php
if (array_key_exists('delete_file', $_POST)) {
$filename = $_POST['delete_file'];
if (file_exists($filename)) {
unlink($filename);
echo 'File '.$filename.' has been deleted';
} else {
echo 'Could not delete '.$filename.', file does not exist';
}
}
$folder = glob("../img/travaux/villa/*jpg");
foreach ($folder as $picture) {
echo "<div class='divimages'>";
echo '<img src="'.$picture.'"/>';
echo '<form method="post">';
echo '<input type="hidden" value="'.$picture.'" name="delete_file" />';
echo '<input type="submit" class="delete-button" value="Delete image" />';
echo '</form>';
echo "</div>";
}
?>
You can try like this:
$fileName = basename($_POST['delete_file']);
// this will remove the path and leave only the name of the file.
$filePath = 'your full path'.'/'.$fileName;
// now build the 'mini image' full path - like '/var/www/project/img/travaux/villa/mini'.'/'.$fileName
if (file_exists($filePath)) {
unlink($filePath);
echo 'File '.$filePath.' has been deleted';
} else {
echo 'Could not delete '.$filePath.', file does not exist';
}
Note: this only deletes the 'mini' image. You'll need to add this to your existing code to also delete the main image
Just add this line of code after unlink main image:
unlink(pathinfo($filename, PATHINFO_DIRNAME).'/mini/'.pathinfo($filename, PATHINFO_BASENAME));
You should create a simple file remover function which takes an array of file names. And call the function with booth names. This is a flexible solution, because the changing parts takes place outside.
There is a vulnerability in your code, someone can delete any file from your website root folder, be careful!
You can try the following code:
$paths = array(
'orig' => '../img/travaux/villa/',
'mini' => '../img/travaux/villa/mini/',
);
if (array_key_exists('delete_file', $_POST)) {
$filename = basename($_POST['delete_file']);
foreach($paths as $path) {
if (file_exists($path.$filename)) {
if(!unlink($path.$filename)) {
$error = 'File '.$filename.' could not be deleted';
}
else {
echo 'File '.$filename.' has been deleted';
}
}
else {
$error = 'Could not delete '.$filename.', file does not exist';
}
if($error) echo $error;
}
}

PHP unlinking not working with variable

Going out of my mind with php unlinking
Here is my delete file script
$pictures = $_POST['data'];
//print_r ($pictures);
$imageone = $pictures[0];
$filename = "file:///Users/LUJO/Documents/CODE/REVLIVEGIT/wp-content/uploads/dropzone/" . $imageone;
echo $filename;
if (is_file($filename)) {
chmod($filename, 0777);
if (unlink($filename)) {
echo 'File deleted';
} else {
echo 'Cannot remove that file';
}
} else {
echo 'File does not exist';
}
The above does not work, error response is file does not exist
however if i change the filename path to this (the echo data from the echo above)
$filename = "file:///Users/LUJO/Documents/CODE/REVLIVEGIT/wp-content/uploads/dropzone/1420291529-whitetphoto.jpeg "
works fine and deletes the image.
Why can i not use the $imageone variable?
Do a print_r($pictures) to see if $pictures[0] is indeed the filename you're looking for.
Also note that if $pictures[0] is "//windows/*" you'll loose your windows if the user running PHP has administrative rights... so just using $pictures=$_POST["data"] is very VERY unsafe!

copy images issue in php

I want to copy some images from one folder to another, I do not want to copy them all.
Here is my code but it give me an issue failed to open stream
$image = "a.jpg";
$srcfile='uploads/listings/my_from/'.$image;
$dstfile='uploads/listings/my_to/images/';
copy($srcfile, $dstfile);
What am I missing? Can I do anyhting else so that I can copy selected images to destination without deleting it?
Note: both of these folders are on the same server and same project. Should I do it by curl?
It might pay to do some error checking as well, but you just need to add the full image path to your $dstfile variable:
<?php
$image = "a.jpg";
$srcfile='uploads/listings/my_from/'.$image;
$dstfile='uploads/listings/my_to/images/'.$image;
echo 'Attempting to copy "'.$srcfile.'" to "'.$dstfile.'"<br />';
if(file_exists($srcfile)) {
if(file_exists($dstfile)) {
echo 'Cannot copy file, destination file already exists';
} else {
if(is_writable(dirname($dstfile))) {
if(copy($srcfile,$dstfile)) {
echo 'File successfully copied';
} else {
echo 'File could not be copied';
}
} else {
echo 'Destination is not writable';
}
}
} else {
echo 'Cannot copy file, source file doesnt exist';
}
?>
if you are sure that file a.jpg exists, then this should work
$srcfile='uploads/listings/my_from/'.$image;
$dstfile='uploads/listings/my_to/images/'.$image;
copy($srcfile, $dstfile);
note: destination file name must be specified.
You should check it exists really.
try:
$image = "a.jpg";
$srcfile='uploads/listings/my_from/'. $image;
$dstfile='uploads/listings/my_to/images/' . $image;
if(!file_exists($srcfile) {
throw new \Exception("File does not exist!");
}
copy($srcfile, $dstfile);

Categories