How to make my get Facebook like script loop every 3 seconds? - php

I am building a Facebook page like counter. I want to be able to get page like updates roughly every 2-3 seconds. The result will be sent to a sql database then sent to an Arduino. First of all though, I need to get the likes from the desired page. I have the PHP script below that works great but you have to load the page every time to get an updated like count.
Would you be able to use a while loop with some sort of 2-3 second delay? or what you recommend in situation? p.s I used Dan Bilzerian's FB page as an example because his likes just keep going up up up, its ridiculous.
Thanks
function facebook_count($url){
// Query in FQL
$fql = "SELECT like_count";
$fql .= " FROM link_stat WHERE url = '$url'";
$fqlURL = "https://api.facebook.com/method/fql.query?format=json&query=" . urlencode($fql);
// Facebook Response is in JSON
$response = file_get_contents($fqlURL);
return json_decode($response);
}
$fb = facebook_count('https://www.facebook.com/danbilzerianofficial');
// facebook like count
echo $fb[0]->like_count;

Related

Send a message when the score gets an update - Telegram Bot

Hope you all are doing great! I developed a telegram bot that posts the score of the match in the telegram group. I already did most of the part but there is something I didn't able to figure out
How to post score in the group when the score is updated or when there is a change in over. I also tried to keep the API in while loop and set a time delay (sleep();) but that didn't work as I expected because, at one time, execution time would be timed out (endless loop). So what is the best way to achieve this?
Here is my code
<?php
$token = 'xyz';
$group_name = 'xyz';
$ipl = file_get_contents('https://cricket-api.vercel.app/cri.php?url=https://www.cricbuzz.com/live-cricket-scores/37631/kkr-vs-srh-49th-match-indian-premier-league-2021'); // cricbuzz unofficial API
$ipl_data = json_decode($ipl, true);
$current_score = $ipl_data['livescore']['current'];
$bot = "https://api.telegram.org/bot{$token}/sendMessage?chat_id={$group_name}&text={$current_score}";
$hit = file_get_contents($bot);
?>

How to optimize the facebook likes counter onpage

I'm trying to optimize my following code that shows how many likes the page/post on my website have.
This code is looping for 20 posts in my homepage and it's very slow to load.
Is there a way to speed up this code maybe using another call?
Thanks
$url = get_permalink();
$fburl = "http://api.facebook.com/method/fql.query? query=select%20like_count%20from%20link_stat%20where%20url='$url'&format=atom";
$ch = curl_init($fburl);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
$atom_data = curl_exec($ch);
preg_match('#like_count>(\d+)<#',$atom_data,$matches);
$like_count = $matches[1];
echo "$like_count";
You can also use an IN list for your URLs like this:
select url, like_count from link_stat where url in ('URL1', 'URL2')
Questions:
Why do you use a deprecated endpoint, and not https://graph.facebook.com/fql?q=...
Why don't you use JSON formatting? This can easily be parsed with PHP and you don't have to use preg_match
You can speed up your code by using batched requests. So you request just one time and not 20 times... https://developers.facebook.com/docs/graph-api/making-multiple-requests/

how to : define and get a custom report from google analytics using gapi

I have a custom report called my-newsletters in Google analytics. I want to fetch this report with a php call to $ga->requestReportData(...) and then parse the response and format it up.
First I made an account to collect all my newsletter open and click hits - each time someone opens a newsletter or clicks on a link in the newsletter I capture that with a call to the __utm.gif on Google. That part is working and I include in the call ( in the Landing Page aka utmp parameter) some data such as the word 'open' and 'click' to distinguish the events and also some other data i hope to parse out later, plus i use the campaign field and maybe I should do something with the source field too - now I just dup the utmp field. So far that part seems to work.
Now I need help to define a report that will return that utmp and campaign field info and the number of hits each has taken, sorted by date of hit I guess. then i need to call that report from my php and then later parse it - the parsing part I'm not worried about yet.
PS: here is the code I use to generate the utm url
function getGoogleUtmUrl($source='Emails', $referer='opens', $estid='0',$mailid='0', $campaign){
$stat_id='MO-xxx31982-1';
$var_utmcs=urlencode( 'UTF-8');
$var_utmac = $stat_id;
$var_utmhn = 'mysite.com'; //enter your domain
$var_utmn = rand(1000000000,9999999999); //random request number
$var_cookie = rand(10000000,99999999); //random cookie number
$var_random = rand(1000000000,2147483647); //number under 2147483647
$var_today = time(); //today
$var_referer = $referer; //referer url
$utm_source = 'my_newsletter';
$utm_medium = 'Emails';
$utm_campaign = $campaign;//$_GET['url'];
$var_uservar = $estid.'_'.$mailid; //enter your own user defined variable
$var_utmp = 'mysite.com/newsletters/'.$referer.'/'.$estid.'/'.$mailid;//.$estid;//$_GET['url']; //this example adds a fake file request to the (fake) tracker directory (the image/pdf filename).
$urchinUrl1 = 'http://www.google-analytics.com/__utm.gif?utmwv=4.3&utmn='.$var_utmn.'&utmsr='.$referer.'&utmcs='.$var_utmcs.
'&utmul=en&utmje=0&utmfl=-&utmdt='.$utm_campaign.'&utmhn='.$var_utmhn.
'&utm_source='.$var_utmp.'&utm_medium='.$utm_medium.'&utm_campaign='.$utm_campaign.'&utmr='.$var_referer.
'&utmp='.$var_utmp.'&utmac='.$var_utmac.
'&utmcc=__utma%3D'.$var_cookie.'.'.$var_random.'.'.
$var_today.'.'.$var_today.'.'.$var_today.
'.2%3B%2B__utmb%3D'.$var_cookie.'%3B%2B__utmc%3D'.
$var_cookie.'%3B%2B__utmz%3D'.$var_cookie.'.'.$var_today.
'.2.2.utmccn%3D(direct)%7Cutmcsr%3D(direct)%7Cutmcmd%3D(none)%3B%2B__utmv%3D'.
$var_cookie.'.'.'%3B';
// Now fire off the HTTP request
echo "urchinURL1 == ".$urchinUrl1.' '.__FILE__.' '.__LINE__.'<br/>';
return $urchinUrl1;
seems like over kill to me but it works, I tried the code at https://developers.google.com/analytics/devguides/collection/other/mobileWebsites and it doesn't work - the opens and clicks do not register in analytics - at least not on the real time page.
Please help.
I suggest that you build your report query first, I recommend that you use Google Analytics Query Explorer for that.
And next use the reporting API from PHP to transpose the resulting query and extract the data from within your app.

mySQL + Facebook FQL queries make my page really slow. How to improve performance?

I have many fan pages that I admin in Facebook and I made a little script to let me see how many fans they have. I have saved the pages (page_name + page_id ) I want in a mySQL database. The script makes a FQL query and prints how many fans every page has.
The problem is that when I added the FQL query, the page became kind of slow. I guess if I add other FQL queries it will become really slow to load.
My question is: What are some methods to use so my page will be loaded as fast as possible?
I thought of having the fans and other data saved in DB. But that means I will not have real time numbers.
Thank you.
$my_pages = mysql_query("SELECT page_name, page_id FROM pages WHERE user = '".$my_id."' ");
while($page_name = mysql_fetch_assoc($my_pages)) {
$fan_count = $facebook->api("/fql", array("q" => "SELECT fan_count FROM page WHERE page_id = '".$page_name['page_id']."'"));
echo $page_name['page_name'].'-'.$fan_count['data'][0]['fan_count'], '<br />';
}
It'll be much better to get all pages ids from DB, then issue single call to Graph API and just iterate over results.
$my_pages = mysql_query("SELECT page_name, page_id FROM pages WHERE user = '{$my_id}';");
$pages = array();
while($page = mysql_fetch_assoc($my_pages)) {
$pages[] = $page['page_id'];
}
$pagesIds = implode(',', $pages);
$pagesFanCounts = $facebook->api("/fql", array(
"q" => "SELECT page_id, name, fan_count FROM page WHERE page_id IN ({$pagesIds})"
));
foreach ($pagesFanCounts['data'] as $page){
echo "{$page['name']} - {$page['fan_count']}", '<br />';
}
BTW, Never but never do calls to external services like this in a loop with unknown number of iterations and for sure not while having open connection to DB (this may slow down not only the single user result but may have impact on other visitors/application users)!
P.S.
You can read some stuff on FQL performance from removed and outdated (FQL stuff still conceptually correct) Performance Guide (web.archive.org)

Facebook Friends Count?

What is the best way to count a Facebook user's friends...
I'm currently using (PHP):
$data = $facebook->api('/me/friends');
$friends_count = count($data['data']);
and its very slow... (about 2 secs)
Querying the facebook api sends a request to facebook. Because its a common http-request this Probably takes most of the time. There is usually no way around it. If you need the values more often, you should cache them somewhere
if (file_exists($cacheFile)) {
$data = file_get_contents($cachefile);
} else {
$data = $facebook->api('/me/friends');
file_put_contents($cacheFile, $data);
}
$friends_count = count($data['data']);
Remember to update the cache file from time to time.
If you are not processing the data given by Facebook on server side, instead of doing it using PHP, you can use JavaScript graph API to fetch, it can fetch it using ajax which wont effect your page load time.

Categories