Facebook PHP SDK Starter Code


/ Published in: PHP
Save to your folder(s)

This is just a quick and dirty template that I use to begin writing my apps. If you know of a better way to approach various portions of this code I would love to hear it. It\'s assuming you are using the latest PHP SDK and is positioned around Iframe based application (though it works with FBML, I would just use AJAX calls to request auth as it\\\\\\\'s a little more seamless).


Copy this code and paste it in your HTML
  1. <?php
  2. //This is my skeleton template for a PHP SDK canvas app, use it if you find it useful.
  3. //Lately I use iframe canvas apps so I used a javascript page redirect instead of fbjs ajax with require_login();
  4.  
  5. //Don't forget to change path to PHP SDK if necessary
  6. require_once 'facebook.php';
  7. // Create our Application instance. Don't forget to change to your AppId and Secret
  8.  
  9. $facebook = new Facebook(array(
  10. 'appId' => 'XXXXXXXXXXXXX',
  11. 'secret' => 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
  12. 'cookie' => true,));
  13.  
  14. // Uncomment to debug post fields
  15. // print_r($_REQUEST);
  16.  
  17. // Setting canvas to 1 and fbconnect to 0 fixes issues with being redirected back to your base domain instead of back to the canvas app on auth
  18. $loginUrl = $facebook->getLoginUrl($params = array('canvas' => 1, 'fbconnect' => 0, 'req_perms' => 'insert required perms here'));
  19.  
  20. $session = $facebook->getSession();
  21. $me = null;
  22.  
  23. if ($session) {
  24. try {
  25. $me = $facebook->api('/me');
  26. //If user has authed application, render a logout link.
  27. //echo '<a href="'.$facebook->getLogoutUrl().'">Logout</a>';
  28. } catch(FacebookApiException $e){
  29. //Uncomment the line below to have a user click to authorize the app instead of requesting permissions on page load.
  30. //echo '<a href="'.$loginUrl.'">Login</a>';
  31. //Request permissions on page load if app is not authed & cannot request user information.
  32. echo "<script type='text/javascript'>top.location.href = '".$loginUrl."';</script>";
  33. error_log($e);
  34. }
  35. } else {
  36. //Request permissions on page load if app is not authed & or session is invalid.
  37. echo "<script type='text/javascript'>top.location.href = '".$loginUrl."';</script>";
  38. }
  39.  
  40. // If you can hit user on the Graph API, do some stuff
  41. if($me) {
  42.  
  43. }
  44.  
  45.  
  46.  
  47. ?>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.