The scripts and code provided here are the work of Jeremy Blanchard, Paul Wells and Kevin Pazirandeh. The current implementation of the Facebook Platform PHP Library lacks support for uploading photos. The PHP5 class provided here makes it easy to upload photos into Facebook albums.
[edit] UPDATEI haven't had time to update this code to the changed Facebook has made to the API. I have had many reports of it not functioning properly or at all. Thanksfully, Kevin Youkhana modified the code and got it working. I haven't integrated this code into the .zip file below, but I will post it here:
$header = 'User-Agent: Facebook Photo API PHP5 Client 1.0 ' . phpversion() . "\r\n" .
'Content-Type: multipart/form-data; boundary=' . $boundary . "\r\n" .
'MIME-version: 1.0' . "\r\n" .
'Content-length: ' . strlen($content) . "\r\n" .
'Keep-Alive: 300' . "\r\n" .
'Connection: keep-alive';
if (function_exists('fsockopen')) {
$url = parse_url($this->server_addr);
$sock = @fsockopen($url['host'], 80, $errno, $errstr, 5);
$header = 'POST ' . $url['path'] . ' HTTP/1.1' . "\r\n" .
'Host: ' . $url['host'] . "\r\n" .
$header;
fwrite($sock, $header . "\r\n\r\n" . $content);
} else {
$context = array('http' => array('method' => 'POST',
'header' => $header,
'content' => $content));
$contextid=stream_context_create($context);
$sock = fopen($this->server_addr, 'r', false, $contextid);
}
if ($sock) {
$result='';
while (!feof($sock)) {
$temp = fgets($sock, 4096);
$result .= $temp;
if (!$temp) break; //wtf facebook? return feof already...
}
fclose($sock);
}
[edit] Installing the scriptThe code only works with PHP5. Download facebook_php5_photoslib.php Updated: June 11, 2007
[edit] Change log
[edit] Example usage
<?php
require_once 'facebook_api/facebook_php5_photoslib.php';
$appapikey = '[YOUR KEY]';
$appsecret = '[YOUR SECRET]';
$facebook = new FacebookPhotos($appapikey, $appsecret);
$user = $facebook->require_login();
$appcallbackurl = 'http://eyermonkey.com/FlickrTools/';
//catch the exception that gets thrown if the cookie has an invalid session_key in it
try {
if (!$facebook->api_client->users_isAppAdded()) {
$facebook->redirect($facebook->get_add_url());
}
} catch (Exception $ex) {
//this will clear cookies for your app and redirect them to a login prompt
$facebook->set_user(null, null);
$facebook->redirect($appcallbackurl);
}
// Get a list of the users albums
$albums = $facebook->api_client->photos_getAlbums($user, null);
// Pick the first album for sake of the example
$aid = $albums[0]['aid'];
$filename = 'http://eyermonkey.com/FlickrTools/test_image.jpg';
$caption = 'IM IN UR C0D. UPLOADING UR FOTOS!!1!';
// Perform the upload and get the return data (including the URL of the new photo)
$upload_result = $facebook->api_client->photos_upload($filename, $aid, $caption);
// See the data that you have access to now that the photo is uploaded
echo '<pre>';
print_r($upload_result);
echo '</pre>';
?>
[edit] BugsIf you find any bugs, please add them to the discussion page of this article, or email them to: eyeRmonkey (at) gmail.com If there is no Album create in facebook account, this code will failed. Should detect if there is at least one Album, if not, just create one before call upload function. [edit] The code
<?php
/*----------------------------------------------------------------------
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; version 2 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
----------------------------------------------------------------------*/
include_once 'facebook.php';
class FacebookPhotos extends Facebook {
public function __construct($api_key, $secret) {
$this->api_key = $api_key;
$this->secret = $secret;
$this->api_client = new FacebookPhotosRestClient($api_key, $secret);
$this->validate_fb_params();
}
}
class FacebookPhotosRestClient extends FacebookRestClient {
/**
* Creates and returns a new album owned by the current session user.
* @param string $name the album name
* @param string $location Optional: the album location
* @param string $description Optional: the album description
* @return string a new album owned by the current session user
*/
public function photos_createAlbum($name, $location = null, $description = null) {
return $this->call_method('facebook.photos.createAlbum',
array('name' => $name,
'location' => $location,
'description' => $description));
}
/**
* Uploads a photo owned by the current session user and returns the new photo.
* @param integer $aid Optional: the album id of the destination album. If
* no album is specified, the photo will be uploaded to a default
* album for the application, which will be created if necessary.
* Regular albums have a size limit of 60 photos. Default
* application albums have a size limit of 1000 photos.
* http://developers.facebook.com/documentation.php?method=photos.upload
* for more information.
* @param string $caption Optional: the caption of the photo
* @param string $image_url the url of the image you want to upload
* @return string urls of the resulting image on Facebook's servers
*/
public function photos_upload($filename, $aid = null, $caption = null) {
return $this->call_method('facebook.photos.upload',
array('filename' => $filename,
'aid' => $aid,
'caption' => $caption));
}
public function post_request($method, $params) {
$params['method'] = $method;
$params['session_key'] = $this->session_key;
$params['api_key'] = $this->api_key;
$params['call_id'] = microtime(true);
if ($params['call_id'] <= $this->last_call_id) {
$params['call_id'] = $this->last_call_id + 0.001;
}
$this->last_call_id = $params['call_id'];
if (!isset($params['v'])) {
$params['v'] = '1.0';
}
foreach ($params as $key => $val) if (is_array($val)) $params[$key] = implode(',', $val);
$secret = $this->secret;
$params['sig'] = Facebook::generate_sig($params, $secret);
$boundary = md5(time());
$content = array();
$content[] = '--' . $boundary;
foreach ($params as $key => $val) {
$content[] = 'Content-Disposition: form-data; name="' . $key . '"' . "\r\n\r\n" .
$val . "\r\n--" . $boundary;
}
if ($params['filename']) {
$filename = $params['filename'];
preg_match('/.*?\.([a-zA-Z]+)/', $filename, $match);
$type = strtolower($match[1]);
if ($type == 'jpg') $type = 'jpeg';
$content[] = 'Content-Disposition: form-data; filename="' . $filename . '"' . "\r\n" .
'Content-Type: image/' . $type . "\r\n\r\n" .
file_get_contents($filename) . "\r\n--" . $boundary;
}
$content[] = array_pop($content) . '--';
$content = implode("\r\n", $content);
if (function_exists('curl_init')) {
$url = parse_url($this->server_addr);
$header = array('User-Agent: Facebook Photo API PHP5 Client 1.0 ' . phpversion(),
'Content-Type: multipart/form-data; boundary=' . $boundary,
'MIME-version: 1.0',
'Content-Length: '. (strlen($content)) );
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->server_addr);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $content);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
$result = curl_exec($ch);
curl_close($ch);
} else {
$header = 'User-Agent: Facebook Photo API PHP5 Client 1.0 ' . phpversion() . "\r\n" .
'Content-Type: multipart/form-data; boundary=' . $boundary . "\r\n" .
'MIME-version: 1.0' . "\r\n" .
'Content-length: ' . strlen($content) . "\r\n" .
'Keep-Alive: 300' . "\r\n" .
'Connection: keep-alive';
if (function_exists('fsockopen')) {
$url = parse_url($this->server_addr);
$sock = @fsockopen($url['host'], 80, $errno, $errstr, 5);
$header = 'POST ' . $url['path'] . ' HTTP/1.1' . "\r\n" .
'Host: ' . $url['host'] . "\r\n" .
$header;
fwrite($sock, $header . "\r\n\r\n" . $content);
}
else {
$context = array('http' => array('method' => 'POST',
'header' => $header,
'content' => $content));
$contextid=stream_context_create($context);
$sock = fopen($this->server_addr, 'r', false, $contextid);
}
if ($sock) {
$result='';
while (!feof($sock)) {
$temp = fgets($sock, 4096);
$result .= $temp;
if (!$temp) break; //wtf facebook? return feof already...
}
fclose($sock);
}
}
preg_match('/<.*>/s', $result, $match);
return $match[0];
}
}
?>
|