Save image output from php script as file - php

I try to have a php script output a generated image as .jpg file:
$url = 'http://www.photopost.com/photopost/showfull.php?photo=7541';
file_put_contents('image.jpg',file_get_contents($url));
$page = file_get_contents($url);
echo $page;
The echo displays a correct image in the browser.
but image.jpg is not saved.
How can I make this work ?

You need to output a Content-Type header with a proper MIME type for the browser to be able to understand what kind of file the server is sending.
header('Content-Type: image/jpeg');
Refer to http://php.net/manual/en/function.header.php and https://www.sitepoint.com/web-foundations/mime-types-complete-list/ for a list of valid MIME types.

Getting image from url using curl :-
$profile_Image = 'http://www.photopost.com/photopost/showfull.php?photo=7541'; //image url
$userImage = 'myimg.jpg'; // renaming image
$path = ''; // your saving path
$ch = curl_init($profile_Image);
$fp = fopen($path . $userImage, 'wb');
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
$result = curl_exec($ch);
curl_close($ch);
fclose($fp);
Getting image from url using file_get_contents :-
$profile_Image = 'http://www.photopost.com/photopost/showfull.php?photo=7541'; //image url
$userImage = 'myimg.jpg'; // renaming image
$path = ''; // your saving path
$thumb_image = file_get_contents($profile_Image);
if ($http_response_header != NULL) {
$thumb_file = $path . $userImage;
file_put_contents($thumb_file, $thumb_image);
}

Change your url from
http://www.photopost.com/photopost/showfull.php?photo=7541 //html document
to
http://www.photopost.com/photopost/watermark.php?file=7541 //downloadable url
Then use code from other answers or use imagecreatefromjpeg
http://php.net/manual/en/function.imagecreatefromjpeg.php

Related

Save image from PHP URL - returns empty image

I'm working on a small project where I read data from electronic identity cards.
It might be worth mentioning I'm using the LightOpenID PHP library to get $attributes[''] with all the data from the eID.
Now I'm stuck trying to save an image which is displayed on http://my-url.com/photo.php
photo.php contains:
<?php
session_start();
$photo = $_SESSION['photo'];
header('Content-Type: image/jpeg');
echo($photo);
The variable $photo contains $_SESSION['photo'] which comes from index.php:
function base64url_decode($base64url) {
$base64 = strtr($base64url, '-_', '+/');
$plainText = base64_decode($base64);
return ($plainText);
}
$encodedPhoto = $attributes['eid/photo'];
$photo = base64url_decode($encodedPhoto);
$_SESSION['photo'] = $photo;
The images are both perfectly visible on index.php (<?php echo '<img src="photo.php"/>'; ?>) as well as on photo.php.
I've read up on a few similar topics and tried the following methods:
cURL
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://my-url.com/photo.php');
$fp = fopen('./photo/' . $filename . '.jpg', 'wb');
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch); curl_close($ch);
fclose($fp);
File_put_contents
$input = "my-url.com/photo.php";
$output = './photo/' . $filename . '.jpg';
file_put_contents($output, file_get_contents($input));
copy
Even tried a basic copy:
copy( "http://my-url/photo.php", './photo/' . $filename . '.jpg');
All 3 methods create an empty .jpg file in the directory I want them too.
Let me know if I need to provide any extra code.
Hope there's someone who can point out my mistakes
Finally found a solution.
I decode the base64url only once with:
function base64url_decodeOnce($base64url){
$base64 = strtr($base64url, '-_', '+/');
return ($base64);
}
that way I can use the $base64 output for:
$data = 'data:image/jpeg;base64,' . $base64data .'\'';
list($type, $data) = explode(';', $data);
list(, $data) = explode(',', $data);
$data = base64_decode($data);
file_put_contents('./photo/' . $filename . '.jpg', $data);

Download Image with Extension from URL using cURL php

I am trying to download GooglePlay app's icons from links provided.
eg. https://lh5.ggpht.com/j0y0xf18PF8iZ_qyKekah11Gg7fteqhqm_VC0SQg7oMsIyMPato7Z_zBsGmOtTf2Fw=w300
now when i am downloading the image, using cURL, using the following code
function scaleImageAndSaveIt($appName,$imageURL){
$format="_%d_%m_%Y_%H_%M_%S";
$strf=strftime($format);
$imageLocnName = $appName . $strf ;
$ch = curl_init($imageURL);
$fp = fopen($imageLocnName, 'wb');
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, true);
$resp = curl_exec($ch);
echo $resp;
curl_close($ch);
fclose($fp);
return $imageLocnName; }
Now when i am try to save image, i do not have any file extension. (.png, or .jpg or anything else). Though, when i manually save the image, i get the image extension as PNG.
How do i either download the image with default image name and extension or how can I find the extension. Any of the solution would be helpful for me.
try something like this, and based on the return value decide which extension to use:
function GetMimeType($path)
{
//$type = mime_content_type($file); //deprecated
/* //file info -> normal method, but returns wrong values for ics files..
$finfo = finfo_open(FILEINFO_MIME_TYPE); // return mime type ala mimetype extension
$type = $filename.":".finfo_file($finfo, $filename);
finfo_close($finfo);
*/
$forbiddenChars = array('?', '*', ':', '|', ';', '<', '>');
if(strlen(str_replace($forbiddenChars, '', $path)) < strlen($path))
throw new \Exception("Forbidden characters!");
$path = escapeshellarg($path);
ob_start();
$type = system("file --mime-type -b ".$path);
ob_clean();
return $type;
}
function GuessExtension($path)
{
$type = GetMimType($path);
$extension = "";
switch($type)
{
case "image/png":
$extension = ".png";
break;
case "image/jpeg":
default:
$extension = ".jpg";
break;
}
}
//use it like this:
var_dump(GuessExtension("/path/to/your/saved/file"));

How Can php know if the image has been loaded fully?

I wrote a PHP script which simply gets URL for images and tries to download/save them on server.
My problem here is that sometimes the image is not fully loaded and the codes blow only save images partially. I did some research but couldn't figure out if I can add something to it, so it can check whether it is saving the full image or not.
Images sizes and other properties of images are random so I can't check it with those factors unless there is a way that I can get those info before loading them image.
Thank you all.
if ( $leng >= "5" ) {
define('UPLOAD_DIR', dirname(__FILE__) . '/files/');
$length = 512000;
$handle = fopen($url, 'rb');
$filename = UPLOAD_DIR . substr(strrchr($url, '/'), 1);
$write = fopen($filename, 'w');
while (!feof($handle))
{
$buffer = fread($handle, $length);
fwrite($write, $buffer);
}
fclose($handle);
fclose($write);
}else {Echo "failed";}
I think that using cURL is a better solution than using fopen for url. Check this out:
$file = fopen($filename, 'wb'); //Write it as a binary file - like image
$c = curl_init($url);
curl_setopt($c, CURLOPT_FILE, $file);
curl_setopt($c, CURLOPT_FOLLOWLOCATION, true); //Allow cURL to follow redirects (but take note that this does not work with safemode enabled)
curl_exec($c);
$httpCode = curl_getinfo($c, CURLINFO_HTTP_CODE); //200 means OK, you may check it later, just for sure
curl_close($c);
fclose($file);
Partially based on Downloading a large file using curl

How to make sure file saved by using cURL

<?php
$source = 'http://www.xxx.com/1.jpg';
$fileBody = date('YmdHis') . rand(1000, 9999);
$extension = pathinfo($source, PATHINFO_EXTENSION);
$fileName = $fileBody . '.' . $extension;
$ch = curl_init($source);
$fp = fopen($path . $fileName, 'wb');
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);
clearstatcache();
return $fileName;
This is how I grab image from internet, the image saved successfully and I will return file name for ajax to make immediately thumbnail, but sometimes php return the $fileName when it still processing download, therefore JavaScript reveal empty image on the page, how response after the file indeed been download.
curl_exec returns true on success and false on failure. Use that information.
Also, You can check curl_getinfo to make sure the transfer completed successfully and was not empty. (You get http_code there for example, as well as content_type and size_download).
$downComplete = false;
while(!$downComplete)
{
if(!file_exist($filePath))
{
sleep(1);
}
else
{
$downComplete = true;
break;
}
}
Hi,Above is an idea for check if file is completely downloaded,i think it's useful,
main idea is check saved file all the time until its finished download,then you can
display the img to front end..you can add it after your curl code,i didn't run it
myself,so just an idea..

How can I save a file url submitted in a form with curl?

I am trying to create an upload plugin that allows for a user to upload any file from their computer or from a url they type into the provided text field.
This is the script I have to upload files from a local disk:
session_start();
//Loop through each file
for($i=0; $i<count($_FILES['file']); $i++) {
//Get the temp file path
if (isset($_FILES['file']['tmp_name'][$i]))
{
$tmpFilePath = $_FILES['file']['tmp_name'][$i];
}
//Make sure we have a filepath
if ($tmpFilePath != ""){
//Setup our new file path
if (isset($_FILES['file']['name'][$i]))
$newFilePath = "./uploaded_files/" . $_FILES['file']['name'][$i];
}
//Upload the file into the temp dir
if(move_uploaded_file($tmpFilePath, $newFilePath)) {
echo "Uploaded Successfully!<br />";
}
All I need now is for the curl part to take the file from the url submitted in the text field and save it to the same location.
Here is the cURL I have so far:
function GetImageFromUrl($link) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, 0);
curl_setopt($ch,CURLOPT_URL,$link);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result=curl_exec($ch);
curl_close($ch);
return $result;
}
$sourcecode=GetImageFromUrl("http://domain.com/path/image.jpg");
$savefile = fopen('/home/path/image.jpg', 'w');
fwrite($savefile, $sourcecode);
fclose($savefile);
Is there a specific reason you want to use curl? Here's how you can simply do that without it:
$url = $_POST['url'];
$file_content = file_get_contents($url);
$file_name = array_pop(explode('/', parse_url($url, PHP_URL_PATH)));
file_put_contents('/home/path/' . $file_name, $file_content);
You should also consider looking into $url and checking if it's valid before working with it.

Categories