I don't understand this:
I use the __autoload feature in php and this works:
include_once '../sys/core/init.inc.php';
$Intro = new Intro();
echo $Intro->ip();
exit();
init.inc.php loads the Intro class and the ip() function prints out the ip.
But this does not work
include_once '../sys/core/init.inc.php';
/*
* Smarty template engine
*/
include_once '../sys/core/smarty/Smarty.class.php';
$smarty = new Smarty;
$smarty->debugging = false;
$smarty->caching = false;
$smarty->cache_lifetime = 86400; // 24 timer
/*
* gettext translation
*/
if( ! defined('PROJECT_DIR')){ define('PROJECT_DIR', realpath('/var/www/v3/')); }
if( ! defined('LOCALE_DIR')){ define('LOCALE_DIR', PROJECT_DIR .'/sys/locale'); }
if( ! defined('DEFAULT_LOCALE')){ define('DEFAULT_LOCALE', 'no_NO'); }
include_once('../sys/core/gettext/gettext.inc');
$encoding = 'utf-8';
$locale = (isset($_COOKIE['lang']))? $_COOKIE['lang'] : DEFAULT_LOCALE;
T_setlocale(LC_MESSAGES, $locale);
$domain = 'messages';
T_bindtextdomain($domain, LOCALE_DIR);
T_bind_textdomain_codeset($domain, $encoding);
T_textdomain($domain);
/*
* facebook
*/
include_once '../sys/core/facebook/facebook.php';
// Create our Application instance (replace this with your appId and secret).
// Create our Application instance.
$facebook = new Facebook(array(
'appId' => 'xxx',
'secret' => 'xxx',
'cookie' => true,
));
$session = $facebook->getSession();
$me = null;
// Session based API call.
if ($session) {
try {
$uid = $facebook->getUser();
$me = $facebook->api('/me'); // me?fields=email
$email = $facebook->api('me?fields=email');
} catch (FacebookApiException $e) {
error_log($e);
}
}
// login or logout url will be needed depending on current user state.
if ($me) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl(
array('req_perms' => 'email, publish_stream')
);
}
$Intro = new Intro();
echo $Intro->ip();
exit();
Now I get Fatal error: Class 'Intro' not found in ... on line 92
I don't understand this because the only code I have added is required includes for facebook, gettext and smarty. Before the includes I can call classes, but not after I have added the includes. This makes no sense to be. Can someone explain.
Try to call your class directly after the include:
include_once '../sys/core/init.inc.php';
$Intro = new Intro();
/*
* Smarty template engine
*/
include_once '../sys/core/smarty/Smarty.class.php';
$smarty = new Smarty;
$smarty->debugging = false;
$smarty->caching = false;
$smarty->cache_lifetime = 86400; // 24 timer
/*
* gettext translation
*/
if( ! defined('PROJECT_DIR')){ define('PROJECT_DIR', realpath('/var/www/v3/')); }
if( ! defined('LOCALE_DIR')){ define('LOCALE_DIR', PROJECT_DIR .'/sys/locale'); }
if( ! defined('DEFAULT_LOCALE')){ define('DEFAULT_LOCALE', 'no_NO'); }
include_once('../sys/core/gettext/gettext.inc');
$encoding = 'utf-8';
$locale = (isset($_COOKIE['lang']))? $_COOKIE['lang'] : DEFAULT_LOCALE;
T_setlocale(LC_MESSAGES, $locale);
$domain = 'messages';
T_bindtextdomain($domain, LOCALE_DIR);
T_bind_textdomain_codeset($domain, $encoding);
T_textdomain($domain);
/*
* facebook
*/
include_once '../sys/core/facebook/facebook.php';
// Create our Application instance (replace this with your appId and secret).
// Create our Application instance.
$facebook = new Facebook(array(
'appId' => 'xxx',
'secret' => 'xxx',
'cookie' => true,
));
$session = $facebook->getSession();
$me = null;
// Session based API call.
if ($session) {
try {
$uid = $facebook->getUser();
$me = $facebook->api('/me'); // me?fields=email
$email = $facebook->api('me?fields=email');
} catch (FacebookApiException $e) {
error_log($e);
}
}
// login or logout url will be needed depending on current user state.
if ($me) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl(
array('req_perms' => 'email, publish_stream')
);
}
echo $Intro->ip();
exit();
Shouldn't work either, but may be a good start for debugging. However, it might be useful to post your Intro class.
This is a simple guess, i haven't really used these librairies (except for Smarty) in a while, but it might be that one of the libraries (Facebook or Gettext) also define a __autoload function that gets called instead of your own.
You can display what is used by PHP for autoloading by calling var_dump(spl_autoload_functions()).
Also, your autoload function might be using a constant or variable getting overwritten by the includes.
Related
I'm making an app on Facebook using WordPress and everything is fine, I'm on the front page of the app, but when I try to access a link to another page of my app in Mozilla Firefox shows a blank page and in Google Chrome stays on the front page.
Has anyone an idea of why this is happening? Has anyone encountered this behaviour?
My next code is used by me in the WordPress root index.php, not the front page index.php, to request permissions of the user before entering the app:
<?php
/**
* Front to the WordPress application. This file doesn't do anything, but loads
* wp-blog-header.php which does and tells WordPress to load the theme.
*
* #package WordPress
*/
/**
* Tells WordPress to load the WordPress theme and output it.
*
* #var bool
*/
session_start();
require 'src/facebook.php';
// LOGIN
$app_details = array('app_id' => 'secret',
'app_secret' => 'secret',
'page_link' => '//www.facebook.com/secret/'
);
$http = "http:";
if(isset($_SERVER['HTTPS']))
if (!empty($_SERVER['HTTPS'])) $http = "https:";
$facebook = new Facebook(array(
'appId' => $app_details['app_id'],
'secret' => $app_details['app_secret'],
'cookie' => true
));
$the_signed_request = $facebook->getSignedRequest();
if ($the_signed_request == null) {
header("Location: ".$http.$app_details['page_link']."app/".$app_details['app_id']);
}
if ( !isset($the_signed_request['user_id']) && !isset($the_signed_request['oauth_token']) ){
$loginUrl = $facebook->getLoginUrl(array('scope'=>'email'));
if (!isset($_SESSION['rejects'])) $_SESSION['refuzuri'] = 0;
else $_SESSION['rejects']++;
if ($_SESSION['rejects']>4) {
echo "This app works only if permissions are accepted.<br/>";
echo "To accept the permissions <a href='".$loginUrl."' target='_top'>click here</a>";
die();
}
echo( "<script>top.location.href='" . $loginUrl . "';</script>" );
}else{
try{
$access_token = $facebook->getAccessToken();
$user = $facebook->getUser();//userid
$userinfo = $facebook->api('/me?fields=id,name,email,gender,locale'); //for basic details
}catch (FacebookApiException $e) {
$user = null;
$userinfo = null;
}
$_SESSION['user']= $userinfo;
define('WP_USE_THEMES', true);
/** Loads the WordPress Environment and Template */
require( dirname( __FILE__ ) . '/wp-blog-header.php' );
}
?>
So far i have it set up to retrieve basic user info, nothing extended. Im trying to get the user email as well, with no success. Here's what i got:
$facebook = new Facebook(array(
'appId' => APP_ID,
'secret' => APP_SECRET,
'cookie' => true,
));
$session = $facebook->getSession();
if (!empty($session)) {
try {
$params = array(
'scope' => 'email',
'redirect_uri' => 'https://www.dormduels/splash_test'
);
$loginUrl = $facebook->getLoginUrl($params);
$uid = $facebook->getUser();
$access_token = $facebook->getAccessToken();
echo $access_token;
$user = $facebook->api('me?fields=name,first_name,last_name,username,email&access_token='.$access_token);
echo "<pre>";
print_r($user);
exit();
The problem is. the getAccessToken that its displaying, when tested in facebooks graph explorer, doesnt show extended data like email, only basic. How do i request a more permission enabled acces token?
On my side, i do it this way:
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => FB_API_KEY,
'secret' => FB_API_SECRET,
));
// Get User ID
$fb_user = $facebook->getUser();
// We may or may not have this data based on whether the user is logged in.
//
// If we have a $fb_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 ($fb_user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$fb_user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
$fb_user = null;
}
}
// Login or logout url will be needed depending on current user state.
if ($fb_user) {
$fb_loggedin = true;
} else {
$fb_loggedin = false;
$fb_loginUrl = $facebook->getLoginUrl(array(
'scope' => 'email,user_location',
'redirect_uri' => 'http://'.$_SERVER['HTTP_HOST'].'/debut_'.($lang == 'fr' ? 'fr' : 'eng').'.php'
));
}
The SCOPE in the getLoginUrl is what you want to look at, you can see all the different permissions on the developer site at:
https://developers.facebook.com/docs/authentication/permissions/
Good luck
You need to ask for extended permissions, namely "email" for here in one of the following ways:
php sdk
Use the getLoginUrl() method of the sdk object, and specify the extended permissions you need in the 'scope', and redirect the user to its return value, Also you need to add the domain and the site url in your facebook app's admin page. Here's an example:
define('APP_ID', 'TODO FILL IT WITH YOURS');
define('APP_SECRET', 'TODO FILL IT WITH YOURS');
require_once 'facebook.php';
function redirect_to_login($fb){
$login_url = $fb->getLoginUrl(array(
'scope' => 'email',
));
header('Location: '.$login_url);
exit;
}
$fb = new Facebook(array(
'appId' => APP_ID,
'secret' => APP_SECRET,
'cookie' => true,
));
$uid = $fb->getUser();
if (!$uid || !check_perms($fb, $uid, array('email'))) { // see check_perms below
// send users to login/auth page if they are not logged in,
// or not installed the app,
// or don't have all the perms we need
redirect_to_login($fb);
}
try {
$me = $fb->api('/me');
var_dump($me);
} catch (Exception $e) {
redirect_to_login($fb);
}
js sdk
Use the FB.login() function to ask for the extended permissions you need, in the second parameter.
For detailed information on the whole authentication process, see this page.
If you want to check if the current user has the all the permissions you want, you can use FQL like this:
function check_perms($facebook, $uid, $perms = array()) {
$perms_str = join(' = 1 and ', $perms).' = 1';
$query = "select uid from permissions where uid = '".$uid."' and ".$perms_str;
try {
$row = $facebook->api(array(
'method' => 'fql.query',
'query' => $query,
));
return $row && $row[0]['uid'] == $uid;
} catch (Exception $e) {
return false;
}
}
note:
Your php sdk version probably is outdated, the getSession() method have been deprecated in favor of getUser() / getAccessToken()
Try following:
$facebook = new Facebook(array(
'appId' => APP_ID,
'secret' => APP_SECRET,
'cookie' => true,
));
public function login() {
$loginUrl= $facebook->getLoginUrl(array('scope' => 'email',
'redirect_uri' => 'your redirectUri',
'display' => 'popup'
));
header("Location:$loginUrl");
}
public function fUserInfo() {
$access_token = $facebook->getAccessToken();
//check permissions list
$permissions_list = $facebook->api('/me/permissions', 'GET', array('access_token' => $access_token));
$permissions_needed = array('email');
foreach ($permissions_needed as $perm) {
if (!isset($permissions_list['data'][0][$perm]) || $permissions_list['data'][0][$perm] != 1) {
login();
}
}
$user = $facebook->getUser();
if ($user) {
try {
$userInfo = $facebook->api("/$user");
} catch (FacebookApiException $e) {
Config::getLogger()->debug($e->getMessage());
}
}
print_r($userInfo);
}
I tried in many ways.. i used php-sdk and in many other ways... but i am not able to connect my website with facebook... actually.. i am doing my project in codeigniter. Can anybody plz suggest me to connect to facebook login and share using codeigniter.
<?php
include "libs/facebook.php";
$facebook = new Facebook(array(
'appId' => '376406812408828',
'sec`enter code here`ret' => 'ca1eb65bde82a4009c31b4a5adb047b5',
'cookie' => true
));
print_r($facebook);
$session = $facebook->getUser();
echo $session;
$me=null;
if($session)
{
try
{
$me = $facebook->api('/me');
echo $me;
$facebook->api('/me/feed','post',array('message' => 'Hello World!'));
}
catch(FacebookApiException $e)
{
echo $e->getMessage();
}
}
if($me)
{
$logoutUrl = $facebook ->getLogoutUrl();
echo "Logout";
}
else
{
$loginUrl = $facebook ->getLoginUrl(array(
'req_perms' => 'publish_stream,read_friendlists'
));
echo "Login";
}
?>
Danny Tran has provided A Simple & Easy Facebook Library for CodeIgniter.
CI_Facebook is a Facebook Library for CodeIgniter.
Simply copy/merge all the files into the corresponding locations and
setup config/facebook.php.
There are unit tests written for each function/class. You will need
PHPUnit to execute them.
Accessing the Facebook object is easy since the hook is auto-loading
it.
e.g. $user_data = $this->facebook->fb->api_client->fql_query("select name from user where uid = TARGETUSERID");
Link to library on Github: https://github.com/dannybtran/CI_Facebook
Hope this helps.
A couple of weeks I had to do the same, and after and I came up with this. I needed it for an ajax login, but it mostly suits everyone needs.
This is the first step, it prompts the facebook login (if you are not already logged) and then redirect to your previously set uri.
$this->load->library('facebook_handler');
$this->facebook_handler->loginBegin($this->config->item('endpointfacebook'));
Facebook_handler in libraries folder
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Facebook_handler extends ML_index
{
var $scope = "email, user_about_me, user_birthday, user_hometown, user_website,read_stream, publish_stream, read_friendlists";
function __construct()
{ parent::__construct();
$this->CI =& get_instance();
$this->CI->config->load('mlogin_config'); //Config where I have the keys
if ( ! $this->CI->config->item('facebook_api_key') || ! $this->CI->config->item('facebook_api_key_secret') )
{
throw new Exception( "Your application id and secret are required in order to connect to {$this->providerId}.", 4 );
}
include_once(APPPATH.'libraries/Facebook/base_facebook.php'); //Place where I've situated the facebook libraries
include_once(APPPATH.'libraries/Facebook/facebook.php');
$this->fb = new Facebook( ARRAY( 'appId' => $this->CI->config->item('facebook_api_key'),'cookie'=>true, 'secret' => $this->CI->config->item('facebook_api_key_secret') ) );
$this->user = $this->fb->getUser();
}
/*The login process starts here, endpoint is the redirect_url for facebook*/
function loginBegin($endpoint)
{
$scope=$this->CI->config->item('facebook_scope');
if( isset( $scope ) && ! empty( $scope ) )
{
$this->scope = $scope;
}
$this->logout();
$url = $this->fb->getLoginUrl( array( 'domain'=>base_url(),'scope' => $this->scope, 'redirect_uri' => $endpoint,'display' => 'popup' ) );
redirect($url);
}
/*Function to get user data*/
function getUser(){
if ($this->user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $this->fb->api('/me');
return $user_profile;
} catch (FacebookApiException $e) {
error_log($e);
return false;
}
}else{
$this->output->set_output('no logueado');
}
}
/*Facebook logout, it destroys facebook sessions. I dont really use this*/
function logout(){
$this->fb->destroySession();
}
}
?>
The function to redirect to
function closewindowfacebook(){
$this->load->library('facebook_handler');
$userprofile=$this->facebook_handler->getUser();
if ($userprofile!=false){
$fb_uid = $this->facebook_handler->fb->getUser();
$fb_email=$userprofile['email'];
$fb_name=$userprofile['name'];
/*My function to connect to the website, that you'd do it yourself*/
//$this->auth->try_fb_login($fb_uid,$fb_email,$fb_name);
/*I use this to close the popup window*/
die('<script type="text/javascript">
window.opener.everythingready();
window.close();
</script>');
} else{
echo 'error ';
}
}
Ask if you have any further question
I have my own site which I am creating a blog/news entries but I want these to upload directly to my Facebook page as I add them.
Is there a simple way to do this?
My code is something like this
<?php
$title = "$_Post['title'];
$article = "$_Post['article'];
// Upload sql and query code code
?>
Is there a code or api I can use to also update to my facebook page
You will need to sign up to become a facebook developer, create an application, and then using the PHP SDK you can do exactly this.
Developers site: http://developers.facebook.com/
PHP SDK: http://developers.facebook.com/docs/reference/php/
Example code:
http://www.masteringapi.com/tutorials/how-to-post-on-facebook-page-as-page-not-as-admin-user-using-php-sdk/31/
<?php
// This code is just a snippet of the example.php script
// from the PHP-SDK <http://github.com/facebook/php-sdk/blob/master/examples/example.php>
require '../src/facebook.php';
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => 'app_id',
'secret' => 'app_secret',
));
// Get User ID
$user = $facebook->getUser();
if ($user) {
try {
$page_id = 'page_id';
$page_info = $facebook->api("/$page_id?fields=access_token");
if( !empty($page_info['access_token']) ) {
$args = array(
'access_token' => $page_info['access_token'],
'message' => "I'm a Page!"
);
$post_id = $facebook->api("/$page_id/feed","post",$args);
}
} 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(array('scope'=>'manage_pages,publish_stream'));
}
?>
I am trying to write a script that will post to my facebook page and I assume all I have to do is modify my code for posting to a users stream.
$attachment = array
(
...
);
$result = $facebook->api($user.'/feed/','post',$attachment);
What do I put instead of the user's id? I am not sure if it is simply my page's id. Any ideas?
Assuming that my facebook page means my feed you simply do
$user = 'me';
1. POST ON PAGE'S WALL AS USER:
Publishing on a Page's wall as user is straight forward, you could use something like:
<?php
// path to sdk
require './src/facebook.php';
$facebook = new Facebook(array(
'appId' => 'APP_ID',
'secret' => 'APP_SECRET',
));
$user = $facebook->getUser();
try {
$post_id = $facebook->api('/TARGET_PAGE_ID/feed', 'POST', array('message'=>"I am a user!"));
var_dump($post_id);
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl(array('scope'=>'publish_stream'));
}
// rest of code here
Note:
The owner of the post will be the current connected user.
the above depends on the page's Posting Ability settings.
you need the publish_stream permission
2. POST ON PAGE'S WALL AS PAGE:
Now to post as a Page you could use something like:
<?php
// This code is just a snippet of the example.php script
// from the PHP-SDK <http://github.com/facebook/php-sdk/blob/master/examples/example.php>
require '../src/facebook.php';
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => 'app_id',
'secret' => 'app_secret',
));
// Get User ID
$user = $facebook->getUser();
if ($user) {
try {
$page_id = 'TARGET_PAGE_ID';
$page_info = $facebook->api("/$page_id?fields=access_token");
if( !empty($page_info['access_token']) ) {
$args = array(
'access_token' => $page_info['access_token'],
'message' => "I'm a Page!"
);
$post_id = $facebook->api("/$page_id/feed","post",$args);
}
} 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(array('scope'=>'manage_pages,publish_stream'));
}
// rest of code
?>
Notes:
You need the manage_pages and publish_stream permissions
Once you obtain the page's access_token you can start posting on its behalf
More about this is explained in depth in my tutorial.