Jump to content
MakeWebGames

PHP script/MySQL undesirably slow


Sean_93

Recommended Posts

So ive been trying to work out for a while now why this page is taking ages to load.. But i just cannot find the problem at all, if you could let me know if theres any problems you notice with the code, or if you can help suggest ways on which i could optimize the code.. I'd be very grateful! :D

Thanks

 

<?php
//header('P3P:CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT"');
require_once("connect.php");
require_once ("config.php");
require_once ("fb_config.php");
?>
 <? echo microtime();?>
 <?//=$user?>
 <?php

if($user == 0) {
echo "You are not logged into facebook.";
}else{


$query = "SELECT id,fb_id,login_ip,login_count,activated,sitestate FROM login WHERE fb_id='".mysql_real_escape_string($user)."'"; 
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result);


if (mysql_num_rows($result) == 0){

$choosePlayername = $_POST['choosePlayername'];

if(isset($_POST['proceed'])){


if ((strlen($choosePlayername) > "20") or (strlen($choosePlayername) < "2")){
//echo "<font color='red'>Your name needs to be between 2 and 20 characters long.</font>";
$errorMsg='<font color="red">Your name needs to be between 2 and 20 characters long.</font>';
}else{



$sql = "SELECT id FROM login WHERE name='".mysql_real_escape_string($choosePlayername)."'";
$query = mysql_query($sql) or die(mysql_error());
$count = mysql_num_rows($query);

if($count >= "1"){
//echo "<font color='red'>This username is already taken.</font>";
$errorMsg='<font color="red">This username is already taken.</font>';
}else{

if (ereg('[^A-Za-z0-9]', $choosePlayername)) {
//echo "<font color='red'>Invalid Name only A-Z,a-z and 0-9 is allowed.</font>";
$errorMsg='<font color="red">Invalid Name only A-Z,a-z and 0-9 is allowed.</font>';
}else{

if (in_array ($choosePlayername,$name_blacklist)) {
//echo ("<font color='red'>This name has been disabled, please choose another one.</font>");
$errorMsg='<font color="red">This name has been disabled, please choose another one.</font>';
}else{
$randomlocation = rand (1,6);

if ($randomlocation == 2) {
$randomlocation = rand (3,6);
}


$gender=$user_profile['gender'];
$twodayprot = time () + 60 * 60 * 24 * 2;

$sql = "INSERT INTO login SET id = '',
fb_id= '" .mysql_real_escape_string($user). "',
name = '" .mysql_real_escape_string($choosePlayername). "', 
signup =NOW() ,
location='".mysql_real_escape_string($randomlocation)."',
location_start='".mysql_real_escape_string($randomlocation)."',
signup_ip='".mysql_real_escape_string($_SERVER['REMOTE_ADDR'])."',
killprotection = '$twodayprot',
gender='" .mysql_real_escape_string($gender). "'
";

$res = mysql_query($sql) or die(mysql_error());

$message = "Game welcome 1
";

$sql = "INSERT INTO pm SET id = '', sendto = '" .mysql_real_escape_string($choosePlayername). "',sendby = '" .mysql_real_escape_string($choosePlayername). "', title='Welcome' , message = '$message'";
$res = mysql_query($sql);

$message = "Game message ";

$sql = "INSERT INTO pm SET id = '', sendto = '" .mysql_real_escape_string($choosePlayername). "',sendby = '" .mysql_real_escape_string($choosePlayername). "', title='Introduction' , message = '$message'";
$res = mysql_query($sql);

// send email.

  $email_message  = "
  Welcome to MobWorld, the free, online, mafia themed, text-based game. \n\n
  Your Account Information: \n\n
  Username: ".$choosePlayername."\n
  Activation Link: ".$_SERVER['HTTP_HOST']."/index.php?activation_link=".$activation_link." \n
  Activation Code: ".$activation_link." \n\n

  You will need to activate your account in order to start playing. Click the above link, or copy and paste it into your web browser and your account will be activated.
  \n \n
  If the above link fails to work, enter your activation code in the activate page.
  ";

     $mail = mail($_POST['mail'],"Welcome to MobWorld",$email_message,"From: [email protected]");
	if (!$mail) {
	echo ("<font color='red'>Fatal Error! Your E-mail was not sent! </font><br />");
	}
$_SESSION['user_id'] = $row['id'];
header("location: home.php");

} // invalid name
}// check name characters.
}// check if name is unused.
}// name check.
}// if post register.
echo"<center>$errorMsg</center>";
echo $user_profile['gender'];
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<link rel="stylesheet" type="text/css" href="http://static.mob-world.com/NEW/FB/css/main.min.css">
</head>
<body>
<table width="50%" align="center" class="default">
<tr>
 <td colspan="2" class="header">Hey, <?=$user_profile['name']?></td>
</tr>
<tr>
 <td width="50px" class="subheader"><img name="" src="http://graph.facebook.com/<?=$user?>/picture?type=square" width="50" height="50" /></td>
 <td class="subheader">This is the very first step to a long journey on becoming the top mafiso, we wish you good luck.</td>
</tr>
<tr>
 <td colspan="2" class="header">Please choose your playername to proceed:</td>
</tr>
<tr align="center">
 <td colspan="2" class="content"><form action="" method="post">
   <label>Playername: 
     <input name="choosePlayername" type="text" id="choosePlayername" />
   </label>
   <input type="submit" name="proceed" id="proceed" value="Proceed" />
 </form></td>
</tr>
<tr align="center">
 <td colspan="2" class="content">The playername you choose above will be available to see by other players, so choose wisely.</td>
</tr>
</table>
</body>
</html>
<?

}else{


	if(empty($row['login_ip'])){
	$row['login_ip'] = $_SERVER['REMOTE_ADDR'];
	}else{

	$ip_information = explode("-", $row['login_ip']);

	if (in_array($_SERVER['REMOTE_ADDR'], $ip_information)) {	
	$row['login_ip'] = $row['login_ip'];
	}else{	
	$row['login_ip'] = $row['login_ip']."-".$_SERVER['REMOTE_ADDR'];
	}
	}

$update_login = mysql_query("UPDATE login SET login_count=login_count+'1' WHERE name='".mysql_real_escape_string($_POST['username'])."'")
or die(mysql_error());

$_SESSION['user_id'] = $row['id'];

$result = mysql_query("UPDATE login SET userip='".mysql_real_escape_string($_SERVER['REMOTE_ADDR'])."',login_ip='".mysql_real_escape_string($row['login_ip'])."',login_count='0' WHERE id='".mysql_real_escape_string($_SESSION['user_id'])."'")
or die(mysql_error());


if ($row['sitestate'] == 0){
header("location: home.php");
} elseif ($row['sitestate'] == 2) {
header("location: killed.php?id={$row['id']}&encrypted={$row['password']}");
} else {
header("location: banned.php?id={$row['id']}&encrypted={$row['password']}");
}

}// id check.
}

?>
Link to comment
Share on other sites

Before we blame the script, can we confirm server resources are not to blame?

I am going to assume here, please feel free to confirm or deny, but is this a game script?

If so, how many active users?

Are other pages slow? Or just this?

What kind of server set up you got? Dedi? VPS? Shared?

Its part of a Facebook application im making, what it does is basically logs the user in if they already have created a player, otherwise you'll be prompted to make one

Active user wise; its pretty much only me that's the active user as the games under development

It seems to be only that page that is slow..

Server wise, its on shared hosting, as it wont need much resources until it starts picking up a user base :)

Link to comment
Share on other sites

Why are you disabling the P3P header?

There's a reason it was designed.

Do an EXPLAIN and PROFILE on each query, see what pops up.

Ah, yes, the p3p header I just disabled whilst I was running some tests in IE, im starting to think Facebook's API is just very slow at the minute..

Also, im not sure how i'd use EXPLAIN and PROFILE :confused:

Thanks

Link to comment
Share on other sites

Cheers, ill take a look at that now, ive also attached a screenshot which is showing the latency etc, if this means anything, to anyone.. :)

[ATTACH=CONFIG]336[/ATTACH]

I had to open the page in a new tab so i could show the network section clearly, so that's why its not in FB's iFrame before anyone asks :P

MWFBAPP.thumb.jpg.3dcdd5e6d51ef34928fbca4d813806bc.jpg

Edited by Sean_93
Link to comment
Share on other sites

Cheers, ill take a look at that now, ive also attached a screenshot which is showing the latency etc, if this means anything, to anyone.. :)

[ATTACH=CONFIG]336[/ATTACH]

I had to open the page in a new tab so i could show the network section clearly, so that's why its not in FB's iFrame before anyone asks :P

Do you use the PHP API?

If so, this is normal.

The default PHP API uses curl, which is slow.

There's a function called requestSomething within the class, and I'd suggest you follow my method of replacing that function during runtime(class __socket_fork extends Base?).

Link to comment
Share on other sites

Do you use the PHP API?

If so, this is normal.

The default PHP API uses curl, which is slow.

There's a function called requestSomething within the class, and I'd suggest you follow my method of replacing that function during runtime(class __socket_fork extends Base?).

Yeah, i use the PHP API, and could you expand on the function bit to replace, as this would be a life saver spudinski! :)

Link to comment
Share on other sites

Yeah, i use the PHP API, and could you expand on the function bit to replace, as this would be a life saver spudinski! :)

Well, in an OOP sense, Facebook has made provision to use other connection methods.

The thing is though, that they don't have a fallback for if curl is installed on the system.

Luckily, Facebook made it's code open source, which means other developers have already created ways in which to make that API better.

One such example is https://github.com/mattmecham/php-sdk/blob/matts3.x/src/base_facebook.php#L722.

If you would take a look at the highlighted line on that page, you will see that there is a conditional statement to validate the existence of curl.

Of course, this isn't ideal. We want to use sockets by default.

So, just change that statement, and replace all of it with false, so it never validates and uses curl.

I haven't had any issues with it yet, since it is supposed to be an exact replica of Facebook's code, but be sure to look at the docs.

Link to comment
Share on other sites

Well, in an OOP sense, Facebook has made provision to use other connection methods.

The thing is though, that they don't have a fallback for if curl is installed on the system.

Luckily, Facebook made it's code open source, which means other developers have already created ways in which to make that API better.

One such example is https://github.com/mattmecham/php-sdk/blob/matts3.x/src/base_facebook.php#L722.

If you would take a look at the highlighted line on that page, you will see that there is a conditional statement to validate the existence of curl.

Of course, this isn't ideal. We want to use sockets by default.

So, just change that statement, and replace all of it with false, so it never validates and uses curl.

I haven't had any issues with it yet, since it is supposed to be an exact replica of Facebook's code, but be sure to look at the docs.

I can see that the latest update he done was around 9 months ago, surely he wont have all the new bits that were added?

Do you know what was changed between 3.0.1 and 3.1.1?

I don't get why Facebook would opt for even using cURL in the first place if its slow..

Link to comment
Share on other sites

Can you please post your code?

I'd gladly take a look at it for you.

Sure!

base_facebook.php:

<?php
/**
* Copyright 2011 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/

if (!function_exists('json_decode')) {
 throw new Exception('Facebook needs the JSON PHP extension.');
}

/**
* Thrown when an API call returns an exception.
*
* @author Naitik Shah <[email protected]>
*/
class FacebookApiException extends Exception
{
 /**
  * The result from the API server that represents the exception information.
  */
 protected $result;

 /**
  * Make a new API Exception with the given result.
  *
  * @param array $result The result from the API server
  */
 public function __construct($result) {
   $this->result = $result;

   $code = isset($result['error_code']) ? $result['error_code'] : 0;

   if (isset($result['error_description'])) {
     // OAuth 2.0 Draft 10 style
     $msg = $result['error_description'];
   } else if (isset($result['error']) && is_array($result['error'])) {
     // OAuth 2.0 Draft 00 style
     $msg = $result['error']['message'];
   } else if (isset($result['error_msg'])) {
     // Rest server style
     $msg = $result['error_msg'];
   } else {
     $msg = 'Unknown Error. Check getResult()';
   }

   parent::__construct($msg, $code);
 }

 /**
  * Return the associated result object returned by the API server.
  *
  * @return array The result from the API server
  */
 public function getResult() {
   return $this->result;
 }

 /**
  * Returns the associated type for the error. This will default to
  * 'Exception' when a type is not available.
  *
  * @return string
  */
 public function getType() {
   if (isset($this->result['error'])) {
     $error = $this->result['error'];
     if (is_string($error)) {
       // OAuth 2.0 Draft 10 style
       return $error;
     } else if (is_array($error)) {
       // OAuth 2.0 Draft 00 style
       if (isset($error['type'])) {
         return $error['type'];
       }
     }
   }

   return 'Exception';
 }

 /**
  * To make debugging easier.
  *
  * @return string The string representation of the error
  */
 public function __toString() {
   $str = $this->getType() . ': ';
   if ($this->code != 0) {
     $str .= $this->code . ': ';
   }
   return $str . $this->message;
 }
}

/**
* Provides access to the Facebook Platform.  This class provides
* a majority of the functionality needed, but the class is abstract
* because it is designed to be sub-classed.  The subclass must
* implement the four abstract methods listed at the bottom of
* the file.
*
* @author Naitik Shah <[email protected]>
*/
abstract class BaseFacebook
{
 /**
  * Version.
  */
 const VERSION = '3.1.1';

 /**
  * Default options for curl.
  */
 public static $CURL_OPTS = array(
   CURLOPT_CONNECTTIMEOUT => 10,
   CURLOPT_RETURNTRANSFER => true,
   CURLOPT_TIMEOUT        => 60,
   CURLOPT_USERAGENT      => 'facebook-php-3.1',
 );

 /**
  * List of query parameters that get automatically dropped when rebuilding
  * the current URL.
  */
 protected static $DROP_QUERY_PARAMS = array(
   'code',
   'state',
   'signed_request',
 );

 /**
  * Maps aliases to Facebook domains.
  */
 public static $DOMAIN_MAP = array(
   'api'       => 'https://api.facebook.com/',
   'api_video' => 'https://api-video.facebook.com/',
   'api_read'  => 'https://api-read.facebook.com/',
   'graph'     => 'https://graph.facebook.com/',
   'graph_video' => 'https://graph-video.facebook.com/',
   'www'       => 'https://www.facebook.com/',
 );

 /**
  * The Application ID.
  *
  * @var string
  */
 protected $appId;

 /**
  * The Application App Secret.
  *
  * @var string
  */
 protected $appSecret;

 /**
  * The ID of the Facebook user, or 0 if the user is logged out.
  *
  * @var integer
  */
 protected $user;

 /**
  * The data from the signed_request token.
  */
 protected $signedRequest;

 /**
  * A CSRF state variable to assist in the defense against CSRF attacks.
  */
 protected $state;

 /**
  * The OAuth access token received in exchange for a valid authorization
  * code.  null means the access token has yet to be determined.
  *
  * @var string
  */
 protected $accessToken = null;

 /**
  * Indicates if the CURL based @ syntax for file uploads is enabled.
  *
  * @var boolean
  */
 protected $fileUploadSupport = false;

 /**
  * Initialize a Facebook Application.
  *
  * The configuration:
  * - appId: the application ID
  * - secret: the application secret
  * - fileUpload: (optional) boolean indicating if file uploads are enabled
  *
  * @param array $config The application configuration
  */
 public function __construct($config) {
   $this->setAppId($config['appId']);
   $this->setAppSecret($config['secret']);
   if (isset($config['fileUpload'])) {
     $this->setFileUploadSupport($config['fileUpload']);
   }

   $state = $this->getPersistentData('state');
   if (!empty($state)) {
     $this->state = $this->getPersistentData('state');
   }
 }

 /**
  * Set the Application ID.
  *
  * @param string $appId The Application ID
  * @return BaseFacebook
  */
 public function setAppId($appId) {
   $this->appId = $appId;
   return $this;
 }

 /**
  * Get the Application ID.
  *
  * @return string the Application ID
  */
 public function getAppId() {
   return $this->appId;
 }

 /**
  * Set the App Secret.
  *
  * @param string $apiSecret The App Secret
  * @return BaseFacebook
  * @deprecated
  */
 public function setApiSecret($apiSecret) {
   $this->setAppSecret($apiSecret);
   return $this;
 }

 /**
  * Set the App Secret.
  *
  * @param string $appSecret The App Secret
  * @return BaseFacebook
  */
 public function setAppSecret($appSecret) {
   $this->appSecret = $appSecret;
   return $this;
 }

 /**
  * Get the App Secret.
  *
  * @return string the App Secret
  * @deprecated
  */
 public function getApiSecret() {
   return $this->getAppSecret();
 }

 /**
  * Get the App Secret.
  *
  * @return string the App Secret
  */
 public function getAppSecret() {
   return $this->appSecret;
 }

 /**
  * Set the file upload support status.
  *
  * @param boolean $fileUploadSupport The file upload support status.
  * @return BaseFacebook
  */
 public function setFileUploadSupport($fileUploadSupport) {
   $this->fileUploadSupport = $fileUploadSupport;
   return $this;
 }

 /**
  * Get the file upload support status.
  *
  * @return boolean true if and only if the server supports file upload.
  */
 public function getFileUploadSupport() {
   return $this->fileUploadSupport;
 }

 /**
  * DEPRECATED! Please use getFileUploadSupport instead.
  *
  * Get the file upload support status.
  *
  * @return boolean true if and only if the server supports file upload.
  */
 public function useFileUploadSupport() {
   return $this->getFileUploadSupport();
 }

 /**
  * Sets the access token for api calls.  Use this if you get
  * your access token by other means and just want the SDK
  * to use it.
  *
  * @param string $access_token an access token.
  * @return BaseFacebook
  */
 public function setAccessToken($access_token) {
   $this->accessToken = $access_token;
   return $this;
 }

 /**
  * Determines the access token that should be used for API calls.
  * The first time this is called, $this->accessToken is set equal
  * to either a valid user access token, or it's set to the application
  * access token if a valid user access token wasn't available.  Subsequent
  * calls return whatever the first call returned.
  *
  * @return string The access token
  */
 public function getAccessToken() {
   if ($this->accessToken !== null) {
     // we've done this already and cached it.  Just return.
     return $this->accessToken;
   }

   // first establish access token to be the application
   // access token, in case we navigate to the /oauth/access_token
   // endpoint, where SOME access token is required.
   $this->setAccessToken($this->getApplicationAccessToken());
   $user_access_token = $this->getUserAccessToken();
   if ($user_access_token) {
     $this->setAccessToken($user_access_token);
   }

   return $this->accessToken;
 }

 /**
  * Determines and returns the user access token, first using
  * the signed request if present, and then falling back on
  * the authorization code if present.  The intent is to
  * return a valid user access token, or false if one is determined
  * to not be available.
  *
  * @return string A valid user access token, or false if one
  *                could not be determined.
  */
 protected function getUserAccessToken() {
   // first, consider a signed request if it's supplied.
   // if there is a signed request, then it alone determines
   // the access token.
   $signed_request = $this->getSignedRequest();
   if ($signed_request) {
     // apps.facebook.com hands the access_token in the signed_request
     if (array_key_exists('oauth_token', $signed_request)) {
       $access_token = $signed_request['oauth_token'];
       $this->setPersistentData('access_token', $access_token);
       return $access_token;
     }

     // the JS SDK puts a code in with the redirect_uri of ''
     if (array_key_exists('code', $signed_request)) {
       $code = $signed_request['code'];
       $access_token = $this->getAccessTokenFromCode($code, '');
       if ($access_token) {
         $this->setPersistentData('code', $code);
         $this->setPersistentData('access_token', $access_token);
         return $access_token;
       }
     }

     // signed request states there's no access token, so anything
     // stored should be cleared.
     $this->clearAllPersistentData();
     return false; // respect the signed request's data, even
                   // if there's an authorization code or something else
   }

   $code = $this->getCode();
   if ($code && $code != $this->getPersistentData('code')) {
     $access_token = $this->getAccessTokenFromCode($code);
     if ($access_token) {
       $this->setPersistentData('code', $code);
       $this->setPersistentData('access_token', $access_token);
       return $access_token;
     }

     // code was bogus, so everything based on it should be invalidated.
     $this->clearAllPersistentData();
     return false;
   }

   // as a fallback, just return whatever is in the persistent
   // store, knowing nothing explicit (signed request, authorization
   // code, etc.) was present to shadow it (or we saw a code in $_REQUEST,
   // but it's the same as what's in the persistent store)
   return $this->getPersistentData('access_token');
 }

 /**
  * Retrieve the signed request, either from a request parameter or,
  * if not present, from a cookie.
  *
  * @return string the signed request, if available, or null otherwise.
  */
 public function getSignedRequest() {
   if (!$this->signedRequest) {
     if (isset($_REQUEST['signed_request'])) {
       $this->signedRequest = $this->parseSignedRequest(
         $_REQUEST['signed_request']);
     } else if (isset($_COOKIE[$this->getSignedRequestCookieName()])) {
       $this->signedRequest = $this->parseSignedRequest(
         $_COOKIE[$this->getSignedRequestCookieName()]);
     }
   }
   return $this->signedRequest;
 }

 /**
  * Get the UID of the connected user, or 0
  * if the Facebook user is not connected.
  *
  * @return string the UID if available.
  */
 public function getUser() {
   if ($this->user !== null) {
     // we've already determined this and cached the value.
     return $this->user;
   }

   return $this->user = $this->getUserFromAvailableData();
 }

 /**
  * Determines the connected user by first examining any signed
  * requests, then considering an authorization code, and then
  * falling back to any persistent store storing the user.
  *
  * @return integer The id of the connected Facebook user,
  *                 or 0 if no such user exists.
  */
 protected function getUserFromAvailableData() {
   // if a signed request is supplied, then it solely determines
   // who the user is.
   $signed_request = $this->getSignedRequest();
   if ($signed_request) {
     if (array_key_exists('user_id', $signed_request)) {
       $user = $signed_request['user_id'];
       $this->setPersistentData('user_id', $signed_request['user_id']);
       return $user;
     }

     // if the signed request didn't present a user id, then invalidate
     // all entries in any persistent store.
     $this->clearAllPersistentData();
     return 0;
   }

   $user = $this->getPersistentData('user_id', $default = 0);
   $persisted_access_token = $this->getPersistentData('access_token');

   // use access_token to fetch user id if we have a user access_token, or if
   // the cached access token has changed.
   $access_token = $this->getAccessToken();
   if ($access_token &&
       $access_token != $this->getApplicationAccessToken() &&
       !($user && $persisted_access_token == $access_token)) {
     $user = $this->getUserFromAccessToken();
     if ($user) {
       $this->setPersistentData('user_id', $user);
     } else {
       $this->clearAllPersistentData();
     }
   }

   return $user;
 }

 /**
  * Get a Login URL for use with redirects. By default, full page redirect is
  * assumed. If you are using the generated URL with a window.open() call in
  * JavaScript, you can pass in display=popup as part of the $params.
  *
  * The parameters:
  * - redirect_uri: the url to go to after a successful login
  * - scope: comma separated list of requested extended perms
  *
  * @param array $params Provide custom parameters
  * @return string The URL for the login flow
  */
 public function getLoginUrl($params=array()) {
   $this->establishCSRFTokenState();
   $currentUrl = $this->getCurrentUrl();

   // if 'scope' is passed as an array, convert to comma separated list
   $scopeParams = isset($params['scope']) ? $params['scope'] : null;
   if ($scopeParams && is_array($scopeParams)) {
     $params['scope'] = implode(',', $scopeParams);
   }

   return $this->getUrl(
     'www',
     'dialog/oauth',
     array_merge(array(
                   'client_id' => $this->getAppId(),
                   'redirect_uri' => $currentUrl, // possibly overwritten
                   'state' => $this->state),
                 $params));
 }

 /**
  * Get a Logout URL suitable for use with redirects.
  *
  * The parameters:
  * - next: the url to go to after a successful logout
  *
  * @param array $params Provide custom parameters
  * @return string The URL for the logout flow
  */
 public function getLogoutUrl($params=array()) {
   return $this->getUrl(
     'www',
     'logout.php',
     array_merge(array(
       'next' => $this->getCurrentUrl(),
       'access_token' => $this->getAccessToken(),
     ), $params)
   );
 }

 /**
  * Get a login status URL to fetch the status from Facebook.
  *
  * The parameters:
  * - ok_session: the URL to go to if a session is found
  * - no_session: the URL to go to if the user is not connected
  * - no_user: the URL to go to if the user is not signed into facebook
  *
  * @param array $params Provide custom parameters
  * @return string The URL for the logout flow
  */
 public function getLoginStatusUrl($params=array()) {
   return $this->getUrl(
     'www',
     'extern/login_status.php',
     array_merge(array(
       'api_key' => $this->getAppId(),
       'no_session' => $this->getCurrentUrl(),
       'no_user' => $this->getCurrentUrl(),
       'ok_session' => $this->getCurrentUrl(),
       'session_version' => 3,
     ), $params)
   );
 }

 /**
  * Make an API call.
  *
  * @return mixed The decoded response
  */
 public function api(/* polymorphic */) {
   $args = func_get_args();
   if (is_array($args[0])) {
     return $this->_restserver($args[0]);
   } else {
     return call_user_func_array(array($this, '_graph'), $args);
   }
 }

 /**
  * Constructs and returns the name of the cookie that
  * potentially houses the signed request for the app user.
  * The cookie is not set by the BaseFacebook class, but
  * it may be set by the JavaScript SDK.
  *
  * @return string the name of the cookie that would house
  *         the signed request value.
  */
 protected function getSignedRequestCookieName() {
   return 'fbsr_'.$this->getAppId();
 }

 /**
  * Constructs and returns the name of the coookie that potentially contain
  * metadata. The cookie is not set by the BaseFacebook class, but it may be
  * set by the JavaScript SDK.
  *
  * @return string the name of the cookie that would house metadata.
  */
 protected function getMetadataCookieName() {
   return 'fbm_'.$this->getAppId();
 }

 /**
  * Get the authorization code from the query parameters, if it exists,
  * and otherwise return false to signal no authorization code was
  * discoverable.
  *
  * @return mixed The authorization code, or false if the authorization
  *               code could not be determined.
  */
 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;
 }

 /**
  * Retrieves the UID with the understanding that
  * $this->accessToken has already been set and is
  * seemingly legitimate.  It relies on Facebook's Graph API
  * to retrieve user information and then extract
  * the user ID.
  *
  * @return integer Returns the UID of the Facebook user, or 0
  *                 if the Facebook user could not be determined.
  */
 protected function getUserFromAccessToken() {
   try {
     $user_info = $this->api('/me');
     return $user_info['id'];
   } catch (FacebookApiException $e) {
     return 0;
   }
 }

 /**
  * Returns the access token that should be used for logged out
  * users when no authorization code is available.
  *
  * @return string The application access token, useful for gathering
  *                public information about users and applications.
  */
 protected function getApplicationAccessToken() {
   return $this->appId.'|'.$this->appSecret;
 }

 /**
  * Lays down a CSRF state token for this process.
  *
  * @return void
  */
 protected function establishCSRFTokenState() {
   if ($this->state === null) {
     $this->state = md5(uniqid(mt_rand(), true));
     $this->setPersistentData('state', $this->state);
   }
 }

 /**
  * Retrieves an access token for the given authorization code
  * (previously generated from www.facebook.com on behalf of
  * a specific user).  The authorization code is sent to graph.facebook.com
  * and a legitimate access token is generated provided the access token
  * and the user for which it was generated all match, and the user is
  * either logged in to Facebook or has granted an offline access permission.
  *
  * @param string $code An authorization code.
  * @return mixed An access token exchanged for the authorization code, or
  *               false if an access token could not be generated.
  */
 protected function getAccessTokenFromCode($code, $redirect_uri = null) {
   if (empty($code)) {
     return false;
   }

   if ($redirect_uri === null) {
     $redirect_uri = $this->getCurrentUrl();
   }

   try {
     // need to circumvent json_decode by calling _oauthRequest
     // directly, since response isn't JSON format.
     $access_token_response =
       $this->_oauthRequest(
         $this->getUrl('graph', '/oauth/access_token'),
         $params = array('client_id' => $this->getAppId(),
                         'client_secret' => $this->getAppSecret(),
                         'redirect_uri' => $redirect_uri,
                         'code' => $code));
   } catch (FacebookApiException $e) {
     // most likely that user very recently revoked authorization.
     // In any event, we don't have an access token, so say so.
     return false;
   }

   if (empty($access_token_response)) {
     return false;
   }

   $response_params = array();
   parse_str($access_token_response, $response_params);
   if (!isset($response_params['access_token'])) {
     return false;
   }

   return $response_params['access_token'];
 }

 /**
  * Invoke the old restserver.php endpoint.
  *
  * @param array $params Method call object
  *
  * @return mixed The decoded response object
  * @throws FacebookApiException
  */
 protected function _restserver($params) {
   // generic application level parameters
   $params['api_key'] = $this->getAppId();
   $params['format'] = 'json-strings';

   $result = json_decode($this->_oauthRequest(
     $this->getApiUrl($params['method']),
     $params
   ), true);

   // results are returned, errors are thrown
   if (is_array($result) && isset($result['error_code'])) {
     $this->throwAPIException($result);
   }

   if ($params['method'] === 'auth.expireSession' ||
       $params['method'] === 'auth.revokeAuthorization') {
     $this->destroySession();
   }

   return $result;
 }

 /**
  * Return true if this is video post.
  *
  * @param string $path The path
  * @param string $method The http method (default 'GET')
  *
  * @return boolean true if this is video post
  */
 protected function isVideoPost($path, $method = 'GET') {
   if ($method == 'POST' && preg_match("/^(\/)(.+)(\/)(videos)$/", $path)) {
     return true;
   }
   return false;
 }

 /**
  * Invoke the Graph API.
  *
  * @param string $path The path (required)
  * @param string $method The http method (default 'GET')
  * @param array $params The query/post data
  *
  * @return mixed The decoded response object
  * @throws FacebookApiException
  */
 protected function _graph($path, $method = 'GET', $params = array()) {
   if (is_array($method) && empty($params)) {
     $params = $method;
     $method = 'GET';
   }
   $params['method'] = $method; // method override as we always do a POST

   if ($this->isVideoPost($path, $method)) {
     $domainKey = 'graph_video';
   } else {
     $domainKey = 'graph';
   }

   $result = json_decode($this->_oauthRequest(
     $this->getUrl($domainKey, $path),
     $params
   ), true);

   // results are returned, errors are thrown
   if (is_array($result) && isset($result['error'])) {
     $this->throwAPIException($result);
   }

   return $result;
 }

 /**
  * Make a OAuth Request.
  *
  * @param string $url The path (required)
  * @param array $params The query/post data
  *
  * @return string The decoded response object
  * @throws FacebookApiException
  */
 protected function _oauthRequest($url, $params) {
   if (!isset($params['access_token'])) {
     $params['access_token'] = $this->getAccessToken();
   }

   // json_encode all params values that are not strings
   foreach ($params as $key => $value) {
     if (!is_string($value)) {
       $params[$key] = json_encode($value);
     }
   }

   return $this->makeRequest($url, $params);
 }

 /**
  * Makes an HTTP request. This method can be overridden by subclasses if
  * developers want to do fancier things or use something other than curl to
  * make the request.
  *
  * @param string $url The URL to make the request to
  * @param array $params The parameters to use for the POST body
  * @param CurlHandler $ch Initialized curl handle
  *
  * @return string The response text
  */
 protected function makeRequest($url, $params, $ch=null) {

	$url_parts  = @parse_url($url);
	$postfields = http_build_query( $params );

	if ( ! $postfields )
	{
		$postfields = $url_parts['query'];
	}

	$postfields = str_replace( '&', '&', $postfields );

	/* Use SSL rather than https */
	$url_parts['scheme'] = ( $url_parts['scheme'] == 'https' ) ? 'ssl' : $url_parts['scheme'];

	$host = $url_parts['scheme'] . '://' . $url_parts['host'];
 	$port = ( isset($url_parts['port']) ) ? $url_parts['port'] : ( $url_parts['scheme'] == 'https' || $url_parts['scheme'] == 'ssl' ? 443 : 80 );

 	if ( !empty( $url_parts["path"] ) )
	{
		$path = $url_parts["path"];
	}
	else
	{
		$path = "/";
	}

	$header  = "POST {$path} HTTP/1.0\r\n";
	$header .= "Host: " . str_replace( array( 'http://', 'https://', 'ssl://' ), '', $host ) . "\r\n";
	$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
	$header .= "Content-Length: " . strlen($postfields) . "\r\n\r\n";

	if ( $fp = fsockopen( $host, $port, $errno, $errstr, 60 ) )
	{
		socket_set_timeout($fp, 60);

		fwrite($fp, $header . $postfields);

		while( ! feof($fp) && ! $status['timed_out'] )		
		{
	  		$data .= fgets ($fp,8192);
	  		$status  = stream_get_meta_data($fp);
		}

		fclose($fp);
 	}		

	/* Strip headers HTTP/1.1 ### ABCD */
	$httpCode     = substr( $data, 9, 3 );
	$lastApiCall = $url;

	/* Chuncked? */

	$_chunked	= false;

	if( preg_match( "/Transfer\-Encoding:\s*chunked/i", $data ) )
	{
		$_chunked	= true;
	}

	$tmp	= explode("\r\n\r\n", $data, 2);
	$data	= trim($tmp[1]);

	if ( $_chunked )
	{
		$lines	= explode( "\n", $data );
		array_pop($lines);
		array_shift($lines);
		$data	= implode( "\n", $lines );
	}

	return $data;
}


 /**
  * Parses a signed_request and validates the signature.
  *
  * @param string $signed_request A signed token
  * @return array The payload inside it or null if the sig is wrong
  */
 protected function parseSignedRequest($signed_request) {
   list($encoded_sig, $payload) = explode('.', $signed_request, 2);

   // decode the data
   $sig = self::base64UrlDecode($encoded_sig);
   $data = json_decode(self::base64UrlDecode($payload), true);

   if (strtoupper($data['algorithm']) !== 'HMAC-SHA256') {
     self::errorLog('Unknown algorithm. Expected HMAC-SHA256');
     return null;
   }

   // check sig
   $expected_sig = hash_hmac('sha256', $payload,
                             $this->getAppSecret(), $raw = true);
   if ($sig !== $expected_sig) {
     self::errorLog('Bad Signed JSON signature!');
     return null;
   }

   return $data;
 }

 /**
  * Build the URL for api given parameters.
  *
  * @param $method String the method name.
  * @return string The URL for the given parameters
  */
 protected function getApiUrl($method) {
   static $READ_ONLY_CALLS =
     array('admin.getallocation' => 1,
           'admin.getappproperties' => 1,
           'admin.getbannedusers' => 1,
           'admin.getlivestreamvialink' => 1,
           'admin.getmetrics' => 1,
           'admin.getrestrictioninfo' => 1,
           'application.getpublicinfo' => 1,
           'auth.getapppublickey' => 1,
           'auth.getsession' => 1,
           'auth.getsignedpublicsessiondata' => 1,
           'comments.get' => 1,
           'connect.getunconnectedfriendscount' => 1,
           'dashboard.getactivity' => 1,
           'dashboard.getcount' => 1,
           'dashboard.getglobalnews' => 1,
           'dashboard.getnews' => 1,
           'dashboard.multigetcount' => 1,
           'dashboard.multigetnews' => 1,
           'data.getcookies' => 1,
           'events.get' => 1,
           'events.getmembers' => 1,
           'fbml.getcustomtags' => 1,
           'feed.getappfriendstories' => 1,
           'feed.getregisteredtemplatebundlebyid' => 1,
           'feed.getregisteredtemplatebundles' => 1,
           'fql.multiquery' => 1,
           'fql.query' => 1,
           'friends.arefriends' => 1,
           'friends.get' => 1,
           'friends.getappusers' => 1,
           'friends.getlists' => 1,
           'friends.getmutualfriends' => 1,
           'gifts.get' => 1,
           'groups.get' => 1,
           'groups.getmembers' => 1,
           'intl.gettranslations' => 1,
           'links.get' => 1,
           'notes.get' => 1,
           'notifications.get' => 1,
           'pages.getinfo' => 1,
           'pages.isadmin' => 1,
           'pages.isappadded' => 1,
           'pages.isfan' => 1,
           'permissions.checkavailableapiaccess' => 1,
           'permissions.checkgrantedapiaccess' => 1,
           'photos.get' => 1,
           'photos.getalbums' => 1,
           'photos.gettags' => 1,
           'profile.getinfo' => 1,
           'profile.getinfooptions' => 1,
           'stream.get' => 1,
           'stream.getcomments' => 1,
           'stream.getfilters' => 1,
           'users.getinfo' => 1,
           'users.getloggedinuser' => 1,
           'users.getstandardinfo' => 1,
           'users.hasapppermission' => 1,
           'users.isappuser' => 1,
           'users.isverified' => 1,
           'video.getuploadlimits' => 1);
   $name = 'api';
   if (isset($READ_ONLY_CALLS[strtolower($method)])) {
     $name = 'api_read';
   } else if (strtolower($method) == 'video.upload') {
     $name = 'api_video';
   }
   return self::getUrl($name, 'restserver.php');
 }

 /**
  * Build the URL for given domain alias, path and parameters.
  *
  * @param $name string The name of the domain
  * @param $path string Optional path (without a leading slash)
  * @param $params array Optional query parameters
  *
  * @return string The URL for the given parameters
  */
 protected function getUrl($name, $path='', $params=array()) {
   $url = self::$DOMAIN_MAP[$name];
   if ($path) {
     if ($path[0] === '/') {
       $path = substr($path, 1);
     }
     $url .= $path;
   }
   if ($params) {
     $url .= '?' . http_build_query($params, null, '&');
   }

   return $url;
 }

 /**
  * Returns the Current URL, stripping it of known FB parameters that should
  * not persist.
  *
  * @return string The current URL
  */
 protected function getCurrentUrl() {
   if (isset($_SERVER['HTTPS']) &&
       ($_SERVER['HTTPS'] == 'on' || $_SERVER['HTTPS'] == 1) ||
       isset($_SERVER['HTTP_X_FORWARDED_PROTO']) &&
       $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') {
     $protocol = 'https://';
   }
   else {
     $protocol = 'http://';
   }
   $currentUrl = $protocol . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
   $parts = parse_url($currentUrl);

   $query = '';
   if (!empty($parts['query'])) {
     // drop known fb params
     $params = explode('&', $parts['query']);
     $retained_params = array();
     foreach ($params as $param) {
       if ($this->shouldRetainParam($param)) {
         $retained_params[] = $param;
       }
     }

     if (!empty($retained_params)) {
       $query = '?'.implode($retained_params, '&');
     }
   }

   // use port if non default
   $port =
     isset($parts['port']) &&
     (($protocol === 'http://' && $parts['port'] !== 80) ||
      ($protocol === 'https://' && $parts['port'] !== 443))
     ? ':' . $parts['port'] : '';

   // rebuild
   return $protocol . $parts['host'] . $port . $parts['path'] . $query;
 }

 /**
  * Returns true if and only if the key or key/value pair should
  * be retained as part of the query string.  This amounts to
  * a brute-force search of the very small list of Facebook-specific
  * params that should be stripped out.
  *
  * @param string $param A key or key/value pair within a URL's query (e.g.
  *                     'foo=a', 'foo=', or 'foo'.
  *
  * @return boolean
  */
 protected function shouldRetainParam($param) {
   foreach (self::$DROP_QUERY_PARAMS as $drop_query_param) {
     if (strpos($param, $drop_query_param.'=') === 0) {
       return false;
     }
   }

   return true;
 }

 /**
  * Analyzes the supplied result to see if it was thrown
  * because the access token is no longer valid.  If that is
  * the case, then we destroy the session.
  *
  * @param $result array A record storing the error message returned
  *                      by a failed API call.
  */
 protected function throwAPIException($result) {
   $e = new FacebookApiException($result);
   switch ($e->getType()) {
     // OAuth 2.0 Draft 00 style
     case 'OAuthException':
       // OAuth 2.0 Draft 10 style
     case 'invalid_token':
       // REST server errors are just Exceptions
     case 'Exception':
       $message = $e->getMessage();
       if ((strpos($message, 'Error validating access token') !== false) ||
           (strpos($message, 'Invalid OAuth access token') !== false) ||
           (strpos($message, 'An active access token must be used') !== false)
       ) {
         $this->destroySession();
       }
       break;
   }

   throw $e;
 }


 /**
  * Prints to the error log if you aren't in command line mode.
  *
  * @param string $msg Log message
  */
 protected static function errorLog($msg) {
   // disable error log if we are running in a CLI environment
   // @codeCoverageIgnoreStart
   if (php_sapi_name() != 'cli') {
     error_log($msg);
   }
   // uncomment this if you want to see the errors on the page
   // print 'error_log: '.$msg."\n";
   // @codeCoverageIgnoreEnd
 }

 /**
  * Base64 encoding that doesn't need to be urlencode()ed.
  * Exactly the same as base64_encode except it uses
  *   - instead of +
  *   _ instead of /
  *
  * @param string $input base64UrlEncoded string
  * @return string
  */
 protected static function base64UrlDecode($input) {
   return base64_decode(strtr($input, '-_', '+/'));
 }

 /**
  * Destroy the current session
  */
 public function destroySession() {
   $this->accessToken = null;
   $this->signedRequest = null;
   $this->user = null;
   $this->clearAllPersistentData();

   // Javascript sets a cookie that will be used in getSignedRequest that we
   // need to clear if we can
   $cookie_name = $this->getSignedRequestCookieName();
   if (array_key_exists($cookie_name, $_COOKIE)) {
     unset($_COOKIE[$cookie_name]);
     if (!headers_sent()) {
       // The base domain is stored in the metadata cookie if not we fallback
       // to the current hostname
       $base_domain = '.'. $_SERVER['HTTP_HOST'];

       $metadata = $this->getMetadataCookie();
       if (array_key_exists('base_domain', $metadata) &&
           !empty($metadata['base_domain'])) {
         $base_domain = $metadata['base_domain'];
       }

       setcookie($cookie_name, '', 0, '/', $base_domain);
     } else {
       self::errorLog(
         'There exists a cookie that we wanted to clear that we couldn\'t '.
         'clear because headers was already sent. Make sure to do the first '.
         'API call before outputing anything'
       );
     }
   }
 }

 /**
  * Parses the metadata cookie that our Javascript API set
  *
  * @return  an array mapping key to value
  */
 protected function getMetadataCookie() {
   $cookie_name = $this->getMetadataCookieName();
   if (!array_key_exists($cookie_name, $_COOKIE)) {
     return array();
   }

   // The cookie value can be wrapped in "-characters so remove them
   $cookie_value = trim($_COOKIE[$cookie_name], '"');

   if (empty($cookie_value)) {
     return array();
   }

   $parts = explode('&', $cookie_value);
   $metadata = array();
   foreach ($parts as $part) {
     $pair = explode('=', $part, 2);
     if (!empty($pair[0])) {
       $metadata[urldecode($pair[0])] =
         (count($pair) > 1) ? urldecode($pair[1]) : '';
     }
   }

   return $metadata;
 }

 /**
  * Each of the following four methods should be overridden in
  * a concrete subclass, as they are in the provided Facebook class.
  * The Facebook class uses PHP sessions to provide a primitive
  * persistent store, but another subclass--one that you implement--
  * might use a database, memcache, or an in-memory cache.
  *
  * @see Facebook
  */

 /**
  * Stores the given ($key, $value) pair, so that future calls to
  * getPersistentData($key) return $value. This call may be in another request.
  *
  * @param string $key
  * @param array $value
  *
  * @return void
  */
 abstract protected function setPersistentData($key, $value);

 /**
  * Get the data for $key, persisted by BaseFacebook::setPersistentData()
  *
  * @param string $key The key of the data to retrieve
  * @param boolean $default The default value to return if $key is not found
  *
  * @return mixed
  */
 abstract protected function getPersistentData($key, $default = false);

 /**
  * Clear the data with $key from the persistent storage
  *
  * @param string $key
  * @return void
  */
 abstract protected function clearPersistentData($key);

 /**
  * Clear all data from the persistent storage
  *
  * @return void
  */
 abstract protected function clearAllPersistentData();
}

 

facebook.php:

 


<?php
/**
* Copyright 2011 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/

require_once "base_facebook.php";

/**
* Extends the BaseFacebook class with the intent of using
* PHP sessions to store user ids and access tokens.
*/
class Facebook extends BaseFacebook
{
 /**
  * Identical to the parent constructor, except that
  * we start a PHP session to store the user ID and
  * access token if during the course of execution
  * we discover them.
  *
  * @param Array $config the application configuration.
  * @see BaseFacebook::__construct in facebook.php
  */
 public function __construct($config) {
   if (!session_id()) {
     session_start();
   }
   parent::__construct($config);
 }

 protected static $kSupportedKeys =
   array('state', 'code', 'access_token', 'user_id');

 /**
  * Provides the implementations of the inherited abstract
  * methods.  The implementation uses PHP sessions to maintain
  * a store for authorization codes, user ids, CSRF states, and
  * access tokens.
  */
 protected function setPersistentData($key, $value) {
   if (!in_array($key, self::$kSupportedKeys)) {
     self::errorLog('Unsupported key passed to setPersistentData.');
     return;
   }

   $session_var_name = $this->constructSessionVariableName($key);
   $_SESSION[$session_var_name] = $value;
 }

 protected function getPersistentData($key, $default = false) {
   if (!in_array($key, self::$kSupportedKeys)) {
     self::errorLog('Unsupported key passed to getPersistentData.');
     return $default;
   }

   $session_var_name = $this->constructSessionVariableName($key);
   return isset($_SESSION[$session_var_name]) ?
     $_SESSION[$session_var_name] : $default;
 }

 protected function clearPersistentData($key) {
   if (!in_array($key, self::$kSupportedKeys)) {
     self::errorLog('Unsupported key passed to clearPersistentData.');
     return;
   }

   $session_var_name = $this->constructSessionVariableName($key);
   unset($_SESSION[$session_var_name]);
 }

 protected function clearAllPersistentData() {
   foreach (self::$kSupportedKeys as $key) {
     $this->clearPersistentData($key);
   }
 }

 protected function constructSessionVariableName($key) {
   return implode('_', array('fb',
                             $this->getAppId(),
                             $key));
 }
}

 

fb_config.php:

 

<?php



// facebook application configuration.

$fbconfig['appid'] = "x";
$fbconfig['secret'] = "x";
$fbconfig['baseUrl'] = "x"; // "http://testurl.com/demo/folder/iframe/sdk3";
$fbconfig['appBaseUrl'] = "x"; // "http://apps.facebook.com/demo";

//
// If user first time authenticated the application facebook
// redirects user to baseUrl, so I checked if any code passed
// then redirect him/her to the application url
//

if (isset($_GET['code']))
{
header("Location: " . $fbconfig['appBaseUrl']);
exit;
}

// ~~
//

if (isset($_GET['request_ids']))
{

// user comes from invitation
// track them if you need

}

$user = null; //facebook user uid
try
{
include_once "fb/facebook.php";
}

catch(Exception $o)
{
echo '<pre>';
print_r($o);
echo '</pre>';
}

// Create our Application instance.

$facebook = new Facebook(array(
'appId' => $fbconfig['appid'],
'secret' => $fbconfig['secret'],
'cookie' => true,
));

// Facebook Authentication part

$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.

$loginUrl = $facebook->getLoginUrl(array(
'scope' => 'email,publish_stream,user_birthday,user_location,user_about_me,user_hometown'
));


if ($user)
{
try
	{

	// Proceed knowing you have a logged in user who's authenticated.

	$user_profile = $facebook->api('/me');
	}

catch(FacebookApiException $e)
	{

	// you should use error_log($e); instead of printing the info on browser

	d($e); // d is a debug function defined at the end of this file
	$user = null;
	}
}

if (!$user)
{
echo "<script type='text/javascript'>top.location.href = '$loginUrl';</script>";
exit;
}

// get user basic description

$userInfo = $facebook->api("/$user");

function d($d)
{
echo '<pre>';
print_r($d);
echo '</pre>';
}
?>

 

:)

Edit: Now instead of sometimes getting curl exception errors (which happened once every so often) i now get:

 

Warning: fsockopen() [function.fsockopen]: SSL: connection timeout in /var/www/vhosts/x/httpdocs/mwfbapp/fb/base_facebook.php on line 883

Warning: fsockopen() [function.fsockopen]: Failed to enable crypto in /var/www/vhosts/x/httpdocs/mwfbapp/fb/base_facebook.php on line 883

Warning: fsockopen() [function.fsockopen]: unable to connect to ssl://graph.facebook.com:443 (Unknown error) in /var/www/vhosts/x/httpdocs/mwfbapp/fb/base_facebook.php on line 883

Which i shouldn't really be getting anyway..

Edited by Sean_93
Added some more info
Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...