Download Image with Extension from URL using cURL php - 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"));

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);

Save image output from php script as file

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

How to validate mime type ( is PDF for instance ) of both a file and a variable string?

I have a bunch of PDFs that were downloaded using a scraper. This scraper didn't check to see if the file was a JPG or a PDF so by default all of them were downloaded and saved with the '.pdf' extension. So, just to clarify all the files in the batch are .pdf. However, if I try to open them(The files that are not PDF but rather JPGs) via a server or locally I'm hit with an error.
My question. Is there a way with PHP to check and see if this file is a valid PDF? I would like to run all the URLs through a loop to check these files. There are hundreds of them and it would take hours upon hours to check.
Thanks
For local files (PHP 5.3+):
$finfo = finfo_open(FILEINFO_MIME_TYPE);
foreach (glob("path/to/files") as $filename) {
if(finfo_file($finfo, $filename) === 'application/pdf') {
echo "'{$filename}' is a PDF" . PHP_EOL;
} else {
echo "'{$filename}' is not a PDF" . PHP_EOL;
}
}
finfo_close($finfo);
For remote files:
$ch = curl_init();
$url = 'http://path.to/your.pdf';
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_NOBODY, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$results = split("\n", trim(curl_exec($ch)));
foreach($results as $line) {
if (strtok($line, ':') == 'Content-Type') {
$parts = explode(":", $line);
echo trim($parts[1]); // output: application/pdf
}
}
Get MIME type of the file using function: finfo_file()
if (function_exists('finfo_open')) {
$finfo = finfo_open(FILEINFO_MIME);
$mimetype = finfo_file($finfo, "PATH-TO-YOUR-FILE");
finfo_close($finfo);
echo $mimetype;
}
echo "<pre>";
print_r($mimetype);
echo "</pre>";
Use finfo_file() function
<?php
if (function_exists('finfo_open')) {
$mime = finfo_open(FILEINFO_MIME_TYPE);
$mime_type = finfo_file($mime, "FILE-PATH");
if($mime_type == "application/pdf")
echo "file is pdf";
else
echo "file is not pdf";
finfo_close($mime);
}
Sometimes you gotta check a mime signature of a file and sometimes of a variable. These are how you do both checkings:
$filename = '/path/to/my/file.pdf';
$content = file_get_contents($filename);
$file_is_pdf = function(string $filename) : bool {
return mime_content_type($filename) === 'application/pdf';
};
$var_is_pdf = function(string $content) : bool {
$mime_type_found = (new \finfo(FILEINFO_MIME))->buffer($content);
return $mime_type_found === 'application/pdf; charset=binary';
};
// Checks if a file contains a pdf signature.
var_dump($file_is_pdf($filename));
// Checks if a variable contains a pdf signature.
var_dump($var_is_pdf($content));

php image upload from url and resize

i have this upload form and i want to resize image when uploaded
its upload form from url i did it from file upload but cant for url upload
can anyone help me?
<?php
if($_POST["sub"]){
$url = trim($_POST["url"]);
if($url){
$file = fopen($url,"rb");
if($file){
$directory = "../images/news/";
$valid_exts = array("jpg","jpeg","gif","png");
$ext = substr(basename($url), strrpos(basename($url), '.'));
$ext = str_replace('.','',$ext);
if(in_array($ext,$valid_exts)){
$rand = rand(0,9999999999);
$filename = $rand.'.'.$ext;
$newfile = fopen($directory . $filename, "wb");
if($newfile){
while(!feof($file)){
fwrite($newfile,fread($file,1024 * 8),1024 * 8);
}
echo ''."";
echo ''.$filename.'';
} else { echo 'Could not establish new file ('.$directory.$filename.') on local server. Be sure to CHMOD your directory to 777.'; }
} else { echo 'Invalid file type. Please try another file.'; }
} else { echo 'Could not locate the file: '.$url.''; }
} else { echo 'Invalid URL entered. Please try again.'; }
}
?>
Use GD or Image Magic library to resize image:
http://php.net/manual/en/imagick.resizeimage.php
http://php.net/manual/en/function.imagecopyresized.php
For saving the file from URL:
If you have allow_url_fopen set to true:
$url = 'http://example.com/image.php';
$img = '/my/folder/flower.gif';
file_put_contents($img, file_get_contents($url));
Else use cURL:
$ch = curl_init('http://example.com/image.php');
$fp = fopen('/my/folder/flower.gif', 'wb');
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);
This is the same as the answer in this post...

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..

Categories