get user list who likes facebook page [duplicate] - php

This question already has answers here:
Facebook API: Get fans of / people who like a page
(8 answers)
Closed 5 years ago.
I am working with codeigniter.
I want to get user list who likes facebook page,in page currently 675 likes but,from below code it shows me 6 likes only ,I am not sure this is correct way or not.
public function fetch_fb_fans($fanpage_name="pagename", $no_of_retries = 10, $pause = 500000 /* 500ms */){
$ret = array();
// prepare real like user agent and accept headers
$context = stream_context_create(array('http' => array('header' => 'User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/49.0.2623.108 Chrome/49.0.2623.108 Safari/537.36\r\nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8\r\nAccept-encoding: gzip, deflate, sdch\r\nAccept-language: en-US,en;q=0.8,pl;q=0.6\r\n')));
// get page id from facebook html og tags for mobile apps
$fanpage_html = file_get_contents('https://www.facebook.com/' . $fanpage_name, false, $context);
if(!preg_match('{fb://page/(\d+)}', $fanpage_html, $id_matches)){
// invalid fanpage name
return $ret;
}
$url = 'http://www.facebook.com/plugins/fan.php?connections=100&id=pageid';
for($a = 0; $a < $no_of_retries; $a++){
$like_html = file_get_contents($url, false, $context);
preg_match_all('{href="https?://www\.facebook\.com/([a-zA-Z0-9\._-]+)" data-jsid="anchor" target="_blank"}', $like_html, $matches);
if(empty($matches[1])){
// failed to fetch any fans - convert returning array, cause it might be not empty
return array_keys($ret);
}else{
// merge profiles as array keys so they will stay unique
$ret = array_merge($ret, array_flip($matches[1]));
}
// don't get banned as flooder
usleep($pause);
}
echo"<pre>";print_r($ret);die;
}
can any one help me to get required result?

This is the documentation of the plugin.
https://developers.facebook.com/docs/plugins/page-plugin
The connections param doesn't is accepted and no take effects.

Related

Find entry in JSON (Kraken.com uncommon JSON format) [duplicate]

This question already has answers here:
Multidimensional array: check if key exists
(3 answers)
Closed 3 months ago.
I need to find if a string exists in JSON Kraken.com retrieved file:
I get it this way:
$sURL = "https://api.kraken.com/0/public/OHLC?pair=ETHAED&interval=5&since=". strtotime("-1 day");
$ch = curl_init();
$config['useragent'] = 'Mozilla/5.0 (Windows NT 6.2; WOW64; rv:17.0) Gecko/20100101 Firefox/17.0';
curl_setopt($ch, CURLOPT_USERAGENT, $config['useragent']);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $sURL);
$result = curl_exec($ch);
curl_close($ch);
$obj = json_decode($result, true);
Sometimes pairs names differ from URL string and JSON (i.e. I can write LTCEUR but in JSON I see LTCZEUR
So I need to check if the string does exists in the $obj
$sName = "ETHAED";
print_r($obj);
if (in_array($sName,$obj)){
echo("Found ".$sName."<br>");
}else{
echo("NOT FOUND"."<br>");
}
but this doesn't work.
if I do a print_r() I can clearly see the pair name, but can't verify it.
Any suggestion?
Kraken.com JSON is not standard so I can't easily retrieve the name of the PAIR, I tried all possible combinations of $obj["result"][$sName] but without result.
Example:
https://api.kraken.com/0/public/OHLC?pair=LTCUSD
Here pair is LTCUSD
But on Json:
{"error":[],"result":{"XLTCZUSD":[[1669197540,"78.74","78.74","78.58","78.59","78.59","23.82168114",8]
Something is wrong with your comparison.
in_array($sName,$obj)
Should be:
is_array($obj['result'][$sName] ?? null)
Caveat: Read that carefully; it's now is instead of in.
Or, if you don't care if it's null, a string, or non-array:
array_key_exists($obj['result'], $sName)
Detailed explanation
in_array($sName,$obj) is checking if $sName matches (== equality) any of the elements in the first level of your array.
Since the first level of the array looks like this (pseudocode here):
error => []
result => [
XLTCZUSD => [...]
last: 123456
]
Since 'ETHAED' is neither [] nor is it [XLTCZUSD => [...],last: 123456] it doesn't match anything.
Yes it works perfectly.
Just a little correction on format:
if (array_key_exists($sName, $obj['result'])){
echo("FOUND ".$sName."<br>");
}else{
echo("ERROR ".$sName."<br>");
}

i am using a rest API i need to parse a forever changing json result

Okay so here goes i am using a rest api called strichliste
i am creating a user credit payment system
i am trying to grab a users balance by username problems is
my restapi i can only get the blanace via its userid
I have created a bit of php that grabs all the current users and the corresponding id and balance using this below
function getbal(){
// Get cURL resource
$curl = curl_init();
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'https://example.io:8081/user/'
)
);
// Send the request & save response to $resp
$resp = curl_exec($curl);
// Close request to clear up some resources
curl_close($curl);
print_r($resp);
}
this is the resulting respinse i get after using this in my main php script
<? getbal(); ?>
result --- #
{
"overallCount":3,
"limit":null,
"offset":null,"entries":[
{"id":1,
"name":"admin",
"balance":0,
"lastTransaction":null
},
{"id":2,
"name":"pghost",
"balance":0,
"lastTransaction":null
},
{"id":3,
"name":"sanctum",
"balance":0,
"lastTransaction":null
}
]
}
as you can see there are only currently 3 users but this will grow everyday so the script needs to adapt to growing numbers of users
inside my php script i have a var with the currently logged in use so example
$user = "sanctum";
i want a php script that will use the output fro gatbal(); and only output the line for the given user in this case sanctum
i want it to output the line in jsondecode for the specific user
{"id":3,"name":"sanctum","balance":0,"lastTransaction":null}
can anyone help
$user = "sanctum";
$userlist = getbal();
function findUser($u, $l){
if(!empty($l['entries'])){
foreach($l['entries'] as $key=>$val){
if($val['name']==$user){
return $val;
}
}
}
}
This way, once you have the list, and the user, you can just invoke findUser() by plugging in the userlist, and the user.
$userData = findUser($user, $userlist);
However, I would suggest finding a way to get the server to return only the user you are looking for, instead of the whole list, and then finding based on username. But thats another discussion for another time.

php - Facebook Api - Get Fan Page Posts

I am trying to get user's fan page post using the following code, but it's give me warning
Warning: file_get_contents(https://graph.facebook.com/782176371798916/posts): failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request
$page_posts = file_get_contents('https://graph.facebook.com/'.$page_id.'/posts');
$pageposts = json_decode($page_posts);
foreach ($pageposts["data"] as $fppost) {
echo $fppost['message'];
}
SO, how is the correct way to get user's fan page post?
The solution I found is by using the following code:
$pageposts = $facebook->api('/'.$page_id.'/posts', 'GET');
foreach ($pageposts["data"] as $fppost) {
echo $fppost['message'];
}
You didn't send the access_token parameter, just add it and it should work like charm:
$page_id = 'smashmag'; // Page ID or username
$token = '553435274702353|OaJc7d2WCoDv83AaR4JchNA_Jgw'; // Valid access token, I used app token here but you might want to use a user token .. up to you
$page_posts = file_get_contents('https://graph.facebook.com/'.$page_id.'/posts?fields=message&access_token='.$token); // > fields=message < since you want to get only 'message' property (make your call faster in milliseconds) you can remove it
$pageposts = json_decode($page_posts);
foreach ($pageposts->data as $fppost) {
if (property_exists($fppost, 'message')) { // Some posts doesn't have message property (like photos set posts), errors-free ;)
print $fppost->message.'</br>';
}
}

get_browser() array into variables?

Im currently playing around with browser detection mainly for statistics from the site and to better design the site in future. No ive been told the best way to go about this is to use the following code which shows all the browser info in an array if all my ini files are in place (which they are)
function list_array ($array) {
while (list ($key, $value) = each ($array)) {
$str .= "$brw = <b>$key:</b> $value<br>\n";
}
return $str;
}
echo "$HTTP_USER_AGENT<hr>\n";
$browser = get_browser();
echo list_array ((array) $browser);
The then displays this
browser_name_regex: �^mozilla/5\.0 \(.*windows nt 6\.2.*wow64.*\) applewebkit/.* \ (khtml, like gecko\).*chrome/28\..*safari/.*$�
= browser_name_pattern: Mozilla/5.0 (*Windows NT 6.2*WOW64*) AppleWebKit/* (KHTML, like Gecko)*Chrome/28.*Safari/*
= parent: Chrome 28.0
= platform: Win8
= platform_version: 6.2
= win32:
= win64: 1
= comment: Chrome 28.0
= browser: Chrome
= version: 28.0
= majorver: 28
= minorver: 0
= frames: 1
= iframes: 1
= tables: 1
= cookies: 1
= javascript: 1
= javaapplets: 1
= cssversion: 3
= alpha:
= beta:
= win16:
= backgroundsounds:
= vbscript:
= activexcontrols:
= ismobiledevice:
= issyndicationreader:
= crawler:
= aolversion: 0
Now heres were the problem lies all detect browser php plugings or download are overly complicated all im looking to do i seperate iphones ipads android blackberry apple and some of the most basic pieces of information. How can I turn this array into variables that can be used later. for example if i can grab the 2nd 3rd n 4th in the array i will have all the information i want as accurate as i need it all otherways and i seem to get problems with iphones showing as just a mobile device and what not Ive already tried for example
if (preg_match('/windows nt 6.2/i', $u_agent)) {
$platform = 'Windows 8';
}
and
$blackberry = strpos(&ua, 'Android') ? true : false;
and looked at
http://chrisschuld.com/projects/browser-php-detecting-a-users-browser-from-php.html
http://www.phpjabbers.com/php-snippet/detect-browser-php.php
http://www.killersites.com/community/index.php?/topic/2562-php-to-detect-browser-and-operating-system/
First of all, you should use foreach() instead of each + list. See http://www.php.net/manual/fr/function.each.php#63805
Second, you're casting the result of get_browser as an array for your list_array function when you do (array) $browser, that's why it works and why it doesn't create a fatal error.
If you want to use the result of get_browser as an array, you should however use the built in option to do so, ie :
$b = get_browser(null, true);
The second option here tells get_browser to return an array instead of an object, this should solve your problem of trying to use a class as an array.
You will then be able to use :
echo $b['browser'];
The default return type for get_browser beeing an object, you would have to use
$b = get_browser();
echo $b->browser;
if you wanted the same result.
Try reading the php manual http://php.net/manual/en/function.get-browser.php to get a better understanding of the functions you're using. You will find useful code in the comments aswell.
Finally, as you've been told, you should use an existing API for statistics.
Good luck with your coding.

Passing updated value to function (twitter api max_id problems)

I am trying to work with the Twitter search API, I found a php library that does authentication with app-only auth and I added the max_id argument to it, however, I would like to run 450 queries per 15 minutes (as per the rate-limit) and I am not sure about how to pass the max_id. So I run it first with the default 0 value, and then it gets the max_id result from the API's response and runs the function again, but this time with the retrieved max_id value and does this 450 times. I tried a few things, and I can get the max_id result after calling the function, but I don't know how to pass it back and tell it to call the function with the updated value.
<?php
function search_for_a_term($bearer_token, $query, $result_type='mixed', $count='15', $max_id='0'){
$url = "https://api.twitter.com/1.1/search/tweets.json"; // base url
$q = $query; // query term
$formed_url ='?q='.$q; // fully formed url
if($result_type!='mixed'){$formed_url = $formed_url.'&result_type='.$result_type;} // result type - mixed(default), recent, popular
if($count!='15'){$formed_url = $formed_url.'&count='.$count;} // results per page - defaulted to 15
$formed_url = $formed_url.'&include_entities=true'; // makes sure the entities are included
if($max_id!='0'){$formed_url=$formed_url.'&max_id='.$max_id;}
$headers = array(
"GET /1.1/search/tweets.json".$formed_url." HTTP/1.1",
"Host: api.twitter.com",
"User-Agent: jonhurlock Twitter Application-only OAuth App v.1",
"Authorization: Bearer ".$bearer_token."",
);
$ch = curl_init(); // setup a curl
curl_setopt($ch, CURLOPT_URL,$url.$formed_url); // set url to send to
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); // set custom headers
ob_start(); // start ouput buffering
$output = curl_exec ($ch); // execute the curl
$retrievedhtml = ob_get_contents(); // grab the retreived html
ob_end_clean(); //End buffering and clean output
curl_close($ch); // close the curl
$result= json_decode($retrievedhtml, true);
return $result;
}
$results=search_for_a_term("mybearertoken", "mysearchterm");
/* would like to get all kinds of info from here and put it into a mysql database */
$max_id=$results["search_metadata"]["max_id_str"];
print $max_id; //this gives me the max_id for that page
?>
I know that there are must be some existing libraries that do this, but I can't use any of the libraries, since none of them have updated to the app-only auth yet.
EDIT: I put a loop in the beginning of the script, to run e.g. 3 times, and then put a print statement to see what happens, but it only prints out the same max_id, doesn't access three different ones.
do{
$result = search_for_a_term("mybearertoken", "searchterm", $max_id);
$max_id = $result["search_metadata"]["max_id_str"];
$i++;
print ' '.$max_id.' ';
}while($i < 3);

Categories