facebook php sdk $sess returns null? - session

** My problem is I cant login with facebook using facebook php sdk v4 to my website through domain but when I try it on my localhost it works perfectly fine. What could be the problem?**
This is my index.php
<?php include'facebook/fbconnect.php';?>
<?php
require 'connection/connect.inc.php';
require 'connection/core.inc.php';
if(isset($_GET['username'])&&isset($_GET['password'])){
$user=$_GET['username'];
$pass=$_GET['password'];
$query="select Acc_Id from account where Acc_Status_Id=1 and BINARY Acc_Domain_Id=4 and Acc_Username='".$user."' and BINARY Acc_Password='".$pass."' and Acc_Type_Id=1";
if($query_run=mysql_query($query)or die(mysql_error())){
$mysql_rows=mysql_num_rows($query_run);
if($mysql_rows==1){
$user_id = mysql_result($query_run, 0, 'Acc_Id');
$_SESSION['acc_id']=$user_id;
header('Location:index.php');
}else{
?>
<script type="text/javascript">
alert("Invalid Data !");
history.back();
</script>
<?php
}
}
}
use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
use Facebook\FacebookResponse;
use Facebook\FacebookSDKException;
use Facebook\FacebookRequestException;
use Facebook\FacebookAuthorizationException;
use Facebook\GraphObject;
use Facebook\GraphUser;
use Facebook\GraphSessionInfo;
use Facebook\FacebookHttpable;
use Facebook\FacebookCurlHttpClient;
use Facebook\FacebookCurl;
if(isset($sess)){
//store the token in the php session
$_SESSION['fb_token']=$sess->getToken();
//create request object,execute and capture response
$request = new FacebookRequest($sess,'GET','/me');
// from response get graph object
$response = $request->execute();
$graph = $response->getGraphObject(GraphUser::classname());
// use graph object methods to get user details
$name = $graph->getName();
$id = $graph->getId();
$image = 'https://graph.facebook.com/'.$id.'/picture?width=300';
$email = $graph->getProperty('email');
//db check for fb.
$query="select Acc_Id from account where Acc_Status_Id=1 and BINARY Acc_Domain_Id=1 and Acc_Username='$id' and Acc_Type_Id=1";
if($query_run1=mysql_query($query)or die(mysql_error())){
$mysql_rows1=mysql_num_rows($query_run1);
if($mysql_rows1==1){
$user_id1 = mysql_result($query_run1, 0, 'Acc_Id');
$_SESSION['acc_id']=$user_id1;
}else{
$ins="insert into account (Acc_Username,Acc_Name,Acc_Email,Acc_Type_Id,Acc_Status_Id,Acc_Domain_Id)values('$id','$name','$email',1,1,1)";
//echo $ins;
mysql_query($ins)or die(mysql_error());
$user_id = mysql_insert_id();
$_SESSION['acc_id']=$user_id;
}
}
include 'home_1.php';
}else{
if(loggedin()){
include 'home_1.php';
}else{
include 'home_1G.php';
}
}
?>
This is my fbconnect.php
<?php
require_once( 'lib/Facebook/FacebookSession.php');
require_once( 'lib/Facebook/FacebookRequest.php' );
require_once( 'lib/Facebook/FacebookResponse.php' );
require_once( 'lib/Facebook/FacebookSDKException.php' );
require_once( 'lib/Facebook/FacebookRequestException.php' );
require_once( 'lib/Facebook/FacebookRedirectLoginHelper.php');
require_once( 'lib/Facebook/FacebookAuthorizationException.php' );
require_once( 'lib/Facebook/GraphObject.php' );
require_once( 'lib/Facebook/GraphUser.php' );
require_once( 'lib/Facebook/GraphSessionInfo.php' );
require_once( 'lib/Facebook/Entities/AccessToken.php');
require_once( 'lib/Facebook/HttpClients/FacebookCurl.php' );
require_once( 'lib/Facebook/HttpClients/FacebookHttpable.php');
require_once( 'lib/Facebook/HttpClients/FacebookCurlHttpClient.php');
/* USE NAMESPACES */
use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
use Facebook\FacebookResponse;
use Facebook\FacebookSDKException;
use Facebook\FacebookRequestException;
use Facebook\FacebookAuthorizationException;
use Facebook\GraphObject;
use Facebook\GraphUser;
use Facebook\GraphSessionInfo;
use Facebook\FacebookHttpable;
use Facebook\FacebookCurlHttpClient;
use Facebook\FacebookCurl;
/PROCESS/
//1.Stat Session
session_start();
//check if users wants to logout
if(isset($_REQUEST['logout'])){
unset($_SESSION['fb_token']);
}
//2.Use app id,secret and redirect url
$app_id = '**';
$app_secret = '**';
$redirect_url='**';
//3.Initialize application, create helper object and get fb sess
FacebookSession::setDefaultApplication($app_id,$app_secret);
$helper = new FacebookRedirectLoginHelper($redirect_url);
$sess = $helper->getSessionFromRedirect();
//check if facebook session exists
if(isset($_SESSION['fb_token'])){
$sess = new FacebookSession($_SESSION['fb_token']);
} ?>
I'm sure I made the app_id secret and even the url right.

We had a similar problem recently. Local and beta servers worked but our production server did not.
The problem, V4 requires PHP version 5.4 or higher.
https://developers.facebook.com/docs/php/gettingstarted/4.0.0
Might not be your problem but sounds really like ours. Hope it helps.

Related

Codeigniter Facebook Config File not loading

I have this code to start using Facebook SDK V4 with Codeigniter. This is the Facebook.php file inside Library Folder next to Facebook SDK folder files:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
if ( session_status() == PHP_SESSION_NONE ) {
session_start();
}
define('FACEBOOK_SDK_V4_SRC_DIR', APPPATH . 'libraries/facebook/Facebook');
require_once("autoload.php");
require_once( 'Facebook/FacebookSession.php' );
require_once( 'Facebook/FacebookRedirectLoginHelper.php' );
require_once( 'Facebook/FacebookRequest.php' );
require_once( 'Facebook/FacebookResponse.php' );
require_once( 'Facebook/FacebookSDKException.php' );
require_once( 'Facebook/FacebookRequestException.php' );
require_once( 'Facebook/FacebookAuthorizationException.php' );
require_once( 'Facebook/GraphObject.php' );
require_once( 'Facebook/Entities/AccessToken.php' );
require_once( 'Facebook/HttpClients/FacebookHttpable.php' );
require_once( 'Facebook/HttpClients/FacebookCurlHttpClient.php' );
require_once( 'Facebook/HttpClients/FacebookCurl.php' );
use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
use Facebook\FacebookResponse;
use Facebook\FacebookSDKException;
use Facebook\FacebookRequestException;
use Facebook\FacebookAuthorizationException;
use Facebook\GraphObject;
use Facebook\Entities\AccessToken;
use Facebook\HttpClients\FacebookHttpable;
use Facebook\HttpClients\FacebookCurlHttpClient;
use Facebook\HttpClients\FacebookCurl;
class Facebook {
var $ci;
var $helper;
var $session;
var $permissions;
public function __construct() {
$this->ci =& get_instance();
$this->permissions = $this->ci->config->item('permissions', 'facebook');
echo $this->ci->config->item('api_id', 'facebook');
exit;
I am having some errors and found that the problem was the config variables are not loading.
My config file is like this:
<?php
$config['facebook']['api_id'] = 'api-id-key';
$config['facebook']['app_secret'] = 'app-secret-key';
$config['facebook']['redirect_url'] = 'http://neuronr.com/facebook/redirect';
$config['facebook']['permissions'] = array(
'email',
'user_location',
'user_birthday'
);
What am I doing wrong with the config files? I've read documentation and all seems correct to me.
Thanks for any help :)
Now my code worked. Just one line added:
$this->ci->load->config('facebook'); // this is the line that I added
Thanks for the inspiration :)

Joomla 3.3 session and securimage captcha

I am building a form for my module and the final step is to pass a captcha check for security. I have downloaded the latest version of securimage. The captcha displays correctly and new captchas can be generated. However, after the form is posted, the advised technique on checking that the captcha was entered correctly never returns true.
index.php:
<form method="post" action="tmpl/form/contact.php" name="contactform" id="contactform">
<img id="captcha" src="securimage/securimage_show.php" alt="CAPTCHA Image" />
<a style="text-decoration: none; font-size: 10px; margin-top: -10px; " href="#" onclick="document.getElementById('captcha').src = '/securimage/securimage_show.php?' + Math.random(); return false">Refresh</a>
/**input here **/ name="captcha_code"
contact.php:
define( '_JEXEC', 1 )`;
define( 'JPATH_BASE', realpath(dirname(__FILE__))."/../../../..");
define( 'DS', DIRECTORY_SEPARATOR );
require_once ( JPATH_BASE .DS.'includes'.DS.'defines.php' );
require_once ( JPATH_BASE .DS.'includes'.DS.'framework.php' );
$mainframe = JFactory::getApplication('site');
$mainframe->initialise();
$user = JFactory::getUser();
$session = JFactory::getSession();
jimport( 'joomla.application.module.helper' );
$db = JFactory::getDBO();
$db->setQuery("SELECT params FROM #__modules WHERE module = 'module'");
$module = $db->loadObject();
$moduleParams = new JRegistry();
$moduleParams->loadString($module->params);
include_once $_SERVER['DOCUMENT_ROOT'] . 'securimage/securimage.php';
$securimage = new Securimage();
if ($securimage->check($_POST['captcha_code']) == false) {
echo '<div class="error_message">' . $errorcaptchainvalid . '</div>';
exit;
}
After searching for what the problem might be, I found this possibility from http://www.phpcaptcha.org/faq/:
If the variable names are the same this may be due to a problem with
the PHP session that is used to keep track of the user and what their
code is. It is possible that the session was not started or more
likely that the session name being used in securimage_show.php differs
from the session name used in the script that does the code
validation. It is common for other software platforms (forums, content
management systems, form processors etc.) to use a session name other
than the PHP default. If this is the case, you must determine what
session name is used by the software and use the same session name in
securimage_show.php and securimage_play.php.
A non-default session name can be passed to Securimage so it can share
a session with another software platform with the following code:
$img->session_name = 'your_session_name';
This would explain why I'm having no luck with my captcha. I have tried editing the above files but I don't know how sessions are set up in Joomla! or how to get around this problem. Is the problem likely to be the session variables?
securimage_show.php:
require_once dirname(__FILE__) . '/securimage.php';
$img = new Securimage();
if (!empty($_GET['namespace'])) $img->setNamespace($_GET['namespace']);
$img->show();
securimage_play.php
require_once dirname(__FILE__) . '/securimage.php';
$options = array(
'use_database' => true,
'database_name' => '',
'database_user' => '',
'database_driver' => Securimage::SI_DRIVER_MYSQL
);
$img = new Securimage();
if (!empty($_GET['namespace'])) $img->setNamespace($_GET['namespace']);
$img->outputAudioFile();
Your halfway there - the problem is the way Joomla handles sessions. Instead of placing the form in an article, try embedding form through an iframe and it should work fine.

Joomla 2.5 render com_content component output

is it possible to render Joomla content from external script? For example I have some html string, which I want to pass to com_content component, to make all content plugin and module features available. I think I should use JDocumentRendererComponent class. Code in my external file:
<?php
require_once ('framework.php'); //loading joomla framework
jimport('joomla.document.html.renderer.component');
$contentHtml = '<p>Some content html</p>';
echo JDocumentRendererComponent::render('com_content',array(),$contentHtml);
?>
What I get is error on the last line:
Fatal error: Class 'JDocumentRendererComponent' not found...
What Im doing wrong? Any ideas?
It's because you haven't included the Joomla framework to the external script. Use the below code. This will ensure that the Joomla! environment is loaded correctly
/* Initialize Joomla framework */
define( '_JEXEC', 1 );
define('JPATH_BASE', dirname(__FILE__) );
define( 'DS', DIRECTORY_SEPARATOR );
/* Required Files */
require_once ( JPATH_BASE .DS.'includes'.DS.'defines.php' );
require_once ( JPATH_BASE .DS.'includes'.DS.'framework.php' );
/* To use Joomla's Database Class */
require_once ( JPATH_BASE .DS.'libraries'.DS.'joomla'.DS.'factory.php' );
/**************************************************/
// Your code starts here...
// Remember that the Site application isn't running, so you cannot access $mainframe or any of its methods.
/**************************************************/
JDocumentRendererComponent Class is located in located in /libraries/joomla/document/html/renderer/component.php if you correct load the framework everything should work fine.
I found other solution for my question. The job can be also done by content plugin events (triggers). The piece of code from components/com_content/views/article/view.html.php:
JPluginHelper::importPlugin('content');
$results = $dispatcher->trigger('onContentPrepare', array ('com_content.article', &$item, &$this->params, $offset));
$item->event = new stdClass();
$results = $dispatcher->trigger('onContentAfterTitle', array('com_content.article', &$item, &$this->params, $offset));
$item->event->afterDisplayTitle = trim(implode("\n", $results));
$results = $dispatcher->trigger('onContentBeforeDisplay', array('com_content.article', &$item, &$this->params, $offset));
$item->event->beforeDisplayContent = trim(implode("\n", $results));
$results = $dispatcher->trigger('onContentAfterDisplay', array('com_content.article', &$item, &$this->params, $offset));
$item->event->afterDisplayContent = trim(implode("\n", $results));
So we can actually make an object from our string and pass it to these triggers. As a result we are getting content rendered like an article, with its major functionality.
Some more info about it:
http://www.inmotionhosting.com/support/edu/joomla-25/create-plugin/content-plugin-events
https://groups.google.com/forum/#!msg/joomla-dev-cms/VZVurjiZWIs/9Vr45KS2LTMJ

Joomla 2.5 Get User Data from External Script

I need to get the information of the user that's currently logged in to Joomla from a program outside of Joomla itself. I upgraded from 1.5 to 2.5, and what I had before doesn't work anymore.
<?php
define( '_VALID_MOS', 1 );
include_once( 'globals.php' );
require_once( 'configuration.php' );
require_once( 'includes/joomla.php' );
$option="test";
$mainframe = new mosMainFrame( $database, $option, '.' );
$mainframe->initSession();
$my = $mainframe->getUser();
$joomla_name = $my->name;
$joomla_email = $my->email;
$joomla_password = $my->password;
After some research, I've come up with this:
<?php
define( '_JEXEC', 1 );
define( 'JPATH_BASE', dirname(__FILE__) );
define( 'DS', '/' );
require_once ( JPATH_BASE .DS.'configuration.php' );
require_once ( JPATH_BASE .DS.'includes'.DS.'defines.php' );
require_once ( JPATH_BASE .DS.'includes'.DS.'framework.php' );
require_once ( JPATH_BASE .DS.'libraries'.DS.'joomla'.DS.'factory.php' );
$my =& JFactory::getUser();
$joomla_name = $my->name;
$joomla_email = $my->email;
$joomla_password = $my->password;
$joomla_username = $my->username;
It doesn't produce any errors but seems to work. However, the user object is empty. This script is in the same directory as the Joomla installation. What may be the problem? Thanks!
Sources:
http://www.cmsbloke.com/accessing-joomla-objects-from-an-external-script/
Taken from
http://docs.joomla.org/How_to_access_session_variables_set_by_an_external_script
Solution: Replace session_start(); in your external script with
define( '_JEXEC', 1 );
define( 'JPATH_BASE', realpath(dirname(__FILE__).'/../..' ));
define( 'DS', DIRECTORY_SEPARATOR );
require_once ( JPATH_BASE .DS.'includes'.DS.'defines.php' );
require_once ( JPATH_BASE .DS.'includes'.DS.'framework.php' );
$mainframe =& JFactory::getApplication('site');
$mainframe->initialise();
Be sure to change JPATH_BASE to suit your directory structure.
Replace the $_SESSION[ 'name' ] = "value"; in your external script with
$session =& JFactory::getSession();
$session->set('name', "value");
Now you can retrieve this session variable using:
$session =& JFactory::getSession();
echo $session->get('name');
It turns out, I had two problems:
My script was on www.example.com, while I was logged in under example.com, so the different domain was throwing off the session data.
I also wasn't initialising the application, which apparently is necessary.
Here are the results:
<?php
define( '_JEXEC', 1 );
define( 'JPATH_BASE', dirname(__FILE__) );
define( 'DS', '/' );
require_once ( JPATH_BASE .DS.'includes'.DS.'defines.php' );
require_once ( JPATH_BASE .DS.'includes'.DS.'framework.php' );
JFactory::getApplication('site')->initialise();
$user = JFactory::getUser();
$joomla_name = $user->name;
$joomla_email = $user->email;
$joomla_password = $user->password;
$joomla_username = $user->username;
I think people have had problems with this in Joomla 2.5 as things have changed. I haven't found a solution for the way you have requested but wrote this work around (excluding the password field though) that you may want to use.
define a connection to the database:
<?php
$host="localhost";
$username="DB_USERNAME";
$password="DB_PASSWORD";
$db_name="DB_NAME";
mysql_connect($host,$username,$password)or die(mysql_error());
mysql_select_db($db_name)or die(mysql_error());
?>
Echo create a query and echo the results in a table:
<table style="background:#FFF; color:#000;">
<?php
$query = "SELECT username,name,email FROM j25_users ";
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
echo '<tr><td>',$row["username"],'</td><td>',$row["name"],'</td><td>',$row["email"],'</td></tr>' ;
}
?>
</table>
You will need to change j25_users to the correct prefix of your database tables.
Update: Much better to import the framework to get the user object.
Hope this comes in handy for you. Regards.
If you want to skip using Joomla! functions, you can query the Joomla! database. Join tables js25_session and js25_users with the user id. This way, you can get every currently logged-in user and all guests on the website (and possibly the number of online users).

Can't use session variable in routes.php file in codeigniter?

I am use following code to retrieve the session variable in routes.php
if($this->db_session->userdata('request_url')!="")
{
$route['user/(:any)'] = "search_user_name/redirect_url/".$_SESSION['request_url'];
$this->db_session->unset_userdata('request_url');
}
else {
$route['user/(:any)'] = "search_user_name/index/$1";
}
the session variable would be set into template/header.php
$this->db_session->set_userdata('request_url', $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"]);
You can not use db_session in routes.php because routes.php is parsed before db_session is loaded.
Maybe you should create a base controller and redirect from the constructor of the base controller.
Correct me if iam wrong.
You can use hooks.
Codeigniter user guide hooks
You can use database in routes and put your routes url in database.
Here is an example:
require_once( BASEPATH .'database/DB'. EXT );
$db =& DB();
$table2 = $db->dbprefix.'lang';
$query2 = $db->get( $table2 );
$result2 = $query2->result();
foreach( $result2 as $row )
{
$fields = $db->list_fields($table2);
$findme = 'code';
foreach($fields as $field):
$pos = strpos($field, $findme);
if($pos !== false and $row->$field != ''):
$route[''.$row->$field.''] = 'main/setlang/$1';
endif;
endforeach;
}

Resources