Given URL is not allowed - php

if someone can help please help it will be appreciated
actually i want to include facebook data in my website
and i am getting an error
Given URL is not allowed by the Application configuration.: One or more of the given URLs is not allowed by the App's settings. It must match the Website URL or Canvas URL, or the domain must be a subdomain of one of the App's domains
since i am new to php
what should be come in place of
api('/me');
$userdata = $facebook->api('/me');
please someone help me i am frustrated
here is the full code
<h1>Facebook SDK Login - Basic Information</h1>
<h4><a href='http://9lessons.info'>9lessons.info</a></h4>
<?php
include('lib/db.php');
require 'lib/facebook.php';
require 'lib/fbconfig.php';
// Connection...
$user = $facebook->getUser();
if ($user)
{
$logoutUrl = $facebook->getLogoutUrl();
try {
$userdata = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
$_SESSION['facebook']=$_SESSION;
$_SESSION['userdata'] = $userdata;
$_SESSION['logout'] = $logoutUrl;
header("Location: home.php");
}
else
{
$loginUrl = $facebook->getLoginUrl(array( 'scope' => 'email,user_birthday'));
echo '<img src="facebook.png" title="Login with Facebook" />';
}
?>
fblogin.php

Go to your Facebook App :-
1. click on "setting" tab(Basic)
App Domains = example.com
site url = http://example.com/
(Advanced) tab
Age Restriction = 13+
2. click on "Status & Review" tab
Do you want to make this app and all its live features available to the general public? = Yes
only these option is required for create an basic app.
You can check for full doc :- sourceaddons or developer facebook

I think you're missing some parameters the API wants. According to https://developers.facebook.com/docs/reference/php/facebook-api/ the API expects the following syntax:
$ret = $facebook->api($path, $method, $params);
So "/me" is the path, but the API does not know what you want to do.
Have a look at the examples like this one here that fetches the user's profile:
https://developers.facebook.com/docs/php/howto/profilewithgraphapi/4.0.0

Related

Facebook PHP SDK - api returns empty

I am trying to learn some facebook development because it seems people ask for facebook integration one way or another.
I am trying to get something as simple as my name to be echoed on screen using the PHP SDK and I cant seem to do it.
My code is extremely basic, just what's required for the
<?php
require_once('src/facebook.php');
$config = array(
'appId' => '14283923YYYYYYY48',
'secret' => 'XXXXXXXXXXXXXXXXXXXXXXXX',
'allowSignedRequest' => false
);
$facebook = new Facebook($config);
$user_id = $facebook->getUser();
?>
<html>
<head></head>
<body>
<?php
if($user_id) {
$user_profile = $facebook->api('/me','GET');
echo "Name: " . $user_profile['name'];
if (is_null($user_profile))
echo "NULL";
else echo "NOT NULL";
}
?>
</body>
</html>
The name does not show up, and as you can see I tested the $user_profile variable and it comes up NULL, so I assume that the api function doesn't work, doesn't return anything.
Is my code wrong? Or should I look elsewhere for the issue? Any tip or suggestion to solve the issue will be really helpful.
You need to provide a login facility to let the user explicitly allow use of their user ID, and create an access token. This can be done in the PHP SDK or JavaScript SDK (and can be both implemented for dual functionality).
Link:
https://developers.facebook.com/docs/facebook-login/
** Please also view the following: Facebook PHP SDK/Graph API - Returning MY name/info, but not anyone elses?
<?php
if($user_id) {
$user_profile = $facebook->api('/me','GET');
echo "Name: " . $user_profile['name'];
if (is_null($user_profile))
echo "NULL";
else echo "NOT NULL";
}
?>
change the partial section of code above
$user_profile = $facebook->api('/me','GET'); to
$user profile = $facebook->api($user_id, 'GET')
then you would able to get the user profile whose using facebook login in your website
Hope this is help
if you happened to work with a old project in codeigniter 3.x & deployed in aws ELB
in 2018 the facebook call back url mentioned in config or in fb app settings isn't enough,
with ssl, you need to manually edit base_facebook.php and replace redirect_uri from blank to your https url in the function getAccessTokenFromCode() argument,
protected function getAccessTokenFromCode($code, $redirect_uri = 'https://www.example.com/index/fblogin') {
if (empty($code)) {
return false;
}
.....

Facebook Login Doesn't Work

I am trying to add Facebook login to my web site.
What I have done?
Created APP on Facebook as Website with Facebook Login
Sandbox mode is off
APP is set to work on localhost.
What is the problem?
I keep getting $user variable's value as 0
example.php in Facebook PHP SDK works just fine!
I can see my APP when I visit Facebook -> Privacy Settings -> Apps. No matter if I login with my login.php or example.php of Facebook PHP SDK, the app seems to be added just the same. However while example.php can retrieve data from facebook, login.php can't.
I copy and paste the codes from example.php to my login.php page (please check the code below).
Here is my code (login.php);
require_once('system/api/facebook/facebook.php');
$facebook = new Facebook(array(
'appId' => '123456',
'secret' => 'abcde12345',
));
$user = $facebook->getUser();
if ($user) {
try {
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
// Login or logout url will be needed depending on current user state.
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl();
}
if (!$user) echo 'Login';
echo '<pre>';
var_dump($user);
echo '</pre>';
Can someone please tell me what is the difference between my login.php and example.php? I also Googled and searched here without finding any info which was helpful.

How does Facebook react when someone denies permission to a resource?

I'm using the below code for my app. If I deny the permission, I am still able to access the app, but it should not take me to app right?
Where am I going wrong?
//Facebook Authentication part
$user = $facebook->getUser();
$loginUrl = $facebook->getLoginUrl(
array(
'scope' => 'publish_stream,read_stream',
)
);
$me = null;
// Session based API call.
if ($session) {
try {
$uid = $facebook->getUser();
$me = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
}
}
if (!$user) {
echo "<script type='text/javascript'>top.location.href = '$loginUrl';</script>";
exit;
}
I am not sure this will give you the answer you are looking for. But I just wonder if you are aware of the expected authentication flow of a Facebook application.
When the "Don't Allow" is selected then the Facebook dialog box will redirect to:
http://YOUR_URL?error_reason=user_denied&
error=access_denied&error_description=The+user+denied+your+request.
Where YOUR_URL is the redirect_uri paramater that was specified in the oauth dialog URL.
Check out Facebook Authentication Docs
I think if you click on Dont Allow button it will take you to the app page, but if you handled the don't allow action in your code then you can redirect it to anywhere you want

Facebook Like button using PHP

My knowledge of Facebook's PHP SDK is limited at this point but is it possible to use their PHP SDK to create a text link version of their 'Like' button?
No, I'm afraid this is not possible.
I am currently using the Like button as well as the like box on our Website but the JS SDK has a kind of high execution time and takes a while to load and thus I am currently looking for a proper way to avoid the JS SDK.
The Like button can - more or less - be replaced with the Graph API whereas the like box can't.
To set a like for an object (website, photo, link, whatever) you can simply call the graph api with the method=post Parameter.
<?php
require_once("facebook.php"); //from the FB SDK
$config = array();
$config['appId'] = 'your_app_id';
$config['secret'] = 'your_app_secret';
$facebook = new Facebook($config);
$user = $facebook->getUser();
if(!$user){
$loginUrl = $facebook->getLoginUrl(array('scope'=>'publish_stream, user_likes', 'redirect_uri'=>'www.example.com'));
}
if($user){
try{
$user_profile = $facebook->api('/me');
$access_token = $facebook->getAccessToken();
$access_token = $facebook->getAccessToken();
$attend = "https://graph.facebook.com/www.example.com/like?method=post&access_token=".$access_token;
file($attend);
}
catch(FacebookApiException $e){
error_log($e);
$user = NULL;
}
}
else{
echo 'Please login via Facebook';
}
?>
You'll need an FB Application though, as you have to specify the app_id and app_secret for the PHP SDK, which you don't have to when you are using just the like button.
There's a /likes graph API object that the docs say you can write to with the proper permissions. I've never tried it though.

Why is Facebook PHP SDK getUser always returning 0?

I'm trying to work with a website that requires some information from a Facebook user, I'm using PHP and JS SDKs.
I have a function in PHP:
public function isLoggedOnFacebook() {
$user = $this->_facebook->getUser();
if ($user) {
return $this->_facebook->api("/$user");
}
return false;
}
On a class that is holding the facebook object from the SDK in $this->_facebook.
Then on a block I do this:
<?php if (!$this->isLoggedOnFacebook()): ?>
<div>
<fb:login-button show-faces="true" perms="email" width="500" />
</div>
<?php endif ?>
And the FB JS environment is properly set up (I think) so it works. So the user gets the pop up and authorizes the site.
The problem is even after the app is been authorized by the user $user is always 0, meaning $facebook->getUser() always returns 0, and then lists the faces of users, including the logged user, but if I make it call $facebook->api('/me') or whatever, then it'll throw the invalid token exception.
I've seen this problem, but I haven't seen a solution, I have no idea
where the problem is and I run out of ideas.
There's a Website tab on the developers' Facebook page in the apps section, where you can set up your Site URL and your Site Domain, and I'm thinking this are the cause of my problem, but I have no knowledge of exactly what these fields are supposed to contain.
I had the same problem and I figured it out that is because SDK uses the variable $_REQUEST and in my environment is not true that is merged with $_GET, $_POST and $_COOKIE variables.
I think it depends on the PHP version and that is why someone made it work by enabling cookies.
I found this code in base_facebook.php:
protected function getCode() {
if (isset($_REQUEST['code'])) {
if ($this->state !== null &&
isset($_REQUEST['state']) &&
$this->state === $_REQUEST['state']) {
// CSRF state has done its job, so clear it
$this->state = null;
$this->clearPersistentData('state');
return $_REQUEST['code'];
} else {
self::errorLog('CSRF state token does not match one provided.');
return false;
}
}
return false;
}
And I modified it as you can see below by creating $server_info variable.
protected function getCode() {
$server_info = array_merge($_GET, $_POST, $_COOKIE);
if (isset($server_info['code'])) {
if ($this->state !== null &&
isset($server_info['state']) &&
$this->state === $server_info['state']) {
// CSRF state has done its job, so clear it
$this->state = null;
$this->clearPersistentData('state');
return $server_info['code'];
} else {
self::errorLog('CSRF state token does not match one provided.');
return false;
}
}
return false;
}
I ran into similar problem. $facebook->getUser() was returning 0 and sometimes it returned valid user id when user wasn't actually logged in, resulting in Fatal Oauth error when I tried to make graph api calls. I finally solved this problem. I don't know if it is the right way but it works. Here is the code :
<?php
include 'includes/php/facebook.php';
$app_id = "APP_ID";
$app_secret = "SECRET_KEY";
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret,
'cookie' => true
));
$user = $facebook->getUser();
if ($user <> '0' && $user <> '') { /*if valid user id i.e. neither 0 nor blank nor null*/
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) { /*sometimes it shows user id even if user in not logged in and it results in Oauth exception. In this case we will set it back to 0.*/
error_log($e);
$user = '0';
}
}
if ($user <> '0' && $user <> '') { /*So now we will have a valid user id with a valid oauth access token and so the code will work fine.*/
echo "UserId : " . $user;
$params = array( 'next' => 'http://www.anujkumar.com' );
echo "<p><a href='". $facebook->getLogoutUrl($params) . "'>Logout</a>";
$user_profile = $facebook->api('/me');
echo "<p>Name : " . $user_profile['name'];
echo "<p>";
print_r($user_profile);
} else {/*If user id isn't present just redirect it to login url*/
header("Location:{$facebook->getLoginUrl(array('req_perms' => 'email,offline_access'))}");
}
?>
Check out this blog post: http://thinkdiff.net/facebook/new-javascript-sdk-oauth-2-0-based-fbconnect-tutorial/
New JS SDK has been released - https://developers.facebook.com/blog/post/525
You need to ensure that your app is set to pick up the code parameter from the Query String rather than the uri_fragment, this can be set on facebook apps page apps>settings>permissions.
That did it for me using $facebook->getLoginUrl() to provide the login URL.
Check your config array.
Ensure that you are using proper string encaps quotes when setting the values.
$config = array();
$config["appId"] = $APP_ID;
$config["secret"] = $APP_SECRET;
$config["fileUpload"] = false; // optional
This works.
$config = array();
$config[‘appId’] = 'YOUR_APP_ID';
$config[‘secret’] = 'YOUR_APP_SECRET';
$config[‘fileUpload’] = false; // optional
This is a direct copy/paste from the website http://developers.facebook.com/docs/reference/php/ and does NOT work because of the odd squiggly quotes.
the long answer is that your hash for your "checking" of the app signature is not coming out to a correct check, because the app secret is not returning a valid value (it's returning nothing, actually)... so the hash_hmac function is returning an incorrect value that doesn't match properly, etc...
After debugging through the base_facebook.php I found, because somehow I had lost my .crt file the access token is forever invalid. Make sure you have your fb_ca_chain_bundle.crt available at: https://github.com/facebook/facebook-php-sdk/blob/master/src/fb_ca_chain_bundle.crt
Hours and hours down the drain. None of the posts about this on Stack Overflow or other sites provided the solution to my problem. I finally went in to the library code and figured out exactly where it was dying.
On my development machine, which uses XAMPP for Windows, I kept getting the 0 for logging in, while my test server would work properly. After realizing an exception was being thrown but hidden, I put an $e->getMessage() in base_facebook.php, which pointed out I was having an SSL error. The following post, HTTPS and SSL3_GET_SERVER_CERTIFICATE:certificate verify failed, CA is OK, led me to a solution.
The solution:
In base_facebook.php, add the following before curl_exec($ch):
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
You should probably wrap the above in whatever flags you use to determine if you are in development mode, because you won't want the above line in a production system. For instance:
if ( getenv( 'environment' ) === 'development' ) {
curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false );
}
I checked and test a long time, Now I found the reason.
Please login developer apps, in settings-->Advance-->Migrations-->Deprecate offline access-->disabled.
You will find $facebook->getUser() will work.
another thing. had better add domain when new the facebook class;
$facebook = new Facebook(array(
'appId' => APP_ID,//$app_id,
'secret' => APP_SECRET,//$app_secret,
'cookie' => true,
'domain'=>'xxxdomain.com',
));
$session = $facebook->getUser();
Try this in your piece of code:
on if condition true you'll be reirected to facebook then login yourself and i hope you'll good to go by then but remember use new libraries of php SDK
if(($facebook->getUser())==0)
{
header("Location:{$facebook->getLoginUrl(array('scope' => 'photo_upload,user_status,publish_stream,user_photos,manage_pages'))}");
exit;
}
else {
$accounts_list = $facebook->api('/me/accounts');
echo "i am connected";
}
i solved this as i faced the same problem.
Just goto developers.facebook.com/apps then navigate to your app
hit EDIT APP button
IF you have check "App on facebook" and have entered a canvas url to it
the app will not work out side the facebook
will work under apps.facebook.com/
just remove this check it worked for me
<?php
require 'facebook.php';
// Create our application instance
// (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => 'YOUR_APP_ID',
'secret' => 'YOUR_APP_SECRET',
));
// Get User ID
$user = $facebook->getUser();
// We may or may not have this data based
// on whether the user is logged in.
// If we have a $user id here, it means we know
// the user is logged into
// Facebook, but we don’t know if the access token is valid. An access
// token is invalid if the user logged out of Facebook.
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
// Login or logout url will be needed depending on current user state.
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl();
}
// This call will always work since we are fetching public data.
$naitik = $facebook->api('/naitik');
?>
<!doctype html>
<html xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
<title>php-sdk</title>
<style>
body {
font-family: 'Lucida Grande', Verdana, Arial, sans-serif;
}
h1 a {
text-decoration: none;
color: #3b5998;
}
h1 a:hover {
text-decoration: underline;
}
</style>
</head>
<body>
<h1>php-sdk</h1>
<?php if ($user): ?>
Logout
<?php else: ?>
<div>
Login using OAuth 2.0 handled by the PHP SDK:
Login with Facebook
</div>
<?php endif ?>
<h3>PHP Session</h3>
<pre><?php print_r($_SESSION); ?></pre>
<?php if ($user): ?>
<h3>You</h3>
<img src="https://graph.facebook.com/<?php echo $user; ?>/picture">
<h3>Your User Object (/me)</h3>
<pre><?php print_r($user_profile); ?></pre>
<?php else: ?>
<strong><em>You are not Connected.</em></strong>
<?php endif ?>
<h3>Public profile of Naitik</h3>
<img src="https://graph.facebook.com/naitik/picture">
<?php echo $naitik['name']; ?>
</body>
</html>
$facebook->getUser() will return 0, if the user doesn't authenticate the app.
use $facebook->getLoginUrl to get the URL to authenticate the app.
I was having the exact same problem on my Facebook app, and I finally figured it out after 2 days of hair pulling frustration. It turned out to be an issue with the redirect-uri in the getLoginUrl()! if it doesn't match the registered app domain through facebook, they return the error, and the user gets returned as 0 (the default user value).
I had same problem with getUser(), It returns 0 in IE 8. I found a solution after doing some research. Follow the link below. This worked like a charm.
http://www.andugo.com/facebook-php-sdk-getuser-return-0-value-on-ie/
After some desperate hours, here is what caused the same issue on my server: If you use SSL, make sure that port 443 is not blocked! I opened the port last year, but it appeared that my webhoster somehow did a reset recently.
If you use the new SDK 3.1.1 and JS you need to add new variable to FB.init routine called
oauth : true
to use the new OATH 2.0 Protocol !
Then update your login button while perms are not allowed please use scope instead of perms
getUser() and PHP-SDK silently fails if _REQUEST like globals dropping by http server by misconfiguration. I was using wrong-configured nginx and after tracing code ~3 hours solved this problem via vhost configuration change.
I wrote a comment about solution here: https://github.com/facebook/php-sdk/issues/418#issuecomment-2193699
I hope helps.
A facebook->getUser() will return 0 when there is no logged-in user. (https://developers.facebook.com/docs/reference/php/facebook-getUser/)
To resolve this, the Facebook JS SDK provides an access token from a successful login which you can use with the Facebook PHP SDK.
The javascript below will check whether or not a Facebook login already exists and your Facebook App is authorized:
FB.getLoginStatus(function($response) {
if ($response.status === 'connected') {
var uid = $response.authResponse.userID;
var accessToken = $response.authResponse.accessToken;
_accessServer(uid, accessToken);
} else if ($response.status === 'not_authorized') {
_loginPopup();
} else {
_loginPopup();
}
});
The function _accessServer opens another request back to your server, sending the access token.
The function _loginPopup should open the Facebook login popup requesting the appropriate permissions for the user to "allow access" to your application.
The PHP application should then pass the access token back to the Facebook API:
$facebook->setAccessToken($new_access_token);
$uid = $facebook->getUser();
https://developers.facebook.com/docs/reference/php/facebook-setAccessToken/
Hope that helps.
Adding this line solved this problem for me in IE9:
header('P3P:CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT"'); // This is the main cause to use on IE.
If this question is still relevant to people, I'd like to contribute my 2 cents as I struggled quite some time to get things working.
First of all, try out the SDK that would suit you, whether it be PHP or JS. In essence they both do the same stuff, it's just that JS might handle it a bit more elegant (with the pop-up dialog and what not). There's a lot of different tutorials, manuals and examples out there! It took me like a week to find 1 that suited me and that I could actually use. Once you've found the piece of code that works with the SDK you plan on using, it's time for you to alter the code to your specific needs.
Once I had finished my code, I started testing it. I noticed I was running my code on localhost, and I too was getting no result from my arrays. To answer your question: upload your code to a (sub)domain and try again. My code worked all the time, but because I did not have it online, it didn't work. If you already got it online, then my answer is not of use to you.
I'm sorry if this kind of small story isn't really meant to be on SO, but it might help people.
Good luck!
if ($facebook->getUser()) {
$userProfile = $facebook->api('/me');
// do logic
} else {
$loginUrl = $facebook->getLoginUrl($params = array('scope' => SCOPE));
header('Location:' . $loginUrl);
}
that how i fixed my problem, now it is returning me the detail of user profile for further processing. (it was such a headache)
These are good suggestions but the thing that worked for me is on Facebook itself. After refactoring the code many times I realized it's a problem with the configurations on Facebook.
The following steps resolved my issue.
1.) Under Basic > App on Facebook... I deselected that although you can leave it if you want
2.) Under Permissions > Privacy -> set to Public
Permissions > Auth Token -> set to Query String
3.) Under Advanced -> Authentication > App Type -> Web
The third step is the one that really fixed it all, not completely sure why though, hope that helps
Make sure you call this Facebook API-function getUser before any output, because it uses Session variables and Cookies. Headers can not be sent/read correctly if you did.
I also spent many hours looking at this and also found a solution. Might not be for you but it seems there is some issue with $_SERVER['QUERY_STRING'] so you need to set it into the $_REQUEST array.
I was using codeigniter and found that the following code above the library load worked.
parse_str($_SERVER['QUERY_STRING'],$_REQUEST);
parse_str($_SERVER['QUERY_STRING'],$_REQUEST);
$config = array();
$config["appId"] = "63xxxxx39";
$config["secret"] = "dexxxx3bf";
$this->load->library('facebook',$config);
$this->user = $user = $this->facebook->getUser();
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $this->facebook->api('/me');
//print_r($user_profile);exit;
} catch (FacebookApiException $e) {
echo '<pre>'.htmlspecialchars(print_r($e, true)).'</pre>';
$user = null;
}
$logout = $this->facebook->getLogoutUrl();
$this->fb_logout = $logout;
$this->fb_user = $user_profile;
} else {
$login = $this->facebook->getLoginUrl(array("scope"=>"email","redirect_uri"=>"http://domain/login/login_fbmember/"));
$this->fb_login = $login;
}
}
This issue is really weird. I have discovered that the problem was the static $CURL_OPTS array in the base_facebook.php.
Try to edit it from this:
/**
* Default options for curl.
*
* #var array
*/
public static $CURL_OPTS = array(
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 60,
CURLOPT_USERAGENT => 'facebook-php-3.2',
);
to
/**
* Default options for curl.
*
* #var array
*/
public static $CURL_OPTS = array(
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 60,
CURLOPT_USERAGENT => 'facebook-php-3.2',
CURLOPT_IPRESOLVE => CURL_IPRESOLVE_V4
);
The answer to my specific issue was that there were incompatibilities between the versions of the JS SDK and PHP SDK I was using and just upgrading them solved it.
The symptom of this issue is similar when it's caused by a variety of different things so you may do very well in scouting through the different answers available in this page.

Categories