Problem with require_once in a hello world facebook app - php

Im new to developing facebook apps.I have the following issue and would be glad if someone could help.
I have registered my app on facebook and uploaded the code and php client library to the hosting server. If i use the code below then everything works fine.
<?php
require_once('./facebook/php/facebook.php');
/* initialize the facebook API with your application API Key
and Secret */
$facebook = new Facebook("<my_api_key>","<my_secret_key>");
$user = $facebook->require_login();
echo "<p>Your User ID is: $user</p>";
echo "<p>Your name is: <fb:name uid=\"$user\" useyou=\"false\"/></p>";
echo "<p>You have several friends: </p>";
$friends = $facebook->api_client->friends_get();
echo "<ul>";
foreach ($friends as $friend) {
echo "<li><fb:name uid=\"$friend\" useyou=\"false\" /></li>";
}
echo "</ul>";
/* Echo some information that will
help us see what's going on with the Facebook API: */
echo "<pre>Debug:" . print_r($facebook,true) . "</pre>";
?>
But, if i divide the code into two files as follows then i just get a blank canvas when i navigate to http://apps.facebook.com/myapp
appinclude.php
<?php
require_once('./facebook/php/facebook.php');
/* initialize the facebook API with application API Key
and Secret */
$facebook = new Facebook("<my_api_key>","<my_secret_key>");
$user = $facebook->require_login();
?>
index.php
<?php
require_once('./appinclude.php');
echo "<p>Your User ID is: $user</p>";
echo "<p>Your name is: <fb:name uid=\"$user\" useyou=\"false\"/></p>";
echo "<p>You have several friends: </p>";
$friends = $facebook->api_client->friends_get();
echo "<ul>";
foreach ($friends as $friend) {
echo "<li><fb:name uid=\"$friend\" useyou=\"false\" /></li>";
}
echo "</ul>";
/* Echo some information that will
help us see what's going on with the Facebook API: */
echo "<pre>Debug:" . print_r($facebook,true) . "</pre>";
?>
Any way to fix this ?
Thank You.

The way I set up my app is to have all the files in the same directory so there is no confusion.
/Myapp/index.php
<?php
require_once('appinclude.php');
?>
/Myapp/appinclude.php
<?php
require_once('facebook.php');
?>
The Myapp directory looks like this:
/Myapp/jsonwrapper/JSON/JSON.php
/Myapp/jsonwrapper/JSON/LICENSE
/Myapp/jsonwrapper/jsonwrapper.php
/Myapp/jsonwrapper/jsonwrapper_inner.php
/Myapp/facebook.php
/Myapp/facebookapi_php5_restlib.php
/Myapp/appinclude.php
/Myapp/index.php
In your second example the layout would need to be like this to work:
/facebook/php/facebook.php
/Myapp/AnotherDirectory/index.php
/Myapp/appinclude.php
Notice the appinclude.php and index.php are not in the same folder. index.php looks for a file appinclude.php in the directory above itself, and appinclude.php looks for a file facebook/php/facebook.php in the directory above itself. If you were to remove the dots and slashes from the front of the require statements it would look for it all in the same directory. Basically what you need to realize is that the ./ in require_once('./appinclude.php'); says look in the directory above this one.

I would check file paths.
It seems in your second (non-working version) you're trying to include a file from a directory called 'facebook/php/'.
If this is the directory that you've specified as your application's root then I would guess Facebook won't allow you to include files below that directory level.

Related

Php code to randomly pick links And Open

Im new to Php. I kinda need code to open Links in browser when script is loaded.
heres my code below.
<?php
$links = array_open("https://stackoverflow.com/",
"https://outlook.office.com/",
"https://www.protectedtext.com/",
"https://www.adobe.com/",
"https://www.linkedin.com");
echo $links[array_rand($links)];
?>
Hi change array_open to array
<?php
$links = array("https://stackoverflow.com/", "https://outlook.office.com/", "https://www.protectedtext.com/", "https://www.adobe.com/", "https://www.linkedin.com");
echo $links[array_rand($links)];
?>
And if you want to send the browser to the link you would send a location header like so...
<?php
$links = array("https://stackoverflow.com/", "https://outlook.office.com/", "https://www.protectedtext.com/", "https://www.adobe.com/", "https://www.linkedin.com");
header('Location: ' . $links[array_rand($links)]);
exit;
?>

Logged in user name and last name wont show on the navbar

I'm a beginner in php and I want the name and last name of the logged in user to show on my navbar. Instead it shows the php code. This is my code inside the navbar.
<?php
echo "<p>" . $_SESSION['vorname'] . " " . $_SESSION['nachname'] . "</p>";
?>
This is what it shows instead.
The output on the screen.
I changed the file extension to .php and this is what it outputs now.
PHP-Files have to be saved with the .php file extension to be executed. I suppose the other working files all have the right file extension?
You have to save all files with php code as .php.
Inside them you can use clean HTML:
<html>
<head></head>
<body>
<h1>Hello, World!</h1>
</body>
</html>
or HTML mixed with PHP:
<html>
<head></head>
<body>
<?php echo '<h1>Hello, World!</h1>'; ?>
<?php echo '<p>You are logged as '.$_SESSION['vorname'].' '.$_SESSION['nachname'].'</p>'; ?>
</body>
</html>
And remember to use PHP server (XAMPP, WAMP) on localhost - PHP files will not work if you open them directly in web browser (i.e. file:///C:/xampp/htdocs/hello/index.php )
The notice suggests that session is not started in your script, so you need to call session_start() prior to accessing $_SESSION variable. It would also be wise to check whether the user is logged in or not:
<?php
session_start();
if (isset($_SESSION['vorname'], $_SESSION['nachname'])) {
echo "<p>" . $_SESSION['vorname'] . " " . $_SESSION['nachname'] . "</p>";
} else {
echo "<p>No user is logged in</p>";
}
?>

Unable to get FirstName and LastName from openid attributes

I am able to get the email when the user sign in via apps.com.
My problem is I cant get first name and last name. here's a sample code from intuit, I tried adding 'namePerson/first' and 'namePerson/last', to the required attribute but it doesn't help.
The codes that i use is from intuit example https://github.com/IntuitDeveloper/SampleApp-PHP-for-OpenId-OAuth-V3APICalls/blob/master/PHPSample/index.php
<?php
ob_start();
require_once("config.php");
require_once("CSS Styles/StyleElements.php");
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<h3>IPP PHP Sample App</h3>
<title>IPP PHP sample</title>
<script type="text/javascript" src="https://appcenter.intuit.com/Content/IA/intuit.ipp.anywhere.js"></script>
<script>
// Runnable uses dynamic URLs so we need to detect our current //
// URL to set the grantUrl value ########################### //
/*######*/ var parser = document.createElement('a');/*#########*/
/*######*/parser.href = document.url;/*########################*/
// end runnable specific code snipit ##########################//
intuit.ipp.anywhere.setup({
menuProxy: '',
grantUrl: 'http://'+parser.hostname+'/sampleqboapp/PHPSample/oauth.php?start=t'
// outside runnable you can point directly to the oauth.php page
});
</script>
</head>
<body>
<?php
# This sample uses the LightOpenID library located here: https://gitorious.org/lightopenid
echo '<div> Please refer to the <a target="_blank" href="http://localhost/PHPSample/ReadMe.htm">Read Me</a> page for detailed instructions and information regarding this sample </div><br />';
require 'lightopenid-lightopenid/openid.php';
try {
# Change 'localhost' to your domain name.
$openid = new LightOpenID('localhost');
if(!$openid->mode) {
echo '<div> This sample uses PHP 5.6.3 and Intuit PHP SDK version v3-php-sdk-2.2.0-RC
</div><br />';
echo '<div> To be listed on QuickBooks Apps.com, any app must implement OpenID for user authentication. This sample uses LightOpenID library located at
<a target="_blank" href="https://gitorious.org/lightopenid"> https://gitorious.org/lightopenid </a><br />
</div><br />';
# The connectWithIntuitOpenId parameter is passed when the user clicks the login button below
# The subscribeFromAppsDotCom parameter is an argument in the OpenID URL of a sample app on developer.intuit.com
# Example of OpenID URL: http://localhost/ippPhpOpenId/IPP-PHP-OpenID-Login.php?subscribeFromAppsDotCom
$openid->identity = "https://openid.intuit.com/Identity-jameshwart";
# The following two lines request email and full name
# from the Intuit OpenID provider
$openid->required = array(
'namePerson/friendly',
'contact/email' ,
'contact/country/home',
'namePerson',
'namePerson/first',
'namePerson/last',
'pref/language',
);
header('Location: ' . $openid->authUrl());
} elseif($openid->mode == 'cancel') {
echo 'User has canceled authentication!';
} else {
# Print the OpenID attributes that we requested above, email and full name
echo '<pre>';
print_r($openid);
print_r($openid->getAttributes());
echo '</pre>';
# Add a link to allow the user to logout. The link makes a JavaScript call to intuit.ipp.anywhere.logout()
echo '<br />Sign Out';
//oAuth code
require_once('../v3-php-sdk-2.2.0-RC/config.php'); // Default V3 PHP SDK (v2.0.1) from IPP
require_once(PATH_SDK_ROOT . 'Core/ServiceContext.php');
require_once(PATH_SDK_ROOT . 'DataService/DataService.php');
require_once(PATH_SDK_ROOT . 'PlatformService/PlatformService.php');
require_once(PATH_SDK_ROOT . 'Utility/Configuration/ConfigurationManager.php');
error_reporting(E_ERROR | E_PARSE);
// After the oauth process the oauth token and secret
// are storred in session variables.
$tk = $_SESSION['token'];
if(!isset($_SESSION['token'])){
echo "<h3>You are not currently authenticated!</h3>";
echo '<div> This sample uses the Pecl Oauth library for OAuth. </div> <br />
<div> If not done already, please download the Oauth package from
<a target="_blank" href="http://pecl.php.net/package/oauth"> http://pecl.php.net/package/oauth </a> and follow the instructions given
<a target="_blank" href="http://pecl.php.net/package/oauth"> here </a> for installing the Oauth module.
</div><br />
<div> Add the OAuth Consumer Key and OAuth Consumer Secret of your application to config.php file </div> </br>
<div> Click on the button below to connect this app to QuickBooks
</div>';
// print connect to QuickBooks button to the page
echo "<br /> <ipp:connectToIntuit></ipp:connectToIntuit><br />";
} else {
echo "<h3>You are currently authenticated!</h3>";
$token = unserialize($_SESSION['token']);
echo "If not already done, please make sure that you set the below variables in the app.config file, before proceeding further! <br />";
echo "<br />";
echo "realm ID: ". $_SESSION['realmId'] . "<br />";
echo "oauth token: ". $token['oauth_token'] . "<br />";
echo "oauth secret: ". $token['oauth_token_secret'] . "<br />";
echo "<br />";
echo "<button class='myButton' title='App Home Page' onclick='myFunction($value)'>Go to the app</button>";
echo ' ';
echo "<button class='myButton' title='Disconnect your app from QBO' onclick='Disconnect($value)'>Disconnect the app</button>";
echo ' ';
echo "<button class='myButton' title='Regenerate the tokens within 30 days prior to token expiration' onclick='Reconnect($value)'>Reconnect the app</button>";
echo "<br />";
echo "<br />";
echo "<br />";
echo '<div> <small> <u> Note:</u> Configuring the Oauth tokens manually in app.config file is only for demonstartion purpose in this sample app. In real time production app, save the oath_token, oath_token_secret, and realmId in a persistent storage, associating them with the user who is currently authorizing access. Your app needs these values for subsequent requests to Quickbooks Data Services. Be sure to encrypt the access token and access token secret before saving them in persistent storage.<br />
Please refer to this <a target="_blank" href="https://developer.intuit.com/docs/0050_quickbooks_api/0020_authentication_and_authorization/connect_from_within_your_app"> link </a>for implementing oauth in your app. </small></div> <br />';
}
}
} catch(ErrorException $e) {
echo $e->getMessage();
}
ob_end_flush();
?>
<script>
function myFunction(parameter){
window.location.href = "http://localhost/PHPSample/SampleAppHomePage.php";
}
function Disconnect(parameter){
window.location.href = "http://localhost/PHPSample/Disconnect.php";
}
function Reconnect(parameter){
window.location.href = "http://localhost/PHPSample/Reconnect.php";
}
</script>
</body>
</html>
Could someone point out what did i miss?

Why I'm not able to print the whole output to the screen in PHP?

I'm using Slim framework for my project. I've copied the Slim folder to my project directory.
No following is the code I'm having issue with :
PHP Code(requestdemo.php):
<?php
require 'Slim/Slim.php';
/* Invoke the static "registerAutoloader()" function defined within Slim class.
* Register the autoloader is very important.
* Without doing it nothing will work.
*/
\Slim\Slim::registerAutoloader();
//Instantiate Slim class in order to get a reference for the object.
$application = new \Slim\Slim();
$application->get(
'/request',
function()
{
GlOBAL $application;
echo " <br/><b>request methods</b>";
echo "<br/>application->request->getMethod()=".$application->request->getMethod();
echo "<br/>application->request->isGet()=".$application->request->isGet();
echo "<br/>application->request->isPost()=".$application->request->isPost();
echo "<br/>application->request->isPut()=".$application->request->isPut();
echo "<br/>application->request->isDelete()=".$application->request->isDelete();
echo "<br/>application->request->isHead()=".$application->request->isHead();
echo "<br/>application->request->isOptions()=".$application->request->isOptions();
echo "<br/>application->request->isPatch()=".$application->request->isPatch();
echo "<br/>application->request->isAjax()=".$application->request->isAjax();
echo "<br/> <br/><b>request headers</b>";
$headers = $application->request->headers;
foreach($headers as $k=>$v)
{
echo "<br/>$k => $v";
}
echo "<br/> <br/><b>request body</b>";
echo "<br/>body=".$application->request->getBody();
echo "<br/> <br/><b>request variables</b>";
echo "<br/>width=".$application->request->params('width');
echo "<br/>height=".$application->request->params('height');
echo "<br/> <br/><b>request get variables</b>";
echo "<br/>width=".$application->request->get('width');
echo "<br/>height=".$application->request->get('height');
echo "<br/> <br/><b>request post variables</b>";
echo "<br/>width=".$application->request->post('width');
echo "<br/>height=".$application->request->post('height');
echo "<br/> <br/><b>resource uri</b>";
/*From the below line I'm not able to see the output in a browser.*/
echo "<br/>rootUri=".$application->request->getUri();
echo "<br/>resourceUri=".$application->request->getResourceUri();
echo "<br/> <br/><b>request ajax check</b>";
echo "<br/>rootUri=".$application->request->isAjax();
echo "<br/>resourceUri=".$application->request->getResourceUri();
echo "<br/> <br/><b>request helpers</b>";
echo "<br/>content type=".$application->request->getContentType();
echo "<br/>media type=".$application->request->getMediaType();
echo "<br/>host=".$application->request->getHost();
echo "<br/>scheme=".$application->request->getScheme();
echo "<br/>path=".$application->request->getPath();
echo "<br/>url=".$application->request->getUrl();
echo "<br/>user agent=".$application->request->getUserAgent();
});
$application->run();
?>
The file 'requestdemo.php' is present in the directory titled "slimsamples" at location /var/www/slimsamples
As I hit the URL 'http://localhost/slimsamples/requestdemo.php/request' I'm able to see only the part of output in a browser window. From where I'm not able to see the output I've commented in my code. I'm not able to see the output after line resource uri. See the screenshot for further understanding.
Also there is no syntactical error in it then why it's happening I'm not understanding.
Can someone please find out the mistake I'm making here?
Thanks in advance.
Use: request->getUrl()
(You used request->getUri())
See http://dev.slimframework.com/phpdocs/classes/Slim.Http.Request.html#getUrl

How can I rewrite this PHP function to extract data from an external website/source

I have this PHP function that pulls/extracts data from xml elements and displays them on my webpage. However it is only working when used with a local path. not from any external sources. Here is the code.
Index.php
<html>
<body>
<?php
include('render_xml_to_html.php');
// The internal path. DOES work.
render_xml_data('example.xml');
?>
</body>
</html>
Example.xml
<eveapi version="2"><currentTime>2014-05-08 03:34:23</currentTime>
<result>
<serverOpen>True</serverOpen>
<onlinePlayers>24957</onlinePlayers>
</result>
<cachedUntil>2014-05-08 03:35:58</cachedUntil>
</eveapi>
The function - render_xml_to_html.php
<?php
function render_xml_data($path_to_xml_file){
if (!file_exists($path_to_xml_file)){
return;
}else{
$chars_to_replace = array('[\r]','[\n]','[\t]');
$xmlstring = trim(preg_replace($chars_to_replace, '', file_get_contents($path_to_xml_file)));
}
$xml = new SimpleXMLElement($xmlstring);
foreach ($xml->result as $record) {
echo '<div class="record">'."\n";
echo '<h3>'.$record->onlinePlayers.'</h3>'."\n";
echo '</div><!--end record-->'."\n";
}
}
?>
The above code works as is. My issue is when I try to pull this info from the realtime .xml file on the hosts server. That url is:
https://api.eveonline.com/server/ServerStatus.xml.aspx/
When I replace example.xml with the above link it fails to work. So the following doe not work. Where I link to an external path rather than a local.
<?php
include('render_xml_to_html.php');
// The external path DOES NOT WORK
render_xml_data('https://api.eveonline.com/server/ServerStatus.xml.aspx/');
?>
Thanks in advance!
You can just use file_get_contents on this one, it can get the job done. Consider this example:
$url = 'https://api.eveonline.com/server/ServerStatus.xml.aspx/';
// access the url and get that file
$contents = file_get_contents($url);
// convert it to an xml object
$contents = simplexml_load_string($contents);
echo "<div class='record'>Number of Online Players: ".$contents->result->onlinePlayers."</div>";
Sample Output:
Number of Online Players: 23893

Categories