I have to do a very simple operation but my programming skills are not enough. I have to count likes in Facebook page and print that number on my web-site. I have two scripts that do the job well for ordinary web-sites, but they don't want to show the number of likes for the page.
<?php
$source_url = "http://www.facebook.com/"; //This could be anything URL source including stripslashes($_POST['url'])
$url = "http://api.facebook.com/restserver.php?method=links.getStats&urls=".urlencode($source_url);
$likes = $xml->link_stat->like_count;
$comments = $xml->link_stat->comment_count;
$total = $xml->link_stat->total_count;
$max = max($shares,$likes,$comments);
echo $likes;
?>
<?php
$fql = "SELECT url, normalized_url, share_count, like_count, comment_count, ";
$fql .= "total_count, commentsbox_count, comments_fbid, click_count FROM ";
$fql .= "link_stat WHERE url = 'http://www.apple.com/'";
$apifql="https://api.facebook.com/method/fql.query?format=json&query=".urlencode($fql);
$json=file_get_contents($apifql);
print_r( json_decode($json));
?>
Both scripts work for ordinary web-sites but cant fetch fb page likes number. May be I should enter the link in another format or something?
I can get required data using graph like this http://graph.facebook.com/?ids=AutoSpecCenter , just by entering page name like that. But I don't know how to manipulate with this data.
As you already wrote in your question, you can query such information through Facebooks' Graph API. This short example will get the information of the Coca-Cola page, decode the JSON and outputs the number of people that like the page $data->likes.
<?php
$ch = curl_init("https://graph.facebook.com/CocaCola?access_token=<Access Token>");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$raw = curl_exec($ch);
curl_close($ch);
$data = json_decode($raw);
echo $data->likes . " people like Coca-Cola";
?>
If you need to perform more tasks than just getting the likes of a page, consider using the Facebook SDK as cpilko suggested.
Here's the quick and dirty way:
<?php
$fb_id = 'AutoSpecCenter';
$url = 'https://graph.facebook.com/' . urlencode($fb_id);
$result = json_decode( file_get_contents($url) );
printf("<p>There are %s people who like %s</p>", $result->likes, $result->name);
You'd do much better off installing the Facebook PHP SDK or using cURL to get this.
You could set $fb_id equal to a url as well.
here is a easy way too....
<?php
$page_id = 'yourfbpageid'; // your facebook page id
$xml = #simplexml_load_file("http://api.facebook.com/restserver.php?method=facebook.fql.query&query=SELECT%20fan_count%20FROM%20page%20WHERE%20page_id=".$page_id."") or die ("a lot");
$fans = $xml->page->fan_count;
?>
<li class="text white"><span></span><?php echo $fans.' Fans'; ?></li>
courtesy:ravi patel
This worked for me
<?php
function getData($username){
$access_token = 'YOUR ACCESS TOKEN'; //Replace it with your Access Token
$json = json_decode(file_get_contents("https://graph.facebook.com/".$username."?fields=fan_count&access_token=".$access_token),true);
return $json;
}
$data = getData("Mypage");//Replace it with your Username
$likes = $data['fan_count'];
echo "Facebook Likes: ".$likes;
?>
I was having same problem, just adding likes.summary(true),comments.summary(true) in parameter in against "fields" worked for me.
e.g. I used https://graph.facebook.com/me/feed?access_token=ACCESS_TOKEN&fields=story,from,story_tags,likes.summary(true),comments.summary(true)
instead of https://graph.facebook.com/me/feed?access_token=ACCESS_TOKEN
Also you can add other parameters if you want; separated by a ,
Also if you want count of single post you can use
https://graph.facebook.com/POST_ID/likes?summary=true&access_token=ACCESS_TOKEN
for likes count
Or
https://graph.facebook.com/POST_ID/comments?summary=true&access_token=ACCESS_TOKEN
for comment count
Try this code
<?php echo facebooklike('209414452444193');
function facebooklike($page_id){
$likes = 0; //Initialize the count
//Construct a Facebook URL
$json_url ='https://graph.facebook.com/'.$page_id.'';
$json = get_contents($json_url);
$json_output = json_decode($json);
//Extract the likes count from the JSON object
if($json_output->likes){
$likes = $json_output->likes;
}
return $likes;
}
function 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;
}
?>
Related
I have integrated sendgrid for send mail. I also want to track whether a user has opened the mail and click the link inside the mail or not.
that's why I used sendgrid.
using it I can send mail, but can't track mail states(mail is opened or not, the link is clicked or not).
I tried the below code for sending mail.
function sendMail($toMails, $body, $subject, $ccMails = array(), $bccMails = array()) {
$ci = &get_instance();
if (empty($toName)) {
$toName = $toMails;
}
$sendMail = $ci->config->item('sendMail');
$email = new \SendGrid\Mail\Mail();
$email->setFrom($ci->config->item('from'), "From User name");
$email->setSubject($subject);
$email->addTos($toMails); //for multiple user pass array with emails and names
$email->addCcs($ccMails);
$email->addBccs($bccMails);
$email->addContent("text/html", $body);
$email->setFooter(false, "", "<strong>If you don't want to receive this type of email in the future, please <a href='http://w3schools.com'>Unsubscribe</a>.</strong>");
//$email->setSpamCheck(true, 1, "http://localhost:8081/");
// Tracking Settings
$email->setClickTracking(true, true);
//$email->setOpenTracking(true, true);
$sendgrid = new \SendGrid($ci->config->item('key'));
try {
$response = $sendgrid->send($email);
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
if ($sendMail) :
if (!$response->statusCode()) :
_pre($response->headers());
return false;
else :
return true;
endif;
endif;
}
which is working fine, except it is going in the spam.
now below code, I am using to get details as per email id.
$sendgrid = new \SendGrid($this->config->item('key'));
$query_params = json_decode('{"start_date": "2019-10-07","end_date": "2019-10-07","to_email": "cadmin1#getnada.com","subject":"This is a subject test"}');
$response = $sendgrid->client->stats()->get(null, $query_params);
_pre($response->body());
exit;
above code only gives me date wise data, but I also want email id wise.
but in spite of adding a parameter for that, still, I am not getting desired output.
https://sendgrid.com/docs/for-developers/sending-email/getting-started-email-activity-api/#filter-by-recipient-email
I have used the above demo, in that demo, they have used curl but I am using CodeIgniter's way.
I am not sure about sendgrid version that's why I added both version tag, I used API one.
anyone having a proper solution regarding it?
I have implemented webhooks to archive my desire output.
for that need to follow steps as per documentation shows
after that need to create a page from where we can get mails status.
on executing that page it returns data as per activity.
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: *');
$data = file_get_contents("php://input");
$events = json_encode($data, true);
$requestData = array('response' => $events);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "<url which we earlier set for webhook as per documentation>");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $requestData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec($ch);
curl_close($ch);
?>
i have used Curl for getting desire output.
I'm trying to use this site https://www.oneall.com/ to add social login to a test site. After setting up the code and the login I still don't know how to extract user data from access token. Here's the link I get:
http://MYACCOUNT.api.oneall.com/socialize/redirect.html?provider_connection_token=ACCESS TOKEN HERE
I get this code by the call back page like this
if ( ! empty ($_POST['connection_token']))
{
echo "Connection token received: ".$_POST['connection_token'];
}
else
{
echo "No connection token received";
}
if ( ! empty ($_POST['connection_token']))
{
$token = $_POST['connection_token'];
$site_subdomain = 'myaccountname';
$site_public_key = 'public key';
$site_private_key = 'private key';
$site_domain = $site_subdomain.'.api.oneall.com';
$resource_uri = 'https://'.$site_domain.'/connections/'.$token .'.json';
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $resource_uri);
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_USERPWD, $site_public_key . ":" . $site_private_key);
curl_setopt($curl, CURLOPT_TIMEOUT, 15);
curl_setopt($curl, CURLOPT_VERBOSE, 0);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($curl, CURLOPT_FAILONERROR, 0);
$result_json = curl_exec($curl);
if ($result_json === false)
{
echo 'Curl error: ' . curl_error($curl). '<br />';
echo 'Curl info: ' . curl_getinfo($curl). '<br />';
curl_close($curl);
}
else
{
curl_close($curl);
$json = json_decode ($result_json);
$data = $json->response->result->data;
if ($data->plugin->key == 'social_login')
{
if ($data->plugin->data->status == 'success')
{
$user_token = $data->user->user_token;
$user_id = GetUserIdForUserToken($user_token);
if ($user_id === null)
{
LinkUserTokenToUserId ($user_token, $user_id);
}
else
{
}
}
}
}
}
I need to learn how to extract data now and a little example about extracting the user name by this code.
You can use the access token to get the connection details from oneall using their api
You use the connection_token to get the connection details (including
the user's Facebook profile data).
example
http://MYACCOUNT.api.oneall.com/connections/ACCESS TOKEN HERE.json -->>for json formatted data
oneall docs
Once you get the user's token, you then need to make a API call to Facebook, e.g. https://graph.facebook.com/me/?access_token={$access_token}
If the $access_token is correct, Facebook should return the user's details, including name, username and any other details you've asked for.
i want to check if the url's in my database are reaching the facebook page they should or redirected to "www.facebook.com".
this is the code i use:
<?php
$conn = mysql_connect('localhost', 'user', 'pass');
mysql_select_db('database');
?>
<?php
$query = "SELECT data_txt FROM jos_sobi2_fields_data WHERE fieldid=8 ";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
$url = $row['data_txt'];
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
foreach($row as $url) {
curl_setopt($ch, CURLOPT_URL, $url);
$out = curl_exec($ch);
$out = str_replace("\r", "", $out);
$headers_end = strpos($out, "\n\n");
if( $headers_end !== false ) {
$out = substr($out, 0, $headers_end);
}
$headers = explode("\n", $out);
foreach($headers as $header) {
if( substr($header, 0, 10) == "Location: " ) {
$target = substr($header, 10);
echo "[$url] redirects to [$target]<br>";
continue 2;
}
}
echo "[$url] does not redirect<br>";
}
?>
the result is this:
[http://www.facebook.com/shanibakshi.grooming.dogtraining] redirects to [http://www.facebook.com/common/browser.php]
[http://www.facebook.com/shanibakshi.grooming.dogtraining] redirects to [http://www.facebook.com/common/browser.php]
and this url -> http://www.facebook.com/common/browser.php is a facebook page that says my browser is old...probably because of some function in the code.....
anyway all i want to do is to check if the url in my database stays in their place with any redirection.
thanks :)
ronen.
Are you saying that you want to detect redirection, but the problem is you are always getting redirected to browser.php so you get nothing but "false positives"? In that case you probably just need to set the USERAGENT option, something like:
curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0 (Windows NT 6.2; rv:9.0.1) Gecko/20100101 Firefox/9.0.1');
I added custom Google+ and Facebook buttons, and counter is updated over MY ajax...
Here is the code ( I included for twitter counter too so it can be useful for others, but it's counter is working for sure ):
$url = "URL OF PAGE";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://clients6.google.com/rpc?key=AIzaSyCKSbrvQasunBoV16zDH9R33D88CeLr9gQ");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, '[{"method":"pos.plusones.get","id":"p","params":{"nolog":true,"id":"' . $url . '","source":"widget","userId":"#viewer","groupId":"#self"},"jsonrpc":"2.0","key":"p","apiVersion":"v1"}]');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/json'));
$curl_results = curl_exec ($ch);
curl_close ($ch);
$parsed_results = json_decode($curl_results, true);
echo $parsed_results[0]['result']['metadata']['globalCounts']['count']; //Google+ counter for this URL
$fbresponse = file_get_contents('http://graph.facebook.com/' .$url);
$fbresponse_c = json_decode($fbresponse,true);
if ( $fbresponse_c['shares'] ) { echo $fbresponse_c['shares']; } else { echo '0'; } //Facebook counter for this URL
$twresponse = file_get_contents('http://cdn.api.twitter.com/1/urls/count.json?url=' .$url. '&callback=twttr.receiveCount');
$twresponse = str_replace('twttr.receiveCount(' ,'', $twresponse);
$twresponse = str_replace(')' ,'', $twresponse);
$twresponse_c = json_decode($twresponse,true);
echo $twresponse_c['count']; //Twitter counter for this URL
I changed URL to "http://www.google.com" and it shows counters from all sites 3 sites...
I shared link on my Facebook Wall, using my pop-up ( code is below ) but counter didn't updated ( it didn't updated for two days )...
And for Google+ I don't have account so I can't test it...
Can someone tell me way how to test those?
Since from what I see it's not working...
For sharing I pop-up this URL for Facebook:
"http://www.facebook.com/sharer.php?u=" + escape(url) + "&t=Some text"
and this one for Google:
"https://plusone.google.com/u/0/+1/profile/?type=po&source=p&parent=https%3A%2F%2Fplusone.google.com&hl=en_US&ru=" + escape(urll)
How often facebook updates it's counters?
And how can I check is this Google+ counter working okay?
Thanks!
Everything is updating now...
Facebook instantly, and I opened Google+ account so I tested that too, it's also working...
-Closed-
I'm trying to get some basic information about a user in a PHP script (id and name).
I have tried the following methods:
$retrieve = curl_init("https://graph.facebook.com/me?access_token=$accesstoken");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($retrieve, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$data = curl_exec($retrieve);
curl_close($retrieve);
and
$user = json_decode(file_get_contents(
"https://graph.facebook.com/me?access_token=$accesstoken"))->me;
The cURL method (former) just times out. The file_get_contents (latter) method just doesn't return anything at all...
What could be causing this? Am I using cURL correctly?
for graph api you can use graph api methods rahter than curl
the following code grabs information of current user
define('FACEBOOK_APP_ID', 'Your API ID');
define('FACEBOOK_SECRET', 'YOUR SECRET');
function get_facebook_cookie($app_id, $application_secret)
{
$args = array();
parse_str(trim($_COOKIE['fbs_' . $app_id], '\\"'), $args);
ksort($args);
$payload = '';
foreach ($args as $key => $value)
{
if ($key != 'sig')
{
$payload .= $key . '=' . $value;
}
}
if (md5($payload . $application_secret) != $args['sig'])
{
return null;
}
return $args;
}
$cookie = get_facebook_cookie(FACEBOOK_APP_ID, FACEBOOK_SECRET);
$user=json_decode(file_get_contents('https://graph.facebook.com/me?access_token='.$cookie['access_token']));
its prettey easy
Facebook will not let you use curl. They have the api for that.
copy your link and paste it to browser. It will work. In Mozilla you will see the result in browser, IE will save the result as a file. So it is not about invalid access token etc. It is just because Facebook does not respond to your query when it does not come 1-from a web browser, 2-from Facebook APIs.
here is the relevant PHP call to Facebook.
$attachment = array('access_token' => $access_token);
$result=$facebook->api('/me', 'GET', $attachment);
$id = $result['id'];
$name=$result['name'];