php file get contents not working while fetching fb page data - php

I have the following code to get fb page list
$graph_url_pages = "https://graph.facebook.com/me/accounts?access_token=".$_SESSION['token'];
$pagedata=file_get_contents($graph_url_pages);
echo "DATA : <br>";
print_r($pagedata);
$pages=json_decode($pagedata,true);
var_dump($pages);
$dropdown = "";
for($i=0;$i<count($pages->data);$i++)
{
if($me=="iamindex"){
$dropdown .= "<option value='".$pages->data[$i]->access_token."-".$pages->data[$i]->id."'>".$pages->data[$i]->name."</option>";
}elseif($me=="iammulti"){
$dropdown .= "<input type='checkbox' name='page' id='status' value='".$pages->data[$i]->access_token."-".$pages->data[$i]->id."'>".$pages->data[$i]->name."<br>";
}else{$dropdown.="<option value=''>No Category Selection</option>";}
}
$pagedata and $pages is empty and so dropdown doesn't get populated.
Somewhere at the top of the page I am using Ob_start() and at the end Ob_flush(); And they are needed. I don't know whether this is the issue.
Would be great if somebody can point out what is going wrong ! if more code is needed, I can provide. Please note I am an amateur programmer. Self taught.

I recommend using cURL
$graph_url_pages = "https://graph.facebook.com/me/accounts?access_token=".$_SESSION['token'];
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $graph_url_pages);
if(curl_error($c))
{
echo 'error:' . curl_error($c);
//it will produce the error if any exists
}
$data = curl_exec($ch);
curl_close($ch);
print_r($data);

Related

Get Facebook Profile URL From Facebook Profile id Using PHP

I have a list of Facebook links in xls sheet with Facebook id something like this
and when i go through these links means if i access Facebook with id www.facebook.com/7500
i get urls something like this https://www.facebook.com/davesachs/
so my question is i want to do this with PHP, i have a PHP page which read data from xls sheet
my code here:
require_once 'src/SimpleXLSX.php';
if ( $xlsx = SimpleXLSX::parse('fburl.xlsx') ) {
$rows= $xlsx->rows();
foreach($rows as $data){
echo $data[0].'<br>';
}
} else {
echo SimpleXLSX::parseError();
}
its returning all Facebook link with id same that i am passing like www.facebook.com/7500 but i want it return URL / link of profile as https://www.facebook.com/davesachs/ ,if it is possible please help me to do that.
You can do something like that, Taken reference from here
<?php
require_once 'src/SimpleXLSX.php';
if ( $xlsx = SimpleXLSX::parse('fburl.xlsx') ) {
$rows= $xlsx->rows();
foreach($rows as $data){
getRedirectedUrl($data[0]);
}
} else {
echo SimpleXLSX::parseError();
}
function getRedirectedUrl($link){
$url=$link;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // Must be set to true so that PHP follows any "Location:" header
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$a = curl_exec($ch); // $a will contain all headers
$url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL); // This is what you need, it will return you the last effective URL
// Uncomment to see all headers
/*
echo "<pre>";
print_r($a);echo"<br>";
echo "</pre>";
*/
echo $url; // Voila
}
?>

Alternative to curl_init()?

I'm trying to debug some code using either of these two intrepreters. The code below runs on my GoDaddy site and produces the appropirate output arrays. But, won't run in either of these intrepreters.
Is there a way to modify this code to run in the intrepreters so I can get past line 2 of the code? I inclcuded phpinfo(INFO_MODULES); at the end as an aid.
OR do you know of an online intrepreter that will run this code?
https://3v4l.org/
http://www.runphponline.com/
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = '';
curl_setopt($ch, CURLOPT_URL, "https://api.iextrading.com/1.0/stock/market/batch?symbols=aapl,tsla,ge&types=quote,earnings,stats");
$data = curl_exec($ch);
curl_close($ch);
$data = json_decode($data, true);
// debug -------------------------------
echo ' - ';
echo (count($data)); // number of elements
echo " - " . "<br />\n";
var_dump_pre($data); // dump the array
echo "-" . "<br />\n";
echo "xxxxxxxxxxxxxx-" . "<br />\n";
function var_dump_pre($mixed = null) {
echo '<pre>';
var_dump($mixed);
echo '</pre>';
return null;
}
phpinfo(INFO_MODULES);
?>
http://php.net/manual/en/curl.installation.php
It looks like there are some dependancies that you have to install to use curl_init.
It looks like some poor sap did the work for you at http://phpfiddle.org/
Your code works there.
Since the code ran on my GoDaddy site I was able to copy the data returned from the '$data = curl_exec($ch);' insruction and assign it to a variable name at the start of the code I'm trying to debug. So, the code I'm trying to debug starts out with the intended incomimg data (and doesn't have to go get it). I can now continue to use any of these three online intrepreters:
https://3v4l.org/
http://www.runphponline.com/
http://phpfiddle.org/

Need help passing session using header redirect

I am trying to create a 3rd party app for a game I like (EVE Online) which requires oauth.
I have decided to do the oauth handling in it's own script and once resolved, put an associative array into the session based on the CharacterID retrieved from oauth.
I am able to successfully output the desired contents of the session array from the /callback/index.php' that handles the oauth requests at the end of the script. However, I want to keep this script "in the background" and somewhat secret, and redirect most of the activity to a '../main.php' in the directory just below.
However, when I finally get to main.php, printing the session returns an empty array. What am I doing wrong? I have searched all day for solutions and have implemented every one of them.
Below are the relevant files:
session.php
<?php
if (!empty($_GET['ID'])) {
session_id($_GET['ID']);
}
if (session_status() == PHP_SESSION_NONE) {
session_start();
} else {
$sLocation="http://eve.oriigen.com/eClt";
header("Location: ".$sLocation);
exit();
}
?>
/callback/index.php
<?php require_once '../src/session.php' ?>
<?php require_once 'secret.php' ?>
<?php
function auth_error($error_message)
{
print "There's been an error";
error_log($error_message);
exit();
}
$sUserAgent = "EVE Contact List Toolkit [eClt]";
$post_url = "https://login.eveonline.com/oauth/token";
$get_url = "https://login.eveonline.com/oauth/verify";
$client_id="Basic ".base64_encode($sClientId.":".$sSecretKey);
$content_type = "application/x-www-form-urlencoded";
$host_url = "login.eveonline.com";
$aHeaders = array("Authorization: ".$client_id,
"Content-type: ".$content_type,
"Host: ".$host_url);
$aPostFields = array("grant_type"=>"authorization_code",
"code"=>$_GET["code"]);
$oCurlRequest = curl_init();
curl_setopt($oCurlRequest, CURLOPT_URL, $post_url);
curl_setopt($oCurlRequest, CURLOPT_USERAGENT, $sUserAgent);
curl_setopt($oCurlRequest, CURLOPT_HTTPHEADER, $aHeaders);
curl_setopt($oCurlRequest, CURLOPT_POST, count($aPostFields));
curl_setopt($oCurlRequest, CURLOPT_POSTFIELDS, http_build_query($aPostFields));
curl_setopt($oCurlRequest, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($oCurlRequest, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($oCurlRequest, CURLOPT_SSL_VERIFYHOST, 2);
$oResult = curl_exec($oCurlRequest);
if ($oResult===false) {
auth_error(curl_error($oCurlRequest));
}
curl_close($oCurlRequest);
$aResponse=json_decode($oResult);
unset($oCurlRequest);
unset($oResult);
$sTokenType=$aResponse->token_type;
$sAuthToken=$aResponse->access_token;
$iAuthTokenExpire=$aResponse->expires_in;
$sRefreshToken=$aResponse->refresh_token;
$sGetHeader="Authorization: ".$sTokenType." ".$sAuthToken;
$oCurlRequest = curl_init();
curl_setopt($oCurlRequest, CURLOPT_URL, $get_url);
curl_setopt($oCurlRequest, CURLOPT_USERAGENT, $sUserAgent);
curl_setopt($oCurlRequest, CURLOPT_HTTPHEADER, array($sGetHeader));
curl_setopt($oCurlRequest, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($oCurlRequest, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($oCurlRequest, CURLOPT_SSL_VERIFYHOST, 2);
$oResult = curl_exec($oCurlRequest);
if ($oResult===false) {
auth_error(curl_error($oCurlRequest));
}
curl_close($oCurlRequest);
$aResponse=json_decode($oResult);
unset($oCurlRequest);
unset($oResult);
$sCharId=(string)$aResponse->CharacterID;
$sCharacterName=$aResponse->CharacterName;
$sExpiresOn=$aResponse->ExpiresOn;
$sTokenType=$aResponse->TokenType;
$sCharacterOwnerHash=$aResponse->CharacterOwnerHash;
$sIntellectualProperty=$aResponse->IntellectualProperty;
/* $aCharInfo=array("CharID"=>(int)$sCharId,
"CharName"=>$sCharacterName,
"CharOwnerHash"=>$sCharacterOwnerHash,
"ExpiresOn"=>$sExpiresOn,
"AuthToken"=>$sAuthToken,
"AuthTokenExpIn"=>$iAuthTokenExpire,
"RefreshToken"=>$sRefreshToken);*/
if (!isset($_SESSION[(string)$sCharId])) {
$_SESSION[(string)$sCharId]=array("CharID"=>(int)$sCharId,
"CharName"=>$sCharacterName,
"CharOwnerHash"=>$sCharacterOwnerHash,
"ExpiresOn"=>$sExpiresOn,
"AuthToken"=>$sAuthToken,
"AuthTokenExpIn"=>$iAuthTokenExpire,
"RefreshToken"=>$sRefreshToken);
} else {
$_SESSION["moo"]=0;
}
session_write_close();
$sRedirect="../main.php?ID=".session_id();
header("Location: ".$sRedirect);
exit();
/* echo "<pre>";
print_r($_SESSION);
echo "</pre>";
echo "<hr />";
echo gettype($iCharId);
echo "<hr />";
echo "<pre>";
print_r($aCharInfo);
echo "</pre>";*/
?>
../main.php
<?php require_once './src/session.php' ?>
<?php
//echo "SessionId: ".session_id()."<br />";
//echo "<hr/>";
//echo "<pre>";
print_r($_SESSION);
//echo "</pre>";
?>
[ Logout ]
As you can see from the commented sections, I have tried every diagnostic printout I can think of. So, where am I going wrong?
Solved it - per a related question I found only after posting this question:
from here:
The PHP session storage mechanism was originally built around "registering" variables, so the keys in $_SESSION must be names that could be treated as variables in their own right. This means that $_SESSION[10] is invalid, because $10 wouldn't be a valid variable name, and since $foo[10] and $foo['10'] refer to the same thing, $_SESSION['10'] is invalid as well.
CharacterID was either and int of a string version of an int, apparently PHP sessions don't like numbers in their array keys...

Steam API load the items json

Hello guys i started to try use Steam API and i already done login... but i have a big problem to get items. I cant find solution what im doing wrong.
$GetClientSteamItemsUrl = " http://steamcommunity.com/profiles/" . $_SESSION['steam_steamid'] . "/inventory/json/730/2";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $GetClientSteamItemsUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 3);
$output = curl_exec($ch);
$ArrayInventory = json_decode($output, true);
foreach($ArrayInventory['rgDescriptions'] as $inventory)
{
echo $inventory;
}
On that link is my items that i want to write their name on my page.
Error: Warning: Invalid argument supplied for foreach() in /data/web/virtuals/112855/virtual/www/subdom/ayy/index.php
Can someone help me to select specific part of code?
Try this
$inventory = file_get_contents("http://steamcommunity.com/profiles/".$_SESSION['steamid']."/inventory/json/730/2");
$myarrayInv = json_decode($inventory, true);
foreach($myarrayInv['rgDescriptions'] as $item)
{
echo $item['name'];
}
if you want icon_url etc. do $item['icon_url'], hope this helps.

Mulitple Instagram feeds on one page

I have successfully put an Instagram feed for a specific user on my website, but having very little experience with PHP I cannot figure out how to simply repeat the process. I'm looking to showcase two different users, side by side in one div.
<?php
// http://jelled.com/instagram/lookup-user-id/
$userid = "userid";
// http://instagram.com/developer/
$clientid = "clientid";
// http://jelled.com/instagram/access-token/
$accessToken = "token";
// number of photos to return
$count = "4";
// Gets our data
function fetchData($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 20);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
// Pulls and parses data.
$result = fetchData("https://api.instagram.com/v1/users/{$userid}/media/recent/?access_token={$accessToken}&count={$count}");
$result = json_decode($result);
// cycles through the json tree and uses the low res url in the img tag
echo "<ul>";
foreach ($result->data as $photo) {
$img = $photo->images->{$display_size="thumbnail"};
echo "<li><a href='{$photo->link}'><img src='{$img->url}' /></a></li>";
}
echo "</ul>";
?>
If I just paste the code in again, the whole page stops working. I'm guessing this is something simple, but I don't know exactly what I'm looking for! Should this code be in a separate file that is linked into my website- rather than throwing some PHP inside an HTML Bootstrap site?
Thanks in advance.
EDIT
I was able to get this working by using the answer below. I wanted each account to have it's own div, and the only way I know how to do that is in the html file- which would mean I still need to link to two different files. I created one file with the correct code, and another with this:
<?php
// Set User ID here for different profile
//$userid = "idHere";
$userid = "296517730";
$result = fetchData("https://api.instagram.com/v1/users/{$userid}/media/recent/?client_id={$clientid}&count={$count}");
$result = json_decode($result);
// cycles through the json tree and uses the low res url in the img tag
echo "<ul>";
foreach ($result->data as $photo) {
$img = $photo->images->{$display_size="thumbnail"};
echo "<li><a href='{$photo->link}'><img src='{$img->url}' /></a></li>";
}
echo "</ul>";
?>
It was working just fine on my domain, but when I moved it to my client's domain I'm getting this error: Warning: Invalid argument supplied for foreach() in /home/savenors/savenorsmarket.com/bostoninsta.php on line 53
What happened? I'm guessing whatever I did to get this to work wasn't really working.. but it looked fine to me. Any ideas? This is the website: http://www.savenorsmarket.com
Here's code that is working on my machine pulling in twice. It pulls the same user pictures twice, but to fix this just reset the user id variable before making a second call to fetchData();
<?php
$userid = "idHere";
// http://instagram.com/developer/
$clientid = "IDhere";
// number of photos to return
$count = "4";
// Gets our data
function fetchData($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 20);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
// Pulls and parses data.
$result = fetchData("https://api.instagram.com/v1/users/{$userid}/media/recent/?client_id={$clientid}&count={$count}");
$result = json_decode($result);
// cycles through the json tree and uses the low res url in the img tag
echo "<ul>";
foreach ($result->data as $photo) {
$img = $photo->images->{$display_size="thumbnail"};
echo "<li><a href='{$photo->link}'><img src='{$img->url}' /></a></li>";
}
echo "</ul>";
// Set User ID here for different profile
//$userid = "idHere";
$result = fetchData("https://api.instagram.com/v1/users/{$userid}/media/recent/?client_id={$clientid}&count={$count}");
$result = json_decode($result);
// cycles through the json tree and uses the low res url in the img tag
echo "<ul>";
foreach ($result->data as $photo) {
$img = $photo->images->{$display_size="thumbnail"};
echo "<li><a href='{$photo->link}'><img src='{$img->url}' /></a></li>";
}
echo "</ul>";
?>
Also note that I'm using the client_id over the access_token. It should work either way though.

Categories