How Do I Download Facebook Images Using cURL? - php

I have a PHP script that works just fine downloading most remote images to my file system, but when I try to download a Facebook or Instagram image I get an error that says "failed to open stream: No error in" followed by the line of my fopen function and two additional errors "fwrite() expects parameter 1 to be resource, bool given in" which is obviously due to the Facebook image not downloading.
My code is as follows:
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_BINARYTRANSFER,1);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl, CURLOPT_REFERER, "https://www.facebook.com/");
curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)');
$page = curl_exec($curl);
if(curl_errno($curl)):
echo 'Erro: ' . curl_error($curl);
exit;
endif;
curl_close($curl);
// Use basename() function to return the base name of file
$file_name = basename($url);
if(file_exists($file_name)){
unlink($file_name);
}
$fp = fopen($file_name,'x');
fwrite($fp, $page);
fclose($fp);```
There also seems to be an error when I try to add the first line of code to this post which is:
```$url = 'https://scontent-sea1-1.xx.fbcdn.net/v/t1.0-0/p180x540/119041795_176402070632464_6192328410277888324_o.jpg?_nc_cat=111&ccb=2&_nc_sid=825194&_nc_ohc=O7khk9mGFO4AX86nd5X&_nc_ht=scontent-sea1-1.xx&tp=6&oh=ff35f5eaf960fa7bd30ab1d549f0d817&oe=6045A0D1';```

Screenshot APIs are the workaround for this. There are many, but to spare the one I am using from any scrutiny for how it is being used by now I will not name the specific program. Most are basically the same, but you should choose one that allows you to install it on your own system rather than being dependent on simply getting a screenshot from a URL of theirs. That way you can encode the Facebook/Instagram image URL that you want to take a screenshot of, send the encoded URL to the API, and save the result on your file system.
The ability to encode the URL is key because of all the query strings in Facebook/Instagram image URLs.

Related

Save mp3 file from a download link on your hosting space using PHP

I am fetching data from API of a service provider (Say- http://serviceprovider.com).
From several parameter one is MP3 download Link (example- http://serviceprovider.com/storage/read?uid=475b68f2-a31b-40f8-8dfc-5af791a4d5fa_1_r.mp3&ip=255.255.255.255&dir=recording)
When I put this download link on my browser it saves it to my local PC.
Now My Problem -
I want to save this MP3 file in one of folder on my hosting space, from where I can further use it for playing using JPlayer Audio.
I have tried file_get_contents(), but nothing happened.
Thanks in advance.
Edit:
After reading Ali Answer I tried the following code, But still not working fully.
// Open a file, to which contents should be written to.
$fp = fopen("downloadk.mp3", "w");
$url = 'http://serviceprovider.com/storage/read?uid=475b68f2-a31b-40f8-8dfc-5af791a4d5fa_1_r.mp3&ip=255.255.255.255&dir=recording';
$handle = curl_init($url);
// Tell cURL to write contents to the file.
curl_setopt($handle, CURLOPT_FILE, $fp);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($handle, CURLOPT_HEADER, false);
// Do the request.
$data = curl_exec($handle);
// Clean up.
curl_close($handle);
fwrite($fp, $data);
fclose($fp);
This created the file download.mp3 file on my server but with 0 bytes, i.e. empty.
The url used here is a download link example not a mp3 file that can be played with modern browser directly.
Function file_get_contents is used for reading local files. What you have is an URL and in order to fetch the contents, you need to do a HTTP request in your script. PHP comes with the curl extension, which provides you with a stable library of functions for doing HTTP requests:
http://php.net/manual/en/book.curl.php
Using curl to download your file could be done like this:
// Open a file, to which contents should be written to.
$downloadFile = fopen("download.mp3", "w");
$url = "http://serviceprovider.com/storage/read?uid=475b68f2-a31b-40f8-8dfc-5af791a4d5fa_1_r.mp3&ip=255.255.255.255&dir=recording";
$handle = curl_init($url);
// Tell cURL to write contents to the file.
curl_setopt($handle, CURLOPT_FILE, $downloadFile);
// Follow redirects.
curl_setopt($handle, CURLOPT_FOLLOWLOCATION, true);
// Do the request.
curl_exec($handle);
// Clean up.
curl_close($handle);
fclose($downloadFile);
You should probably add some error checking.

cURL script will not download images; Instead renders junk

I have been using the following function to download pictures from a distributor for use on our website as was described here:
$url = "http://covers.stl-distribution.com/7819/lg-9781936417445.jpg";
$itemnum = 80848;
$path = "www.gullions.com/localstore/test/test.jpg";
header('Content-type: image/jpeg');
$ch = curl_init($url);
$fp = fopen("http://www.gullions.com/localstore/test/test.jpg", 'wb');
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_exec($ch);
curl_close($ch);
fclose($fp);
Instead of downloading and saving the picture, it only prints crazy characters to the screen. I know that means that for some reason the browser is trying to render the picture but most likely doesn't recognize the file type. But I can't seem to find the problem. You can see the crazy output by navigating here. To verify that the image wasn't downloaded and saved, you can navigate here. Also, FTP also shows that no file was downloaded. If you navigate to the original picture's download url you'll see that the file we are trying to download does in fact exist.
I have contacted my host and verified that no settings have been changed with the server, that cURL is functioning properly, and have even rolled back my browser to verify that a recent update didn't cause the issue. I created a test file by removing the function from the application and have tried running it separately but have only had the same results.
Add:
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
as by default this parameter is false. Docs read:
TRUE to return the transfer as a string of the return value of
curl_exec() instead of outputting it out directly.
EDIT
Setting CURLOPT_RETURNTRANSFER make curl_exec() return data, so it should be written manually, like this:
$url = "http://covers.stl-distribution.com/7819/lg-9781936417445.jpg";
$ch = curl_init($url);
$fp = fopen("./test.jpg", 'wb');
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch, CURLOPT_HEADER, 0);
fwrite($fp, curl_exec($ch));
curl_close($ch);
fclose($fp);
Also this code, that uses CURLOPT_FILE works for me just fine:
$url = "http://covers.stl-distribution.com/7819/lg-9781936417445.jpg";
$ch = curl_init($url);
$fp = fopen("./test.jpg", 'wb');
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);
so I basically suspect that your file handle is not valid, therefore cURL falls back to default output. Try this code with elementary error checking (you should ALWAYS check for errors):
$url = "http://covers.stl-distribution.com/7819/lg-9781936417445.jpg";
$fp = fopen("./test.jpg", 'wb');
if( $fp != null ) {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);
} else {
exit('ERROR: Failed to open file');
}
Note that my examples write to the same folder scripts sits in. It must work unless your server got file permissions messed badly. If it works for you, then investigate if (usually) user your scripts runs as can write to your target folder.
You haven't told your browser what type of file to expect, so it's probably defaulting to text/plain.
You need at least:
header('Content-type: image/jpeg');
As well, curl by default outputs whatever it fetches, unless you explicitly tell it you want to have the fetched data returned, or saved directly to file.

How to load an image resource from a URL into a PHP script, using cURL?

I'm using the Google Charts service to generate some QR codes that I afterward need to manipulate (e.g. rotate, scale) in a PHP script and merge with other images to generate one final image.
How do I correctly load such a resource (from a URL) into a PHP script, in a way that will allow me to manipulate it?
An example URL is: https://chart.googleapis.com/chart?cht=qr&chs=500x500&chl=xghsdfgsdfg&choe=UTF-8&chld=L|0
I currently have the following code to retrieve the image using cURL:
function getImage($url){
$ch = curl_init ($url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
$resource = curl_exec($ch);
curl_close ($ch);
return $resource;
}
But when I use it like this:
$image = imagecreatefrompng(getImage("https://chart.googleapis.com/chart?cht=qr&chs=500x500&chl=xghsdfgsdfg&choe=UTF-8&chld=L|0"));
The following error is returned:
Warning: imagecreatefrompng(‰PNG ) [function.imagecreatefrompng]: failed to open stream: No such file or directory in /home/picselbc/public_html/projects/cakemyface/preview.php on line 383
https://chart.googleapis.com/chart?cht=qr&chs=500x500&chl=xghsdfgsdfg&choe=UTF-8&chld=L|0
What you need instead of imagecreatefrompng() is imagecreatefromstring(), because the former expects a filename instead of the file contents itself.
This worked for me
$image = imagecreatefromstring(file_get_contents('http://chart.googleapis.com/chart?cht=qr&chs=500x500&chl=xghsdfgsdfg&choe=UTF-8&chld=L|0'));
header('Content-Type: image/png');
imagepng($image);
Note: I had to use http rather than https because I haven't set up ssl on my local server.

Saving thumbnails images to certain directory

I'm willing to use thumbnails into my website which is mainly like websites directory.
I've been thinking to save url thumbnails into certain directory !
Example :-
I'm going to use free websites thumbnails service that gives me code to show thumbnail image of any URL as follow
<img src='http://thumbnails_provider.com/code=MY_ID&url=ANY_SITE.COM'/>
This would show the thumbnail of ANY_SITE.COM
i want to save the generate thumbnail image into certain directory my_site.com/thumbnails
Why i'm doing this ?
in fact my database table is like my_table {id,url,image} where i'm going to give the image thumbnail random name and store its new name into my_table related to its url then i can call it back anytime and i know how to do it but i don't know how to save it into certain directory.
any help ~thanks
Using cURL should work for you:
$file = 'the URL';
$ch = curl_init ($file);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
$rawdata=curl_exec($ch);
curl_close ($ch);
$fullpath = 'path to destination';
$fp = fopen($fullpath);
fwrite($fp, $rawdata);
fclose($fp);
You could use curl to fetch the remote image. You can save it with curl_setopt($handler, CURLOPT_FILE, '/my/image/path/here.jpg');. The id could be something simple like a hash of the original URL. Obviously you'd have to check to make sure the directories exist before you save the file (using is_dir() and creating them with mkdir() if they don't).

Using cURL to save external files to my Server

I have a website to show opensource movies and videos.
I have saved urls in mysql and linked both videos as well as the images to the content server.
But users are complaining of slow website as images are getting fetched from outside and most of time Internet Explorer is not even displaying the image.
I just learnt about cURL and would like to save images as well as videos to my own server and provide mirror to original website.
I got " curl -O ('') ; " syntax at many places to do the task but don't know how to use it inside my php script.
In short:
I already have my form for url saving in mysql. I wish it to also save save file to a directory on my webserver and save file path to another column in mysql.
Any sort of help is welcome.
Thanx in Advance
$local_file = "/tmp/filename.flv";//This is the file where we save the information
$remote_file = "http://www.test.com/filename.flv"; //Here is the file we are downloading
$ch = curl_init();
$fp = fopen ($local_file, 'w+');
$ch = curl_init($remote_file);
curl_setopt($ch, CURLOPT_TIMEOUT, 50);
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_ENCODING, "");
curl_exec($ch);
curl_close($ch);
fclose($fp);
I've decided to update this answer almost 7 years later.
For those who have copy() enabled for remote hosts, you can simply use:
copy("http://www.test.com/filename.flv", "/some/local/path/filename.flv");

Categories