How can I upload the Facebook image in my "img" folder? - php

I'm using the Facebook php SDK to register my users with their Facebook account. I stored all the data I need in my sql database and I'm able to access the picture with:
<img src="https://graph.facebook.com/<?php echo $user;?>/picture">
I would like to store the image (the actual image not just the link) in one of my server folder so the user can change it without accessing his Facebook profile.
Is it possible to do it?

This should do what you want and put the image into images/facebook/[USERID].jpg.
Keep in mind that you should probably use cURL instead of file_get_contents so you can prepare for timeouts and long response times (which there WILL be with the facebook API.
<?php
$imageData = file_get_contents("https://graph.facebook.com/" . $user . "/picture");
file_put_contents("images/facebook/" . $user . ".jpg", $imageData);
?>
This is how you'd do it with cURL (untested, but should work):
<?php
$facebookCurl = curl_init();
curl_setopt($facebookCurl, CURLOPT_URL, "https://graph.facebook.com/" . $user . "/picture");
curl_setopt($facebookCurl, CURLOPT_HEADER, 0);
curl_setopt($facebookCurl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($facebookCurl, CURLOPT_TIMEOUT, 5);
$imageData = curl_exec($facebookCurl);
curl_close($facebookCurl);
file_put_contents("images/facebook/" . $user . ".jpg", $imageData);
?>

Related

Best bulk image download practise using curl?

I have a script running for a Laravel 5.4 webapplication that is supposed to download a big amount of images (10k). I'm wondering what the best way to handle this would be. I currently grab the base64_encode() data from the remote image and write it to a local folder with the function file_put_contents(). This works fine but some images can take more than 10 seconds to download/write, image that times a 10 thousand. Fair enough these images are rather big but I would like to see this process happen faster and thus I am asking for advice!
My current process is like this;
I read a JSON file containing all the image links I have to
download.
I convert the JSON data to an array with json_decode() and I loop through all the links with a foreach() loop and let curl handle the rest.
All the relevant parts of the code look like this:
<?php
// Defining the paths for easy access.
$__filePath = public_path() . DIRECTORY_SEPARATOR . "importImages" . DIRECTORY_SEPARATOR . "images" . DIRECTORY_SEPARATOR . "downloadList.json";
$__imagePath = public_path() . DIRECTORY_SEPARATOR . "importImages" . DIRECTORY_SEPARATOR . "images";
// Decode the json array into an array readable by PHP.
$this->imagesToDownloadList = json_decode(file_get_contents($__filePath));
// Let's loop through the image list and try to download
// all of the images that are present within the array.
foreach ($this->imagesToDownloadList as $IAN => $imageData) {
$__imageGetContents = $this->curl_get_contents($imageData->url);
$__imageBase64 = ($__imageGetContents) ? base64_encode($__imageGetContents) : false;
if( !file_put_contents($__imagePath . DIRECTORY_SEPARATOR . $imageData->filename, base64_decode($__imageBase64)) ) {
return false;
}
return true;
}
And the curl_get_contents functions looks like this:
<?php
private function curl_get_contents($url)
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
I hope someone could englighten me with possible improvements that I could apply on the current way I'm handling this mass-download.

Getting a gmail contact Photo using Curl

I have created a class managing the connection to Google Contacts API, authenticate and return the contacts.
I've successfully got the contacts list, But I didn't yet manage to get the contact photo. This is my html code :
<img src="<?= $service->getPhoto($contact['image']) ?>" />
and this is my php:
public function getPhoto($url = false){
if(!$url)
return false;
$url = urlencode($url.'&access_token='.$this->_access_token);
//echo $url.'&access_token='.$this->_access_token;
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_TIMEOUT, 15);
$image = curl_exec($curl);
curl_close($curl);
return $image;
}
Note that the $url argument is the url provided by the contacts data returned by the Google API, it's like as the following:
https://www.google.com/m8/feeds/photos/media/{userEmail}/{contactID}
This is an exemple of an URL (according to my project) :
https://www.google.com/m8/feeds/photos/media/example%40gmail.com/ABCDEFGHIJK2345
Sometimes the contactId contains a '/'
The error message from Google is :
401. That's an error.
There was an error in your request. That's all we know.
Did I miss something?
NOTE: I tried with urlencode, urldecode and tried without using them...But I got the same problem. Also, the contacts I'm testing with have gmail photos.
You are encoding your whole url and probably which is causing the mess!?
$url = $url . '&access_token=' . urlencode($this->_access_token);
I've finally solved the problem, and this is what I did:
I changed the '&' to '?' in the $url
$url.'&access_token='.$this->_access_token
changed to :
$url.'?access_token='.$this->_access_token
Since access_token is the first parameter ... and I removed the curl, I just returned the $url as it is and put it in the image src.
Although it's somehow solved, I don't know if it's okey to put the access_token in the src of the image (which can be viewed by any client side user).

PHP Upload Image from URL to Facebook [duplicate]

I'm trying to upload www hosted (e.g. http://www.google.se/intl/en_com/images/srpr/logo1w.png) files to a facebook album.
Creating an album works just fine, but I don't seem to uploading any photos. I'm using the facebook php-sdk ( http://github.com/facebook/php-sdk/ ) and the examples I already tried are:
Upload Photo To Album with Facebook's Graph API
How can I upload photos to album using Facebook Graph API
I'm guessing CURL uploads perhaps only can manage locally stored files and not web hosted ones.
Here's my code:
/*
Try 1:
$data = array();
$data['message'] = $attachment->post_title;
$data['file'] = $attachment->guid;
try {
$photo = $facebook->api('/' . $album['id'] . '/photos?access_token=' . $session['access_token'], 'post', $data);
} catch (FacebookApiException $e) {
error_log($e);
}
*/
// Try 2:
//upload photo
$file = $attachment->guid;
$args = array(
'message' => 'Photo from application',
);
$args[basename($file)] = '#' . realpath(file_get_contents($file));
$ch = curl_init();
$url = 'https://graph.facebook.com/' . $album['id'] . '/photos?access_token=' . $session['access_token'];
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $args);
$data = curl_exec($ch);
//returns the photo id
print_r(json_decode($data,true));
...where attachment->guid contains the photo url.
I'm pretty much stuck right now...
i think the problem is here:
$args[basename($file)] = '#' . realpath(file_get_contents($file));
since you want to post a picture from another source (right?), you should save it temporarily on your own host.
i also needed to do something like this, and since i had to process the image, i used the following way:
$im = #imagecreatefrompng('http://www.google.se/intl/en_com/images/srpr/logo1w.png');
imagejpeg($im, 'imgs/temp/temp.jpg', 85);
$args['image'] = '#' . realpath('imgs/temp/temp.jpg');
the rest looks fine though
I'll suggest to use the Facebook php SDK, it will be easier and the code will work with future updates of the APIs:
Using the Graph API php sdk:
$fbk = new Facebook(/* conf */);
$fbk->setFileUploadSupport(true);
//If you are executing this in a script, and not in a web page with the user logged in:
$fbk->setAccessToken(/* access token from other sources */);
//To add to an album:
$fbk->api("/$albumId/photos", "POST",
array('source' => '#'. realpath($myPhoto), 'message' => "Nice photo"));
//To upload a photo directly (the album will be created automatically):
$fbk->api("/me/photos", "POST",
array('source' => '#'. realpath($myPhoto), 'message' => "Nice photo"));
Using cURL directly:
If your really want to use cURL, your code is almost correct, but the error is in the $args array:
$args = array(
'message' => 'Photo from application',
'source' => file_get_contents($file)
);
Since the key for the photo data is source, see the Facebook Doc
Note on the # in cURL:
Also notice that the # in cUrl means that the parameter will be replaced with the actual bytes of the file that follows the #, so it isn't required if you already put in the source parameter the actual bytes.
I'm guessing CURL uploads perhaps only can manage locally stored files and not web hosted ones.
No, that’s not the case.
But you need to give the full, publicly reachable HTTP URL to the image, without an # in front – and you have to use the parameter name url for this value.
https://developers.facebook.com/docs/reference/api/photo/:
You can also publish a photo by providing a url param with the photo's URL.

How save Facebook user display picture to the disk Without using file_get_contents()`?

Hello I am trying to get the user profile picture and then merge into an existing image as per my Facebook app requirement. For that I need to check its mime time etc. But I am having difficulty in retrieving and saving the picture.
$facebook = new Facebook($config);
$user = $facebook -> getUser();
if ($user) {
$user_profile = $facebook -> api('/me');
}
//User Info. Variables:
try {
$userPpicture = $user_profile[picture];
}
Now we I have retrieved this I want to save this image on disk so I could check its mime time etc. for further processing, how can I achieve this?
p.s. due to my hosting server restrictions I can’t use the function file_get_contents(). So I need a solution except this.
Kindly help.
thank-you.
cURL try:
//Create image instances
$url = "http://graph.facebook.com/{$userId}/picture?type=large";
$dpImage = 'temp/' . $userId . '_dpImage_' . rand().'.jpg';
echo $dpImage;
function get_data($url) {
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$returned_content = get_data($url);
file_put_contents($dpImage, $returned_content);
echo "Type: " . exif_imagetype($dpImage);
getting this error while checking the mime type of the image:
Notice: exif_imagetype(): Read error! in
Are you allowed to use CURL ?
If so, just follow http://phpsense.com/2007/php-curl-functions/

PHP - Upload a web hosted photo to facebook album via Graph API

I'm trying to upload www hosted (e.g. http://www.google.se/intl/en_com/images/srpr/logo1w.png) files to a facebook album.
Creating an album works just fine, but I don't seem to uploading any photos. I'm using the facebook php-sdk ( http://github.com/facebook/php-sdk/ ) and the examples I already tried are:
Upload Photo To Album with Facebook's Graph API
How can I upload photos to album using Facebook Graph API
I'm guessing CURL uploads perhaps only can manage locally stored files and not web hosted ones.
Here's my code:
/*
Try 1:
$data = array();
$data['message'] = $attachment->post_title;
$data['file'] = $attachment->guid;
try {
$photo = $facebook->api('/' . $album['id'] . '/photos?access_token=' . $session['access_token'], 'post', $data);
} catch (FacebookApiException $e) {
error_log($e);
}
*/
// Try 2:
//upload photo
$file = $attachment->guid;
$args = array(
'message' => 'Photo from application',
);
$args[basename($file)] = '#' . realpath(file_get_contents($file));
$ch = curl_init();
$url = 'https://graph.facebook.com/' . $album['id'] . '/photos?access_token=' . $session['access_token'];
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $args);
$data = curl_exec($ch);
//returns the photo id
print_r(json_decode($data,true));
...where attachment->guid contains the photo url.
I'm pretty much stuck right now...
i think the problem is here:
$args[basename($file)] = '#' . realpath(file_get_contents($file));
since you want to post a picture from another source (right?), you should save it temporarily on your own host.
i also needed to do something like this, and since i had to process the image, i used the following way:
$im = #imagecreatefrompng('http://www.google.se/intl/en_com/images/srpr/logo1w.png');
imagejpeg($im, 'imgs/temp/temp.jpg', 85);
$args['image'] = '#' . realpath('imgs/temp/temp.jpg');
the rest looks fine though
I'll suggest to use the Facebook php SDK, it will be easier and the code will work with future updates of the APIs:
Using the Graph API php sdk:
$fbk = new Facebook(/* conf */);
$fbk->setFileUploadSupport(true);
//If you are executing this in a script, and not in a web page with the user logged in:
$fbk->setAccessToken(/* access token from other sources */);
//To add to an album:
$fbk->api("/$albumId/photos", "POST",
array('source' => '#'. realpath($myPhoto), 'message' => "Nice photo"));
//To upload a photo directly (the album will be created automatically):
$fbk->api("/me/photos", "POST",
array('source' => '#'. realpath($myPhoto), 'message' => "Nice photo"));
Using cURL directly:
If your really want to use cURL, your code is almost correct, but the error is in the $args array:
$args = array(
'message' => 'Photo from application',
'source' => file_get_contents($file)
);
Since the key for the photo data is source, see the Facebook Doc
Note on the # in cURL:
Also notice that the # in cUrl means that the parameter will be replaced with the actual bytes of the file that follows the #, so it isn't required if you already put in the source parameter the actual bytes.
I'm guessing CURL uploads perhaps only can manage locally stored files and not web hosted ones.
No, that’s not the case.
But you need to give the full, publicly reachable HTTP URL to the image, without an # in front – and you have to use the parameter name url for this value.
https://developers.facebook.com/docs/reference/api/photo/:
You can also publish a photo by providing a url param with the photo's URL.

Categories