IMGUR file upload via PHP and cURL - php

I'm trying to upload an image to IMGUR via PHP.
This is the code:
<?
$filename = "image.jpg";
$handle = fopen($filename, "r");
$data = fread($handle, filesize($filename));
// $data is file data
$pvars = array('image' => base64_encode($data), 'mykey' => IMGUR_API_KEY);
$timeout = 30;
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'http://api.imgur.com/2/upload.xml');
curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $pvars);
$xml = curl_exec($curl);
curl_close ($curl);
?>
This is the error message I receive:
Warning: fopen(image.jpg) failed to open stream: No such file or directory
I don't understand the part: $filename = "image.jpg";
Where does the filename come from since it's a base64 generated string?
Thanks,
Bob

That warning is because fopen is trying to read in the file image.jpg from the directory from which your script is running.
A good example on how to transfer a file through curl can be seen here
Send file via cURL from form POST in PHP
Where they have $localFile = $_FILES[$fileKey]['tmp_name']; you would put $localFile = '/path/to/image.jpg'; As well as change the server info and add in any other variables you may need to pass to imgur.

Change line 1 from:
$filename = "image.jpg";
To:
$filename = $_FILES['uploaded_file']['tmp_name'];
Then, to post... I recommend a form similar to this:
<form enctype="multipart/form-data" method="post" action="upload.php" target="my_iframe">
Choose your file here:
<input name="uploaded_file" type="file"/>
<input type="submit" value="Upload It"/>
</form>
<!-- when the form is submitted, the server response will appear in this iframe -->
<script language="JavaScript">
<!--
function autoResize(id){
var newheight;
var newwidth;
if(document.getElementById){
newheight=document.getElementById(id).contentWindow.document .body.scrollHeight;
newwidth=document.getElementById(id).contentWindow.document .body.scrollWidth;
}
document.getElementById(id).height= (newheight) + "px";
document.getElementById(id).width= (newwidth) + "px";
}
//-->
</script>
<IFRAME name="my_iframe" width="100%" height="200px" id="iframe1" marginheight="0" frameborder="0" onLoad="autoResize('iframe1');"></iframe>
If you put all your php into upload.php and then have that form on a page in the same directory, it's pretty close to being functional... Except you don't yet have an API_KEY in your source.
You can get an API KEY here: https://imgur.com/register/api_anon
In the end your php should look like this:
<?
if( isset($_FILES['uploaded_file']) )
{
$IMGUR_API_KEY = 'u432ewriuq3oirefuie'; //put your api key here
$filename = $_FILES['uploaded_file']['tmp_name'];
$handle = fopen($filename, "r");
$data = fread($handle, filesize($filename));
//$data is file data
$pvars = array('image' => base64_encode($data), 'key' => $IMGUR_API_KEY);
#$pvars = array('key' => $IMGUR_API_KEY);
$timeout = 30;
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'http://api.imgur.com/2/upload.xml');
#curl_setopt($curl, CURLOPT_URL, 'http://api.imgur.com/2/gallery.xml');
curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $pvars);
$xml = curl_exec($curl);
$xmlsimple = new SimpleXMLElement($xml);
echo '<img height="180" src="';
echo $xmlsimple->links->original;
echo '">';
curl_close ($curl);
}
?>

Related

Saving PDF Curl response on server directory

I'm getting and downloading a .pdf from an URL. It's downloading directly on my PC through the Curl request.
How to save this in a directory at the server where the page is running?
I'm able to use PHP and JS, i've tried many things even combine the two languages but it seems only works the curl request, and it doesnt save that in the directory
<body>
<button id="boton">CLICK ME</button>
<?php
$name = 'file';
$file_downloaded = curl_init();
curl_setopt($file_downloaded, CURLOPT_URL, 'The url');
//curl_setopt($file_downloaded, CURLOPT_HEADER, true);
curl_setopt($file_downloaded, CURLOPT_RETURNTRANSFER, true);
curl_setopt($file_downloaded, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($file_downloaded, CURLOPT_AUTOREFERER, true);
$file_downloaded = curl_exec($file_downloaded);
if(!curl_errno($file_downloaded))
{
header('Content-type:application/pdf');
header('Content-Disposition: attachment; filename ="'.$nuevo_nombre.'.pdf"');
echo($file_downloaded);
exit();
}else
{
echo(curl_error($file_downloaded));
}
?>
<script>
$("#boton").click(function () {
var archivo = '<?php echo($file_downlaoded) ?>';
var data = new FormData();
data.append("data" , archivo);
var xhr = (window.XMLHttpRequest) ? new XMLHttpRequest() : new activeXObject("Microsoft.XMLHTTP");
xhr.open( 'post', '/my/directory', true );
xhr.send(data);
});
</script>
</body>
It's downloading on my local PC, and it's expected to download on the path /my/directory of the server.
EDIT
<?php
$nuevo_nombre = 'remito'; //asignamos nuevo nombre
$archivo_descarga = curl_init(); //inicializamos el curl
curl_setopt($archivo_descarga, CURLOPT_URL, 'URL');
//curl_setopt($archivo_descarga, CURLOPT_HEADER, true);
curl_setopt($archivo_descarga, CURLOPT_RETURNTRANSFER, true);
curl_setopt($archivo_descarga, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($archivo_descarga, CURLOPT_AUTOREFERER, true);
$resultado_descarga = curl_exec($archivo_descarga);
file_put_contents('/path/to/file.pdf', $resultado_descarga);
?>
That was solved with the file_put_contents() function, and there was also an issue with permissions on the directory folder.
function Download($endpoint) {
$URL = 'URL';
$fileName= 'name1';
$path = 'testDirectory/'.$filename.'.pdf';
$file_download= curl_init();
curl_setopt($file__download, CURLOPT_URL, $URL.$endpoint);
curl_setopt($file__download, CURLOPT_RETURNTRANSFER, true);
curl_setopt($file__download, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($file__download, CURLOPT_AUTOREFERER, true);
$result= curl_exec($file__download);
file_put_contents($path, $result);
}

Download file from url to server

I have this code but it's not working, can someone tell me what to do? I don't know PHP, just started to learn PHP. I'm trying to put url in form and get that file downloaded from url to my server.
$prevod = $_POST['prevod'];
$url = file_get_contents("$prevod");
$fp = fopen("prevodi/", "w");
fwrite($fp, $url);
fclose($fp);
<form action="prevod.php" method="post">
<input name="prevod" type="text"/>
<input type="submit" value="Pronađi"/>
</form>
Try this and please avoid quotes for variables
$prevod = $_POST['prevod'];
$url = file($prevod);
you have to give path before filename then it will work if it was protected then you have to access by curl
$urldata = realpath('../severname/folder/'.$prevod.'');
$fp = fopen('../foldername/subfolder','w');
$newfile = realpath('../foldername/subfolder/'. $prevod .'');
file_put_contents($newfile, $urldata);
<form action="prevod.php" method="post">
<input name="prevod" type="text"/>
<input type="submit" value="Pronađi"/>
</form>
Create prevod.php then add following code. Please create "prevodi" directory also. You can change file name by variable $with_extension. Now it is for gif file.
<?php $ch = curl_init();
$source = $_POST['prevod'];
curl_setopt($ch, CURLOPT_URL, $source);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec ($ch);
curl_close ($ch);
$with_extension="filename.gif";
$destination = "prevodi/". $with_extension;
$file = fopen($destination, "w+");
fputs($file, $data);
fclose($file);
?>

Sending a file to a webservice with XML using cURL corrupts it

So I have some code that sends a career application to a webservice which then emails the file to the hr department as an attachment along with other elements in the form. All of the parts except for the file gets emailed as desired. The file gets uploaded to the server without being corrupted. But the resulting email attachment ends up being corrupted.
The problem is; the file ends abruptly before reaching EOF. Let's say it is a pdf file when I open both the original and the reduced size file in a text editor I see that the beginnings are identical until one of them suddenly ends. One of them is about 1MB and the corrupt one is about 600kB.
I have tried sending files smaller(4kB) than the resulting corrupt file but that file also gets corrupt in the same way. The resulting file is about 1kB.
The xml response I get says:
<?xml version="1.0" encoding="utf-8"?><SENDEMLRSP><RTCD>1</RTCD><EXP>OK</EXP><RSP_LIST><RSP><MSGID>0</MSGID><EID /><RESULT>Invalid length for a Base-64 char array or string.</RESULT></RSP></RSP_LIST></SENDEMLRSP>
It is this part that is of interest:
<RESULT>Invalid length for a Base-64 char array or string.</RESULT>
I have prepared a small form with only a file upload for testing purposes.
Here is the HTML:
<html>
<body>
<form action="upload_file.php" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file"><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
Here is the relevant PHP code:
if(isset($_FILES['file']['name']))
{
echo ($_FILES['file']['name']);
echo ($_FILES['file']['tmp_name']);
$target = $_FILES['file']['name'];
move_uploaded_file( $_FILES['file']['tmp_name'], $target);
$rawdata = file_get_contents($target);
$data = urldecode($rawdata);
$data = base64_encode($rawdata);
//error_log('uploadconvertscope');
$iletisimrcpt = '<RCPT>
<TA>someemail#address.com</TA>
<MSG>kgsg</MSG>
<SBJ>'. strlen($rawdata).'</SBJ>
<OBOE>'.OBOE.'</OBOE>
<OBON>'.OBON.'</OBON>
<ATT_LIST><ATT><FN>'.$_FILES['file']['name'].'</FN><DATA>'.$data.'</DATA></ATT></ATT_LIST>
</RCPT>';
$request = '<?xml version="1.0" encoding="utf-8"?>
<SENDEML>
<VERSION>1.0</VERSION>
<TOKEN>'.$token.'</TOKEN>
<JID>'.JOBID.'</JID>
<MSG>Kariyar Basvuru isteði baþarýyla yerleþtirildi.</MSG>
<SBJ>Kariyar Basvuru</SBJ>
<RCPT_LIST>
'.$iletisimrcpt.'
</RCPT_LIST>
</SENDEML>';
error_log($request );
$params = array('data' => $request);
$response = processRequest(EML_URL, $params);
error_log($response );
$xml = new SimpleXmlElement($response);
}
The processRequest function works with the rest of the message. So it may not be the problem but here is the code:
<?php
function processRequest($url, $params) {
if(!is_array($params))
return false;
$post_params = "";
foreach($params as $key => $val) {
$post_params .= $post_params?"&":"";
$post_params .= $key."=".$val;
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_VERBOSE, 0);
curl_setopt($ch, CURLOPT_TIMEOUT, 0);
curl_setopt($ch, CURLOPT_HEADER, false); // 'true', for developer testing purpose
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_params);
$data = curl_exec($ch);
if(curl_errno($ch))
print curl_error($ch);
else
curl_close($ch);
return $data;
}
?>
The file when read as a string between the looks like AHFAY3453GAW//LONG RANDOM STRING OF CHARACTERS//== it always ends with two "==" signs if that means anything.
I am really stumped as the files get uploaded OK with this C# code:
byte[] attach1 = File.ReadAllBytes(#"C:\Users\user\Downloads\amb.pdf");
string attach = Convert.ToBase64String(attach1);
EmlRequest.SetConnectionInformation("someapi.com", "admin", "password");
EmlRequest eml=new EmlRequest(){ MessageJobId="DASFA1SDFAWEFA4X2==" };
eml.Recipients.Add(new ApiEmlRecipient() { TargetAddress = "email#address.com" ,ToName="name",Message="xxx",Subject="subject"});
eml.Recipients[0].Attachments.Add(new ApiEmlAttachment() { FileName = "abm.pdf", Data = attach });
eml.Send();
Which is almost identical to it's PHP version.
I figured this out quite some time ago but only got down to writing an answer.
So the problem was that the "+" signs in the string were replaced by spaces.
This bit was responsible:
$rawdata = file_get_contents($target);
$data = urldecode($rawdata);
$data = base64_encode($rawdata);
I changed it to this:
$rawdata = file_get_contents($_FILES['uploadedfile']['tmp_name']);
$data = base64_encode($rawdata);
$data = urlencode($data);
Now it works.

Can anyone give me an example for PHP's CURLFile class?

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

Facebook profile image and download it to my web directory

Take a Facebook profile image and download it to my directory "www.site.com/images"..
<?php $url = "https://graph.facebook.com/$id/picture?width=350&height=500&redirect=false"; ?>
The variable "$id" is taken from a textfield, I've tried getting around the "redirect" that facebook places on their images, so to get the "real url" I've decided to extract it from a JSON. In browser I receive this:
"url": "https://fbcdn-profile-a.akamaihd.net/hprofil[...]",
"width": 299,
"height": 426,
"is_silhouette": false
All I need is the "real url" to be extracted and saved unto my website's directory.
$.getJSON, seems to be the easiest way to separate the information.
Summary
Extracting/Separator script for JSON in PHP or JAVASCRIPT
Or Save "Image" to "Directory".
My solutions:
PHP with curl
<?php
$ch = curl_init("http://graph.facebook.com/$id/picture?width=350&height=500&redirect=false");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5); // Mean 5 seconds
$content = curl_exec($ch);
$data = json_decode($content, true);
curl_close($ch);
var_dump($data["data"]["url"]);
PHP with file_get_contents()
<?php
$content = file_get_contents("http://graph.facebook.com/$id/picture?width=350&height=500&redirect=false");
$data = json_decode($content, true);
var_dump($data["data"]["url"]);
javascript with jQuery
var url = "http://graph.facebook.com/ID/picture?width=350&height=500&redirect=false";
$.get(url,function(resp) {
alert(resp.data.url);
});
EDIT
Have you tried to remove "&redirect=false"
"https://graph.facebook.com/$id/picture?width=350&height=500"
redirect to
"https://fbcdn-profile-a.akamaihd.net/hprofil[...]"
So you can do:
<?php
$url = "https://graph.facebook.com/$id/picture?width=350&height=500";
$data = file_get_contents($url);
$fp = fopen("img$id.jpg","wb");
if (!$fp) exit;
fwrite($fp, $data);
fclose($fp);
Learn more about picture graph
I used this code when storing images from fb.
$dir = "your_directory";
$img = md5(time()).'.jpg';
$url = "some_value";
$ch = curl_init($url);
$fp = fopen($_SERVER['DOCUMENT_ROOT'].DIRECTORY_SEPARATOR.$dir.DIRECTORY_SEPARATOR.$img, 'wb');
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_exec($ch);
curl_close($ch);
fclose($fp);

Categories