I am using PinterestPinner to create an script that could login once and post multiple pins, rather than login each time I want to post a pin.
This is how I am using it:
foreach ($links as $link)
{
$pinterest = new PinterestPinner($username, $password);
$result = $pinterest->pin(array(
'board' => $boardId,
'image' => $image,
'description' => $description,
'link' => $url,
));
if (false === $result) {
echo 'Error: ' . $pinterest->getError();
} else {
echo 'Pin Created, ID: ' . $pinterest->getPinID();
}
}
I think using it this way makes the script login to Pinterest for every single pin. So for example, if I want to post 3 pins in a single script run, then it logs in 3 times rather than logging in once. (Please let me know if I am wrong about this).
How can I modify the script to keep the login session alive while posting multiple pins on my board?
Use This
try {
$pinterest = new PinterestPinner\Pinner;
$pin_id = $pinterest->setLogin('Your Pinterest Login')
->setPassword('Your Pinterest Password')
->setBoardID('Pinterest Board ID')
->setImage('Image URL')
->setDescription('Pin Description')
->setLink('Pin Link')
->pin();
} catch (PinterestPinner\PinnerException $e) {
echo $e->getMessage();
}
Related
i'm trying make photo upload, but i'm not getting, well the goal was publish in my fan page wall, i cann't, so i decided to test in my wall "me/photo", same thing, this error appears!
CurlException failed creating formpost data
this is my code, and the page "config.php" contains only configurations, appid, secret, etc...
anyway, What am i do wrong?
$photo = '/imagens/teste.jpg'; // Path to the photo on the local filesystem
$message = 'Photo upload via the PHP SDK!';
?>
<html>
<head></head>
<body>
<?php
if($idUsuario) {
// We have a user ID, so probably a logged in user.
// If not, we'll get an exception, which we handle below.
try {
// Upload to a user's profile. The photo will be in the
// first album in the profile. You can also upload to
// a specific album by using /ALBUM_ID as the path
$ret_obj = $facebook->api('/me/photos', 'POST', array(
'access_token'=> $facebook->getAccessToken(),
'source' => '#'.$photo,
'message' => $message
)
);
echo '<pre>Photo ID: ' . $ret_obj['id'] . '</pre>';
echo '<br />logout';
} catch(FacebookApiException $e) {
// If the user is logged out, you can have a
// user ID even though the access token is invalid.
// In this case, we'll get an exception, so we'll
// just ask the user to login again here.
$login_url = $facebook->getLoginUrl( array(
'scope' => 'photo_upload'
));
echo 'Please login.';
error_log($e->getType());
error_log($e->getMessage());
}
} else {
// No user, print a link for the user to login
// To upload a photo to a user's wall, we need photo_upload permission
// We'll use the current URL as the redirect_uri, so we don't
// need to specify it here.
$login_url = $facebook->getLoginUrl( array( 'scope' => 'photo_upload') );
echo 'Please login.';
}
?>
</body>
</html>
You can see that this code is the same code example in dvelopers.facebook to make upload!
You must send the realpath to the API.
Change:
$photo = '/imagens/teste.jpg';
By:
$photo = realpath('/imagens/teste.jpg');
And check if your path is good.
i have a display that shows 6 random friends on facebook when using the app, however, what i would like to figure out is how to change the display, so that when the friend is clicked on, they are sent an invite to use the app.
Nothing flash, just some kind of notification to say something along the lines of 'Bob thinks you should use this app' and when clicked, they go to the app.
not sure if it will help, but here is the code i have to display friends of the user.
code:
<div class= "newboxbottom">
<h1>Why not share?</h1>
<?php
$user = $facebook->getuser();
if ($user) {
$user_profile = $facebook->api('/me');
$friends = $facebook->api('/me/friends?fields=first_name');
echo '<table>';
foreach (array_slice($friends["data"], 0, 6) as $value) {
echo '<td>';
echo '<div class="pic">';
echo '<img src="https://graph.facebook.com/' . $value["id"] . '/picture?type=normal"/>';
echo '</div>';
echo '<div align="center">','<font color="white">','<div class="picName">'.$value["first_name"].'</div>','</font>','</div>';
echo '</td>';
}
echo '</table>';
}
?>
</div>
many thanks to anyone who can help.
Try looking into the Notification API that Anvesh mentioned in a comment.
You'll want to be careful with notifications and follow the recommended best practices. You don't want to send notifications to users who would not want them in the first place. You could get hit with negative feedback and get shut down by Facebook.
As for how to actually make the call? I haven't actually used this particular API method, but from what I can gather, you should be able to do something like this:
<?php
$parameters = array(
'href' => ''
'template' => ''
'ref' => ''
);
try {
$response = $facebook->api('<enter recipient user facebook id here>/notifications', 'post', $parameters);
} catch (FacebookAPIException $e) {
$echo $e->getMessage();
}
Checkout the documentation on more information on the parameters you need to pass. Hope this helps.
ArangoDB is a flexible multi-model database server which has very nice features and lots of good documentation. It's a young, very promising open source project with a growing community but not many real world examples to get started.
A common real-world example, is user registration and authentication. It's needed in most applications out there.
So, how to do user registration and authentication in PHP with ArangoDB?
You can run the following example code directly and it will run through a user registration and authentication by providing some fictional user data.
It will display each step that it's doing. From collection-creation, to user-registration, authentication and finally cleaning up the collection again.
There are also lots of comments that explain what is being done, in order to make it easier to understand.
Just put this code in a file, configure the path to autoload.php according to your environment and visit its link with a browser.
This code requires ArangoDB 1.2 and up as well as the ArangoDB-PHP client version 1.2 and up.
It expects ArangoDB to be running on localhost and listening on port 8529.
Note1: The script automatically creates the 'users' collection and a unique skip-list index on 'username'. It also will drop the collection in the end.
If you want to create the collection by hand instead of automatically, you need to comment out the parts where the collection and index are created as well as the part where the collection is dropped.
After that open up a shell to ArangoDB (arangosh) and run the following commands in it:
arangosh> db._createDocumentCollection('users');
arangosh> db.users.ensureUniqueSkiplist("username");
if you want to drop the collection, type:
arangosh> db.users.drop();
Note2: I have intentionally avoided introducing more OO style, like user objects, address objects, etc.. in order to keep it simple.
So, finally here's the script.
<?php
namespace triagens\ArangoDb;
// use this and change it to the path to autoload.php of the arangodb-php client if you're using the client standalone...
// require __DIR__ . '/../vendor/triagens/ArangoDb/autoload.php';
// ...or use this and change it to the path to autoload.php in the vendor directory if you're using Composer/Packagist
require __DIR__ . '/../vendor/autoload.php';
// This function will provide us with our pre-configured connection options.
function getConnectionOptions()
{
$traceFunc = function ($type, $data) {
print "TRACE FOR " . $type . PHP_EOL;
};
return array(
ConnectionOptions::OPTION_ENDPOINT => 'tcp://localhost:8529/',
// endpoint to connect to
ConnectionOptions::OPTION_CONNECTION => 'Close',
// can use either 'Close' (one-time connections) or 'Keep-Alive' (re-used connections)
ConnectionOptions::OPTION_AUTH_TYPE => 'Basic',
// use basic authorization
/*
ConnectionOptions::OPTION_AUTH_USER => '', // user for basic authorization
ConnectionOptions::OPTION_AUTH_PASSWD => '', // password for basic authorization
ConnectionOptions::OPTION_PORT => 8529, // port to connect to (deprecated, should use endpoint instead)
ConnectionOptions::OPTION_HOST => "localhost", // host to connect to (deprecated, should use endpoint instead)
*/
ConnectionOptions::OPTION_TIMEOUT => 5,
// timeout in seconds
//ConnectionOptions::OPTION_TRACE => $traceFunc, // tracer function, can be used for debugging
ConnectionOptions::OPTION_CREATE => false,
// do not create unknown collections automatically
ConnectionOptions::OPTION_UPDATE_POLICY => UpdatePolicy::LAST,
// last update wins
);
}
// This function tries to persist the user data into the database upon registration
// it will fail if a user with the same username already exists.
function register($connection, $username, $password, $registrationData)
{
// This would be where you call the function that encrypts your password like you did for storage earlier
$hashedPassword = md5($password);
// assign the collection to a var (or type it directly into the methods parameters)
$collectionId = 'users';
//create an example document or an array in order to pass to the following byExample method
$document = Document::createFromArray(
array('username' => $username, 'password' => $hashedPassword, 'data' => $registrationData)
);
// Get an instance of the collection handler
$documentHandler = new DocumentHandler($connection);
try {
// query the given $collectionId by example using the previously declared $exampleDocument array
$result = $documentHandler->add($collectionId, $document);
// return the result;
return $result;
} catch (Exception $e) {
if ($e->getCode()) {
echo ('User already exists... ');
} else {
// any other error
echo ('An error occured. Exception: ' . $e);
}
}
}
// This function tries to authenticate the user and will return an array with its data
function authenticate($connection, $username, $password)
{
// This would be where you call the function that encrypts your password like you did for storage earlier
$hashedPassword = md5($password);
// assign the collection to a var (or type it directly into the methods parameters)
$collectionId = 'users';
//create an example document or an array in order to pass to the following byExample method
$exampleDocumentArray = array('username' => $username, 'password' => $hashedPassword);
// Get an instance of the collection handler
$documentHandler = new CollectionHandler($connection);
try {
// query the given $collectionId by example using the previously declared $exampleDocument array
$cursor = $documentHandler->byExample($collectionId, $exampleDocumentArray);
// check if the count of the cursor is one or not.
if ($cursor->getCount() == 1) {
// do some fancy login stuff here...
// get the current document from the cursor
$userDocument = $cursor->current();
// set session uid to the document key that was set automatically by ArangoDB,
// since we didn't provide our own on registration
$_SESSION['uid'] = $userDocument->getKey();
// extract and return the document in form of an array
return $userDocument->getAll();
} else {
return false;
}
} catch (Exception $e) {
echo ('An error occured. Exception: ' . $e . '<br>');
}
}
// register the connection to ArangoDB
$connection = new Connection(getConnectionOptions());
// register a collection handler to work with the 'users' collection
$collectionHandler = new CollectionHandler($connection);
// create the 'users' collection...
// remark those lines if you want to create the collection by hand.
echo "creating 'users' collection...";
try {
$collection = new Collection();
$collection->setName('users');
$collectionHandler->create($collection);
echo "created.<br>";
} catch (Exception $e) {
echo ('Could not create collection. Exception: ' . $e . '<br>');
}
// create unique skip list index in 'users' collection on field ''username'...
// remark those lines if you want to create the index by hand.
echo "creating unique skip list index in 'users' collection on field ''username'... ";
try {
$collection = new Collection();
$collection->setName('users');
$collectionHandler->index('users', 'skiplist', array('username'), true);
echo "created.<br>";
} catch (Exception $e) {
echo ('Could not create skip list index. Exception: ' . $e . '<br>');
}
// let's assume those variables hold your username / password
$userNameProvided = 'jane';
$passwordProvided = 'mysecretpassword';
// here we pass some structured registration data
$registrationData = array(
'name' => 'Jane',
'surname' => 'Doe',
'addresses' => array(
'email' => array('jane#doe.com', 'jane2#doe.com'),
'home' => array(
array('street' => 'Brooklyn Ave.', 'number' => 10),
array('street' => '54th Street', 'number' => 340, 'is_primary' => true)
)
)
);
// First register
echo "trying to register user for the first time... ";
$result = register($connection, $userNameProvided, $passwordProvided, $registrationData);
if ($result) {
echo " " . $userNameProvided . " registered<br>";
} else {
echo "failed<br>";
}
// Trying to register user with same username a second time
echo "trying to register user with same username a second time... ";
$result = register($connection, $userNameProvided, $passwordProvided, $registrationData);
if ($result) {
echo "registered<br>";
} else {
echo "failed<br>";
}
// now authenticate with the correct username/password combination
echo "trying to authenticate with the correct username/password combination... ";
if ($userArray = authenticate($connection, $userNameProvided, $passwordProvided)) {
echo "login successful. ";
echo '<br>';
// do some fancy after-login stuff here...
echo "<br>Welcome back " . $userArray['username'] . '!<br>';
if (count($userArray['data']['addresses']['email']) > 0) {
echo "Your primary mail address is " . $userArray['data']['addresses']['email'][0] . '<br>';
}
foreach ($userArray['data']['addresses']['home'] as $key => $value) {
if (array_key_exists('is_primary', $value)) {
$homeAddress = $userArray['data']['addresses']['home'][$key];
echo "Your primary home address is " . $homeAddress['number'] . ', ' . $homeAddress['street'] . '<br>';
// if found, break out of the loop. There can be only one... primary address!
break;
}
}
} else {
// re-display login form. +1 the wrong-login counter...
echo "wrong username or password<br>";
}
echo '<br>';
// now authenticate with the wrong username/password combination
echo "trying to authenticate with the wrong username/password combination... ";
if (authenticate($connection, $userNameProvided, 'I am a wrong password')) {
// do some fancy after-login stuff here...
echo "login successful<br>";
} else {
// re-display login form. +1 the wrong-login counter...
echo "wrong username or password<br>";
}
// truncate the collection... not needed if dropping, but only here to empty the collection of its tests
// in case you decide to not create and drop the collection through this script, but by hand.
echo "truncating collection...";
try {
$collectionHandler->truncate('users');
echo "truncated.<br>";
} catch (Exception $e) {
die ('Could not truncate collection. Exception: ' . $e . '<br>');
}
// finally drop the collection...
// remark those lines if you want to drop the collection by hand.
echo "dropping collection...";
try {
$collectionHandler->drop('users');
echo "dropped.<br>";
} catch (Exception $e) {
die ('Could not drop collection. Exception: ' . $e . '<br>');
}
i am try to use try() inside foreach in php for facebook application my app get user permissions than post on his 3 friends wall but the problem is that if one of user friends is non-postable than my app stop with error below is my code and error please take a look
foreach ($friends_list_array["data"] as $value) {
try
{
// compile the post for for user
$WallPost = array(
'access_token' => $atoken,
'message' => $value["name"] . ' .. message here ',
'link' => 'link_here');
// post to user wall
$response = $facebook->api('/' . $value["id"] . '/feed','POST',$WallPost);
echo ' posted on ' . $value["name"];
}
}
all works fine(except non-postable wall problem) without try() its shows error below is error
Parse error: syntax error, unexpected '}', expecting T_CATCH in
Can any one please solve this thank you
Look here
Each try must have at least one corresponding catch block
And thats the answer to your problem ( the error itself says about it, expecting T_CATCH)
If you do not need catch, just don't fill it with any logic, working example:
foreach ($friends_list_array["data"] as $value) {
try{
// do stuff...
}
catch(Exception $e){
// do nothing
}
}
How can I save a comment made with facebook comments to a mysql database? I want to be able to search through the comments on another page.
you mean where you comment on, for example, your wall, the comment to get to your mysql database?
if so, you need to study Facebook API (Graph API)
<?php
// displays some comments for a certain url
$url = 'http://developers.facebook.com/docs/reference/fql/comment/';
// fql multiquery to fetch all the data we need to display in one go
$queries = array('q1' => 'select post_fbid, fromid, object_id, text, time from comment where object_id in (select comments_fbid from link_stat where url ="'.$url.'")',
'q2' => 'select post_fbid, fromid, object_id, text, time from comment where object_id in (select post_fbid from #q1)',
'q3' => 'select name, id, url, pic_square from profile where id in (select fromid from #q1) or id in (select fromid from #q2)',
);
// note format json-strings is necessary because 32-bit php sucks at decoding 64-bit ints :(
$result = json_decode(file_get_contents('http://api.facebook.com/restserver.php?format=json-strings&method=fql.multiquery&queries='.urlencode(json_encode($queries))));
$comments = $result[0]->fql_result_set;
$replies = $result[1]->fql_result_set;
$profiles = $result[2]->fql_result_set;
$profiles_by_id = array();
foreach ($profiles as $profile) {
$profiles_by_id[$profile->id] = $profile;
}
$replies_by_target = array();
foreach ($replies as $reply) {
$replies_by_target[$reply->object_id][] = $reply;
}
/**
* print a comment and author, given a comment passed in an an array of all profiles.
* #param object $comment as returned by q1 or q2 of the above fql queries
* #param array $profiles_by_id, a list of profiles returned by q3, keyed by profile id
* #returns string markup
*/
function pr_comment($comment, $profiles_by_id) {
$profile = $profiles_by_id[$comment->fromid];
$author_markup = '';
if ($profile) {
$author_markup =
'<span class="profile">'.
'<img src="'.$profile->pic_square.'" align=left />'.
''.$profile->name.''.
'</span>';
}
return
$author_markup.
' ('.date('r', $comment->time).')'.
': '.
htmlspecialchars($comment->text);
}
print '<html><body>';
// print each comment
foreach ($comments as $comment) {
print
'<div style="overflow:hidden; margin: 5px;">'.
pr_comment($comment, $profiles_by_id).
'</div>';
// print each reply
if (!empty($replies_by_target[$comment->post_fbid])) {
foreach ($replies_by_target[$comment->post_fbid] as $reply) {
print
'<div style="overflow:hidden; margin: 5px 5px 5px 50px">'.
pr_comment($reply, $profiles_by_id).
'</div>';
}
}
}
?>
There are several ways to do it.
The first way is to get all comments in one go. You have to do it periodically to get new comments, and avoid duplicating the old ones in your database.
This can be achieved by accessing the Graph API with the url of your page:
https://graph.facebook.com/comments/?ids=http://example.com/your_page
This returns comments in JSON which you have to parse. If there are too many, there will be an 'paging' hash telling you the address of the next page.
The second way is to track new comment and saves them immediately. This avoids the refetched duplicate problem. This will require the use of Javascript and Facebook js events.
FB.Event.subscribe('comment.create', function(response) {
var commentQuery = FB.Data.query('SELECT fromid, text FROM comment WHERE post_fbid=\'' + response.commentID + '\' AND object_id IN (SELECT comments_fbid FROM link_stat WHERE url=\'' + response.href + '\')');
FB.Data.waitOn([commentQuery], function () {
text = commentQuery.value[0].text;
// Use your preferred way to inform the server to save comment
$.post( 'http://example.com/comment', text )
});
});
The example below fetches the comment at client side. But you can also do it at server-side.
Of course you'll need to include Facebook's Javascript library, and implement the posting action (http://example.com/comment) on your server.
FB.Event.subscribe('comment.create',
function(response) {
onCommentCreate(response.commentID,response.href); //Handle URL on function to store on database
alert(response.href); //it gives you url
}
);
function onCommentCreate(commentID,href) {
$.ajax({
type: 'POST',
url: 'handlecomment.php',
data: {commentid:commentID,href:href},
success: function(result)
{
alert(result);
}
});
}
//hadlecomment.php
<?php
error_reporting(E_ERROR);
$commentid=$_POST['commentid'];
$url=$_POST['href'];
$pid=substr($url,strpos($url, 'comments')+8);
// Remember to copy files from the SDK's src/ directory to a
// directory in your application on the server, such as php-sdk/
require_once('php-sdk/facebook.php');
$config = array(
'appId' => 'YOUR_APP_ID',
'secret' => 'YOUR_APP_SECRET',
);
$facebook = new Facebook($config);
$user_id = $facebook->getUser();
$accesstoken=$facebook->getAccessToken();
if($user_id) {
// We have a user ID, so probably a logged in user.
// If not, we'll get an exception, which we handle below.
try {
$facebook->setAccessToken($accesstoken);
$fql = 'SELECT text from comment where id = ' . $commentid;
$ret_obj = $facebook->api(array(
'method' => 'fql.query',
'query' => $fql,));
$comment= $ret_obj[0]['text'] ;
$insert_comment="insert into comments(pid,comment) values($pid,$comment)";
mysql_query($insert_comment);
} catch(FacebookApiException $e) {
// If the user is logged out, you can have a
// user ID even though the access token is invalid.
// In this case, we'll get an exception, so we'll
// just ask the user to login again here.
$login_url = $facebook->getLoginUrl();
echo 'Please login.';
error_log($e->getType());
error_log($e->getMessage());
}
} else {
// No user, so print a link for the user to login
$login_url = $facebook->getLoginUrl();
echo 'Please login.';
}
?>
?>
//YOu need to set data-href of comment should be look like this...
//i am using more comments on my website so i looped through to add comment
while($result=mysql_fetch_assoc(mysql_query($query)))
{
$pic_id=$result['pic_id']; // i have saved unique pic id in my database for all images so i am
//retrieving that here
<div class="fb-comments" style=' position:relative;left:55px;top:10px;' data-href="<?php echo 'http://www.lpuphotography.edulogics.in/votography.php/comments' . $pic_id; ?>" data-width="470" data-num-posts="2"></div>
}
//if you are using single comment
<div class="fb-comments" style=' position:relative;left:55px;top:10px;' data-href="<?php echo 'http://www.lpuphotography.edulogics.in/votography.php/comments101' ?>" data-width="470" data-num-posts="2"></div>
//101 is comment id , u can set what ever you want