i am using this curl class for saving the file -->
class CurlHelper
{
/**
* Downloads a file from a url and returns the temporary file path.
* #param string $url
* #return string The file path
*/
public static function downloadFile($url, $options = array())
{
if (!is_array($options))
$options = array();
$options = array_merge(array(
'connectionTimeout' => 5, // seconds
'timeout' => 10, // seconds
'sslVerifyPeer' => false,
'followLocation' => false, // if true, limit recursive redirection by
'maxRedirs' => 1, // setting value for "maxRedirs"
), $options);
// create a temporary file (we are assuming that we can write to the system's temporary directory)
$tempFileName = tempnam(sys_get_temp_dir(), '');
$fh = fopen($tempFileName, 'w');
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_FILE, $fh);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, $options['connectionTimeout']);
curl_setopt($curl, CURLOPT_TIMEOUT, $options['timeout']);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, $options['sslVerifyPeer']);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, $options['followLocation']);
curl_setopt($curl, CURLOPT_MAXREDIRS, $options['maxRedirs']);
curl_exec($curl);
curl_close($curl);
fclose($fh);
return $tempFileName;
}
}
$url = 'http://graph.facebook.com/shashankvaishnav/picture';
$sourceFilePath = CurlHelper::downloadFile($url, array(
'followLocation' => true,
'maxRedirs' => 5,
));
this above code will give me the temporary url in $sourceFilePath variable now i want to store that image in my image folder. I am stuck here...please help me in this...thank you in advance.
There is a pretty easy option for this:
$url = 'http://graph.facebook.com/shashankvaishnav/picture';
$data = file_get_contents($url);
$fileName = 'fb_profilepic.jpg';
$file = fopen($fileName, 'w+');
fputs($file, $data);
fclose($file);
You don´t even need anything else then.
Or if file_get_contents is disabled (usually it isn´t), this should also work:
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, 'http://graph.facebook.com/shashankvaishnav/picture');
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
curl_close($ch);
$fileName = 'fb_profilepic.jpg';
$file = fopen($fileName, 'w+');
fputs($file, $data);
fclose($file);
Edit: This is not possible anymore, since you can´t use the username for API calls anymore. You have to use an (App Scoped) ID after authorizing a User with the Facebook API instead of the username.
$filename = 'abcd.jpg';
$to = 'image/'.$filename;
if(copy($sourceFilePath,$to))
echo 'copied';
else
echo 'error';
$profile_Image = 'http://graph.facebook.com/shashankvaishnav/picture';
$userImage = $picturtmp_name . '.jpg'; // insert $userImage in db table field.
$savepath = '/images/';
insert_user_picture($savepath, $profile_Image, $userImage);
function insert_user_picture($path, $profile_Image, $userImage) {
$thumb_image = file_get_contents($profile_Image);
$thumb_file = $path . $userImage;
file_put_contents($thumb_file, $thumb_image);
}
$fbprofileimage = file_get_contents('http://graph.facebook.com/senthilbp/picture/');
file_put_contents('senthilbp.gif', $fbprofileimage);
Related
I have a problem with Joining 2 functions, So I am use https://github.com/spatie/pdf-to-image - this function for convert uploaded pdf(s) to image(s). this is working fine, but this function uploads converted images to the local directory, but i want to change it and save converted images to the yandex disk not a local directory. my function with curl for upload files to yandex disk working fine too, but i dont know how to join this 2 functions,
I want to change $pdf->setPage($pageNumber)->saveImage($pageNumber . '.jpg'); to uploadtoyandexdisk("folder", "", $pageNumber . '.jpg'); for uploading to yandex disk, can you help ?
//edited code
if(!empty($_FILES["fileToUpload"])){
error_reporting(E_ALL);
ini_set("display_errors", 1);
function uploadtoyandexdisk($folder, $file, $name) {
if(empty($file)){
$filename = $name;
$filepath = $_FILES["fileToUpload"]["tmp_name"];
} else{
$filename = $name;
$filepath = $file;
}
$yandexusername = "username";
$yandexpassword = "password";
$credentials = array($yandexusername,$yandexpassword);
$filesize = filesize($filepath);
$fh = fopen($filepath, 'r');
$remoteUrl = 'https://webdav.yandex.ru/uploads/'.$folder.'/';
$ch = curl_init($remoteUrl . $filename);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_USERPWD, implode(':', $credentials));
curl_setopt($ch, CURLOPT_PUT, true);
curl_setopt($ch, CURLOPT_INFILE, $fh);
curl_setopt($ch, CURLOPT_INFILESIZE, $filesize);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
$response=curl_exec($ch);
fclose($fh);
echo $response;
}
include "../inc/extensions/pdftoimage/Pdf.php";
$pdf = new Spatie\PdfToImage\Pdf($_FILES["fileToUpload"]["tmp_name"]);
foreach (range(1, $pdf->getNumberOfPages()) as $pageNumber) {
$pdf->setCompressionQuality(50);
$pdf->setPage($pageNumber)
->saveImage($pageNumber . '.jpg');
$imgdata = $pdf->setPage($pageNumber)->getImageData($pageNumber . '.jpg');
uploadtoyandexdisk("uploads", $imgdata, $pageNumber . '.jpg');
}
}
An easy look at the source code helps to solve the problem: while saveImage is used to save the converted data to a file, you can call getImageData with the same argument to get the raw data. If you post that raw data to the Yandex server instead of reading data from a file, you should be done
I have an old script that uploads PDF files via an API. I'm getting the error message:
Deprecated: curl_setopt(): The usage of the #filename API for file
uploading is deprecated. Please use the CURLFile class instead.
Here is the relevant code (I think this is all of it). The error points to the line: curl_setopt( $curl_handle, CURLOPT_POSTFIELDS, $postFields ).
//Upload the file
function uploadPdf( $api, $lead_id, $rev, $existing_files = array() ) {
if ( ! file_exists( SERVERPATH . "quotes/quote-". $this->id .".pdf" ) )
$this->createQuotePdf();
$files_array = array( array( 'entityType'=>'files', 'name'=>"quote-". $this->id .".pdf" ) );
// if ( $this->upfile && ! file_exists( SERVERPATH . "uploads/" . $upfile ) )
// $files_array[] = array( array( 'entityType'=>'files', 'name'=> $upfile ) );
foreach ( $existing_files as $file ) {
$files_array[] = (array) $file;
}
//this request gives us the URLs to upload to
$result = $api->editLead( array( 'leadId' => $lead_id, 'rev'=>'REV_IGNORE', 'lead'=> array( 'file' => $files_array ) ) );
//Upload the Quote file
$postFields = array();
$postFields['file'] = "#" . SERVERPATH . "quotes/quote-". $this->id .".pdf";
$postFields['type'] = "application/pdf";
$curl_handle = curl_init();
$file = array_pop( $result->file );
curl_setopt( $curl_handle, CURLOPT_URL, $file->uri );
curl_setopt( $curl_handle, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $curl_handle, CURLOPT_POST, true );
curl_setopt( $curl_handle, CURLOPT_USERPWD, USERNAME . ":" . API_KEY );
curl_setopt( $curl_handle, CURLOPT_POSTFIELDS, $postFields );
//execute the API Call
$return = curl_exec( $curl_handle ) ;
$this->uploadUpfile($api, $lead_id);
return $return;
}
My knowledge is pretty basic. But I've tried to replace:
$postFields['file'] = "#" . SERVERPATH . "quotes/quote-". $this->id .".pdf";
$postFields['type'] = "application/pdf";
with
$postFields['file'] = curl_file_create(SERVERPATH . "quotes/quote-". $this->id .".pdf", 'application/pdf', SERVERPATH . "quotes/quote-". $this->id .".pdf");
Doing the above has got rid of the error, but the underlying problem where I can't actually open the uploaded file is still happening. So I'm wondering if I've done something wrong?
From PHP 5.5 and above you should use CURLFile to upload file, I have already posted a complete answer describing CURLFile and normal file upload, you can check that answer here.
You can use CURLFile as below, feel free to adjust the code as per your need:
//Upload file using CURLFile
function upload($target, $postFields){
$file = $postFields['file'];
$cFile = new CURLFile($file,$postFields['type'], $file);
$data = array(
'file' => $cFile,
'type' => $postFields['type'],
);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $target);
curl_setopt($curl, CURLOPT_HEADER , true); //we need header
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // stop verifying certificate
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true); // enable posting
curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // post images
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true); // if any redirection after upload
curl_setopt($curl, CURLOPT_SAFE_UPLOAD, true);
$r = curl_exec($curl);
if (curl_errno($curl)) {
$error = curl_error($curl);
print_r($error);
} else {
// check the HTTP status code of the request
$resultStatus = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ($resultStatus != 200) {
print_r($resultStatus);
}else{
//successfull
print_r($r);
}
}
curl_close($curl);
}
As your file and filetype are in an array named $postFields, so you can call the above function as below:
upload($target, $postFields);
where $target is the link which you are calling to upload the file.
I'm using PHP to config a webhook for a BOT.
I'd like to send picture from another server.
I've tried this way
function bot1($chatID,$sentText) {
$botUrl = 'https://api.telegram.org/bot'.self::_BOT_TOKEN_;
$img = "https://www.server2.com/1.jpeg";
$this->sendPhoto($botUrl,$chatID,$img);
}
function sendPhoto($botUrl,$chatID, $img){
$this->sendMessage($botUrl,$chatID,'This is the pic'.$chatID);
$this->sendPost($botUrl,"sendPhoto",$chatID,"photo",$img);
}
function sendMessage($botUrl,$chatID, $text){
$inserimento = file_get_contents($botUrl."/sendMessage?chat_id=".$chatID."&text=".$text."&reply_markup=".json_encode(array("hide_keyboard"=>true)));
}
function sendPost($botUrl,$function,$chatID,$type,$doc){
$response = $botUrl. "/".$function;
$post_fields = array('chat_id' => $chatID,
$type => new CURLFile(realpath($doc))
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Content-Type:multipart/form-data"
));
curl_setopt($ch, CURLOPT_URL, $response);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
$output = curl_exec($ch);
}
But I receive only the message.
What is the problem?
I've tried to change in http but the problem persists
Well, I've done a workaround because my cUrl version seems to have a bug in uploading file.
Now I use Zend FW
$botUrl = 'https://api.telegram.org/bot'.self::_BOT_TOKEN_;
$realpath = realpath($doc);
$url = $botUrl . "/sendPhoto?chat_id=" . $chatID;
$client = new Zend_Http_Client();
$client->setUri($url);
$client->setFileUpload($realpath, "photo");
$client->setMethod('POST');
$response = $client->request();
You have to send a file, not a URL.
So:
function bot1( $chatID,$sentText )
{
$botUrl = 'https://api.telegram.org/bot'.self::_BOT_TOKEN_;
$img = "https://www.server2.com/1.jpeg";
$data = file_get_contents( $img ); # <---
$filePath = "/Your/Local/FilePath/Here"; # <---
file_put_contents( $data, $filePath ); # <---
$this->sendPhoto( $botUrl, $chatID, $filePath ); # <---
}
This is as raw example, without checking success of file_get_contents().
In my bot I use this schema, and it works fine.
I had a very simple PHP code to upload a file to a remote server; the way I was doing it (as has been suggested here in some other solutions) is to use cUrl to upload the file.
Here's my code:
$ch = curl_init("http://www.remotesite.com/upload.php");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, array('fileupload' => '#'.$_FILES['Filedata']['tmp_name']));
echo curl_exec($ch);
The server is running PHP 5.5.0 and it appears that #filename has been deprecated in PHP >= 5.5.0 as stated here under the CURLOPT_POSTFIELDS description, and therefore, I'm getting this error:
Deprecated: curl_setopt(): The usage of the #filename API for file uploading is deprecated. Please use the CURLFile class instead in ...
Interestingly, there is absolutely nothing about this Class on php.net aside from a basic class overview. No examples, no description of methods or properties. It's basically blank here. I understand that is a brand new class with little to no documentation and very little real-world use which is why practically nothing relevant is coming up in searches on Google or here on Stackoverflow on this class.
I'm wondering if there's anyone who has used this CURLFile class and can possibly help me or give me an example as to using it in place of #filename in my code.
Edit:
I wanted to add my "upload.php" code as well; this code would work with the traditional #filename method but is no longer working with the CURLFile class code:
$folder = "try/";
$path = $folder . basename( $_FILES['file']['tmp_name']);
if(move_uploaded_file($_FILES['file']['tmp_name'], $path)) {
echo "The file ". basename( $_FILES['file']['tmp_name']). " has been uploaded";
}
Final Edit:
Wanted to add Final / Working code for others looking for similar working example of the scarcely-documented CURLFile class ...
curl.php (local server)
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label> <input type="file" name="Filedata" id="Filedata" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>
<?php
if ($_POST['submit']) {
$uploadDir = "/uploads/";
$RealTitleID = $_FILES['Filedata']['name'];
$ch = curl_init("http://www.remotesite.com/upload.php");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$args['file'] = new CurlFile($_FILES['Filedata']['tmp_name'],'file/exgpd',$RealTitleID);
curl_setopt($ch, CURLOPT_POSTFIELDS, $args);
$result = curl_exec($ch);
}
?>
upload.php (remote server)
$folder = "try/";
$path = $folder . $_FILES['file']['name'];
if(move_uploaded_file($_FILES['file']['tmp_name'], $path)) {
echo "The file ". basename( $_FILES['file']['name']). " has been uploaded";
}
There is a snippet on the RFC for the code: https://wiki.php.net/rfc/curl-file-upload
curl_setopt($curl_handle, CURLOPT_POST, 1);
$args['file'] = new CurlFile('filename.png', 'image/png', 'filename.png');
curl_setopt($curl_handle, CURLOPT_POSTFIELDS, $args);
You can also use the seemingly pointless function curl_file_create( string $filename [, string $mimetype [, string $postname ]] ) if you have a phobia of creating objects.
curl_setopt($curl_handle, CURLOPT_POST, 1);
$args['file'] = curl_file_create('filename.png', 'image/png', 'filename.png');
curl_setopt($curl_handle, CURLOPT_POSTFIELDS, $args);
Thanks for your help, using your working code I was able to solve my problem with php 5.5 and Facebook SDK. I was getting this error from code in the sdk class.
I don't thinks this count as a response, but I'm sure there are people searching for this error like me related to facebook SDK and php 5.5
In case someone has the same problem, the solution for me was to change a little code from base_facebook.php to use the CurlFile Class instead of the #filename.
Since I'm calling the sdk from several places, I've just modified a few lines of the sdk:
In the method called "makeRequest" I made this change:
In this part of the code:
if ($this->getFileUploadSupport()){
$opts[CURLOPT_POSTFIELDS] = $params;
} else {
$opts[CURLOPT_POSTFIELDS] = http_build_query($params, null, '&');
}
Change the first part (with file upload enabled) to:
if ($this->getFileUploadSupport()){
if(!empty($params['source'])){
$nameArr = explode('/', $params['source']);
$name = $nameArr[count($nameArr)-1];
$source = str_replace('#', '', $params['source']);
$size = getimagesize($source);
$mime = $size['mime'];
$params['source'] = new CurlFile($source,$mime,$name);
}
if(!empty($params['image'])){
$nameArr = explode('/', $params['image']);
$name = $nameArr[count($nameArr)-1];
$image = str_replace('#', '', $params['image']);
$size = getimagesize($image);
$mime = $size['mime'];
$params['image'] = new CurlFile($image,$mime,$name);
}
$opts[CURLOPT_POSTFIELDS] = $params;
} else {
$opts[CURLOPT_POSTFIELDS] = http_build_query($params, null, '&');
}
Maybe this can be improved parsing every $param and looking for '#' in the value.. but I did it just for source and image because was what I needed.
FOR curl_setopt(): The usage of the #filename API for file uploading is deprecated. Please usethe CURLFile class instead
$img='image.jpg';
$data_array = array(
'board' => $board_id,
'note' => $note,
'image' => new CurlFile($img)
);
$curinit = curl_init($url);
curl_setopt($curinit, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curinit, CURLOPT_POST, true);
curl_setopt($curinit, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curinit, CURLOPT_POSTFIELDS, $data_array);
curl_setopt($curinit, CURLOPT_SAFE_UPLOAD, false);
$json = curl_exec($curinit);
$phpObj = json_decode($json, TRUE);
return $phpObj;
CURLFile has been explained well above, but for simple one file transfers where you don't want to send a multipart message (not needed for one file, and some APIs don't support multipart), then the following works.
$ch = curl_init('https://example.com');
$verbose = fopen('/tmp/curloutput.log', 'w+'); // Not for production, but useful for debugging curl issues.
$filetocurl = fopen(realpath($filename), 'r');
// Input the filetocurl via fopen, because CURLOPT_POSTFIELDS created multipart which some apis do not accept.
// Change the options as needed.
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_HTTPHEADER => array(
'Content-type: application/whatever_you_need_here',
'Authorization: Basic ' . $username . ":" . $password) // Use this if you need password login
),
CURLOPT_NOPROGRESS => false,
CURLOPT_UPLOAD => 1,
CURLOPT_TIMEOUT => 3600,
CURLOPT_INFILE => $filetocurl,
CURLOPT_INFILESIZE => filesize($filename),
CURLOPT_VERBOSE => true,
CURLOPT_STDERR => $verbose // Remove this for production
);
if (curl_setopt_array($ch, $options) !== false) {
$result = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
} else {
// A Curl option could not be set. Set exception here
}
Note the above code has some extra debug - remove them once it is working.
Php POST request send multiple files with curl function:
<?php
$file1 = realpath('ads/ads0.jpg');
$file2 = realpath('ads/ads1.jpg');
// Old method
// Single file
// $data = array('name' => 'Alexia', 'address' => 'Usa', 'age' => 21, 'file' => '#'.$file1);
// $data = array('name' => 'Alexia', 'address' => 'Usa', 'age' => 21, 'file[0]' => '#'.$file1, 'file[1]' => '#'.$file2);
// CurlFile method
$f1 = new CurlFile($file1, mime_content_type($file1), basename($file1));
$f2 = new CurlFile($file2, mime_content_type($file2), basename($file2));
$data = array('name' => 'Alexia', 'address' => 'Usa', 'age' => 21, 'file[1]' => $f1, 'file[2]' => $f2);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://url.x/upload.php');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false); // !!!! required as of PHP 5.6.0 for files !!!
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; rv:1.9.2) Gecko/20100115 Firefox/3.6 (.NET CLR 3.5.30729)");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); // 1, 2
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
// curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$res2 = curl_exec($ch);
echo $res2;
?>
<?php
// upload.php
$json = json_decode(file_get_contents('php://input'), true);
if(!empty($json)){ print_r($json); }
if(!empty($_GET)){ print_r($_GET); }
if(!empty($_POST)){ print_r($_POST); }
if(!empty($_FILES)){ print_r($_FILES); }
?>
I'm trying to save a users profile image on facebook using CURL. When I use the code below, I save a jpeg image but it has zero bytes in it. But if I exchange the url value to https://fbcdn-profile-a.akamaihd.net/hprofile-ak-snc4/211398_812269356_2295463_n.jpg, which is where http://graph.facebook.com/' . $user_id . '/picture?type=large redirects the browser, the image is saved without a problem. What am I doing wrong here?
<?php
$url = 'http://graph.facebook.com/' . $user_id . '/picture?type=large';
$file_handler = fopen('pic_facebook.jpg', 'w');
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_FILE, $file_handler);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_exec($curl);
curl_close($curl);
fclose($file_handler);
?>
There is a redirect, so you have to add this option for curl
// safemode if off:
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
but if you have safemode if on, then:
// safemode if on:
<?php
function curl_redir_exec($ch)
{
static $curl_loops = 0;
static $curl_max_loops = 20;
if ($curl_loops++ >= $curl_max_loops)
{
$curl_loops = 0;
return FALSE;
}
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
#list($header, $data) = #explode("\n\n", $data, 2);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($http_code == 301 || $http_code == 302)
{
$matches = array();
preg_match('/Location:(.*?)\n/', $header, $matches);
$url = #parse_url(trim(array_pop($matches)));
if (!$url)
{
//couldn't process the url to redirect to
$curl_loops = 0;
return $data;
}
$last_url = parse_url(curl_getinfo($ch, CURLINFO_EFFECTIVE_URL));
if (!$url['scheme'])
$url['scheme'] = $last_url['scheme'];
if (!$url['host'])
$url['host'] = $last_url['host'];
if (!$url['path'])
$url['path'] = $last_url['path'];
$new_url = $url['scheme'] . '://' . $url['host'] . $url['path'] . (#$url['query']?'?'.$url['query']:'');
return $new_url;
} else {
$curl_loops=0;
return $data;
}
}
function get_right_url($url) {
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
return curl_redir_exec($curl);
}
$url = 'http://graph.facebook.com/' . $user_id . '/picture?type=large';
$file_handler = fopen('pic_facebook.jpg', 'w');
$curl = curl_init(get_right_url($url));
curl_setopt($curl, CURLOPT_FILE, $file_handler);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_exec($curl);
curl_close($curl);
fclose($file_handler);
If you can't process the redirect, try this instead:
Make the request to https://graph.facebook.com/<USER ID>?fields=picture and parse the response, which will be in JSON format and look like this - e.g. for Zuck you get this response:
{
"picture": "http://profile.ak.fbcdn.net/hprofile-ak-snc4/157340_4_3955636_q.jpg"
}
Then make your curl request directly to retrieve the image from that cloud storage URL
set
CURLOPT_FOLLOWLOCATION to true
so that it follows the 301/302 redirect the reads the image file from final location.
i.e.
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
I managed to do it this way, works perfectly fine:
$data = file_get_contents('https://graph.facebook.com/[App-Scoped-ID]/picture?width=378&height=378&access_token=[Access-Token]');
$file = fopen('fbphoto.jpg', 'w+');
fputs($file, $data);
fclose($file);
You just need an App Access Token (APPID . '|' . APPSECRET), and you can specify width and height.
You can also add "redirect=false" to the URL, to get a JSON object with the URL (For example: https://fbcdn-profile-a.akamaihd.net/hprofile-ak-xpa1...)
CURLOPT_FOLLOWLOCATION has been removed in PHP5.4, so it´s not really an option anymore.