Facebook SDK 4.0.0 for PHP: A working sample to manage sessions


Once you have a working sample of Facebook SDK 4.0.0 for PHP, you will notice upon refreshing the page an error:
Fatal error: Uncaught exception ‘Facebook\FacebookAuthorizationException’ with message ‘This authorization code has expired.’

Well, this is quite annoying as it breaks the user navigation on your site. To get around this issue, record the FacebookSession token to the user’s session and use it next time the page load.


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/GraphSessionInfo.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\GraphSessionInfo;

$appid = ''; // your AppID
$secret = ''; // your secret

// Initialize app with app id (APPID) and secret (SECRET)
FacebookSession::setDefaultApplication($appid ,$secret);

// login helper with redirect_uri
$helper = new FacebookRedirectLoginHelper( 'http://www.metah.ch/' );

  // In case it comes from a redirect login helper
  $session = $helper->getSessionFromRedirect();
catch( FacebookRequestException $ex ) 
  // When Facebook returns an error
  echo $ex;
catch( Exception $ex ) 
  // When validation fails or other local issues
  echo $ex;

// see if we have a session in $_Session[]
if( isset($_SESSION['token']))
	// We have a token, is it valid? 
	$session = new FacebookSession($_SESSION['token']);	
		$session->Validate($appid ,$secret);
	catch( FacebookAuthorizationException $ex)
		// Session is not valid any more, get a new one.
		$session ='';

// see if we have a session
if ( isset( $session ) ) 
	// set the PHP Session 'token' to the current session token
	$_SESSION['token'] = $session->getToken();
	// SessionInfo 
	$info = $session->getSessionInfo();	
	// getAppId
	echo "Appid: " . $info->getAppId() . "<br />"; 
	// session expire data
	$expireDate = $info->getExpiresAt()->format('Y-m-d H:i:s');
	echo 'Session expire time: ' . $expireDate . "<br />"; 
	// session token
	echo 'Session Token: ' . $session->getToken() . "<br />"; 
  // show login url
  echo '<a href="' . $helper->getLoginUrl() . '">Login</a>';

The session expire time (getExpiresAt()) can be used to monitor how long the token can be used and potentially request a new token.

Splitting large CSV in smaller CSV

I had to use a tool today that gave me a frustrating error: “your csv file have more than a 1000 rows”. I had multiple CSVs that had more than 1000’s of rows actually, so splitting it manually would have been a total waste of time and sanity. That’s where PowerShell came in handy. As it took me more than 5 minutes to get the script right, I’m sharing it here.
The script is looking for all CSV’s within a defined folder ($location variable in the configuration), and split them by the number of rows defined in $rowsMax.
It is also removing the quotes in the CSV as by default export-csv generates quotes.

# Configuration
$location = "C:\csvdrop\" # CSVs location
$rowsMax = 900; # how many rows per CSV?

# Get all CSV under current folder
$allCSVs = Get-ChildItem $location\* -include *.csv

# Read and split all of them
$allCSVs | ForEach-Object {
Write-Host $_.Name;
$content = Import-Csv $_.Name;
$insertLocation = ($_.Name.Length - 4);
for($i=1; $i -le $content.length ;$i+=$rowsMax){
$newName = $_.Name.Insert($insertLocation, "splitted_"+$i)
$content|select -first $i|select -last $rowsMax | convertto-csv -NoTypeInformation | % { $_ -replace '"', ""} | out-file $location\$newName -fo -en ascii

Hopefully, this works for you too!

The week in search advertising 3/15/2014

Episode #3 of the weekly review of search adverting! Covering the week ending on 3/15/2014.

  • Native Ads are not engaging readers
    • Some data shows that native ads are not getting as much attention from the visitors
    • This can be somewhat improved if the ad creative is of good quality
    • Source: marketing land
  • Twitter experiment on click to call ads
  • Native ad spotted on The Wall Street Journal
    • Transparent, quality, and rare
    • Source: Digiday
  • Google experiment desktop to mobile retargeting
    • As cookies don’t really work on mobile devices, they use a “hashed tag” dropped when a user visit the advertiser’s site that ties to the cookies and device of the user.
    • Source: Ad Age
  • Addressing the Bing dilemma
    • 1/3 of all US search traffic goes to the Yahoo Bing Network.
    • There is a revenue opportunity to advertise on Bing (disclaimer: I work for Bing Ads)
    • Source: Search Engine Land
  • Facebook is showing autoplay advertising video
    • Facebook is willing to display only quality video, and will have a company gauges the commercials
    • Source: Business Insiders
  • Ads Worth Spreading
    • Some beautiful ads, for the creative folks J
    • Source: Ted

The week in online advertising (ending 3/9/2014)

I’m slightly increasing the scope of this series to capture a larger part of the online advertising (instead of focusing on search advertising only).

  • Focusing on mobile is solving yesterday’s problems
    • The focus should now be on ads that work across multiple screens
    • Focusing on reach is where we are trending today
    • Source: Forbes
  • 8 ways to write terrible online ads
    • Blindly using keyword insertion
    • Relying too much on broad keywords
    • Forgetting to spell check your ads
    • Using abbreviations to save space
    • Using technical jargon
    • Including your company name in the headline
    • Using superlatives
    • Don’t promise what you can’t deliver
    • Source: Entrepreneur
  • The good, the bad, and the ugly from last night’s Oscars real-time marketing
  • Why publishers are moving away from mobile banner ads and toward cross-device formats
    • 300×250 ad unit works well on all platforms
    • Placement should be automated, smaller screens tend to have more real estate available on mobile
    • Source: Digiday
  • Apple rolling out full screen video ads within apps
    • Interstitials video might pop-up while you are using your apps on iPhone or iPad (probably at a transition time)
    • This will probably be sold through Apple new ad exchange
    • Source: Advertising Age
  • How to take advantage of YouTube Pre-Roll ads
  • Does more targeting work better?
    • Interesting discussion on the future of targeting and its usage
    • Data shows that the user context (search vs social) impact his response to targeting / advertising
    • Source: Search Engine Land
  • How internet ads works
  • Instagram strikes first big ad deal
    • It was announced a while back and now it’s official, Instagram will be displaying ads
    • Source: Marketing Land

The week in search advertising

I decided to start a new series on this blog about what happened in the small world of search advertising during the week. It will mostly be a collection of links to interesting articles. The primary goal, for me, is to retrieve quickly articles. I hope this series will be useful for more people than just me!

  • How Facebook knows what you looked at on Amazon
    • Simple explanation on how FBX works
    • Source: 25hoursaday
  • Facebook is rolling out new targeting mechanics, the new options are:
    • Location (country & city; country & state; state & city; state & zip code)
    • Demographic (relationship status; life events as relationship status)
    • Interests (people interested in a topic – supposedly better than categories and keywords targeting)
    • Behaviors (based on offline activates: purchases, website visits)
    • Source: marketing land
  • Ad tech merger and acquisition will rage on 2014
  • WTF is ad viewability
    • Interesting discussion on the problem of displaying ads on some part of a site that is not actually viewed by the visitor (think the bottom of a site).
    • Source: Digiday
  • How to build effective mobile in-apps ads without irking your users
    • Advises for native advertising (embedding ads within the content)
    • .01% of apps will generate revenue
    • Source: TNW
  • The Ad Industry Reinvents the Hyperlink for the mobile Era
    • How advertiser are thinking of expending the hyperlink to be within Apps
    • Source: MIT TR

Some competition in the contextual ads landscape, finally!

I am quite happy to have received an invite to the Yahoo! | Bing network contextual ads (powered by media.net). I just migrated my websites to use these ads.
I don’t have yet information regarding the profitability of this network, I should be able to come back with some numbers in a couple of weeks (or month given the frequency of my posts on this blog J).

Setting up ads is super easy, if you are already familiar with AdSense, it should not be a problem at all. Setup your ad unit, copy the code to your website, and start getting paid.

If you are looking for an invite, this is the way: http://contextualads.yahoo.net/

Preparing my next certification (with uCertify)

I have been thinking for a while about my next certification, however I wasn’t able to find one certification where the courses would not overlap too much with my work or my family life. Luckily, I have been contacted by uCertify to review their tool, and was offered access to one course! I decided to give a try to the PMI – Project Management Professional (V5) certification.

The site is designed to help you get your certification, they have a lot of tools bundled under the uCertify site that makes it a great companion for any certification you might plan for.
The course site is divided into 7 categories and 3 tickers.

Pre-assessment, help you identify early on what areas you need improvement before you even begin the course.
Chapters & Lessons, is the course material (the PMPBOK v5 in my case) with nice functionalities to annotate and bookmark pages.

Exercises, Flashcards, and quizzes, is the place where I am actually spending most of my time. It is a great way to train for the exam! Flashcards prepares you for each chapters potential questions and give great sample answers.
Practice Tests, this is the simulated environment for the exam. 600 questions, I feel it will wait for a rainy Sunday (which happen quite frequently in Seattle during fall) to complete this.
Post assessment, this is the actual test, you need to get at least 90% to confirm your mastery. This should be done only when all above categories are completed. Once you get all answers correct, you can go ahead and do the real test (at the test center).
Videos, multiple videos on some of the chapters and lessons of your certification.
Glossary, this is a great place to get a quick definition of some terms. The annotation functionality is also available.


Target, this ticker enable you to track how much more you need to work to reach your targeted based on the progress you are making on each category. This is an extremely motivating factor.
If you click on it, you can access a detailed view (study planner) of your progress and step by step ‘coaching’ advices to help stay on track and increase your chance of passing the test.

Certificate of Completion, will allow you to have a virtual certificate once you are ready for the test.
Test history & performance analytics, is a report that help gauging the progress and our focus (with visualization tools showing how much time you spend working, what you have been working on, and when you have been mostly working).

Overall, I feel confident that this site will help me get my certification, eventually. At least it gives me enough flexibility and enough tools so I can prepare well.