Facebook connect using PHP

Posted: November 1, 2011 in PHP

index.php

<?php 
    include_once "fbmain.php";
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
        <title>FB PHP Connect Tutorial</title>
    
        <script type="text/javascript">
            function streamPublish(name, description, hrefTitle, hrefLink, userPrompt){  
				alert('streamPublish');
                FB.ui({ method : 'feed', 
                        message: userPrompt,
                        link   :  hrefLink,
                        caption:  hrefTitle,
                        picture: 'http://thinkdiff.net/ithinkdiff.png'
               });
               //http://developers.facebook.com/docs/reference/dialogs/feed/
   
            }
            function publishStream(){
				alert('publishStream');
                streamPublish("Stream Publish", 'Checkout iOS apps and games from iThinkdiff.net. I found some of them are just awesome!', 'Checkout iThinkdiff.net', 'http://ithinkdiff.net', "Demo Facebook Application Tutorial");
            }
            
            function newInvite(){
				alert('newInvite');
                 var receiverUserIds = FB.ui({ 
                        method : 'apprequests',
                        message: 'Come on man checkout my applications. visit http://ithinkdiff.net',
                 },
                 function(receiverUserIds) {
                          console.log("IDS : " + receiverUserIds.request_ids);
                        }
                 );
                 //http://developers.facebook.com/docs/reference/dialogs/requests/
            }
        </script>
    </head>
<body>
    
          <div id="fb-root"></div>
<script type="text/javascript">
    window.fbAsyncInit = function() {
        FB.init({appId: '172300909522869', status: true, cookie: true, xfbml: true});
    };
    (function() {
        var e = document.createElement('script');
        e.type = 'text/javascript';
        e.src = document.location.protocol +
            '//connect.facebook.net/en_US/all.js';
        e.async = true;
        document.getElementById('fb-root').appendChild(e);
    }());
	FB.api('/me', function(response) {
  alert(response.name);
});
	</script>
    <fb:login-button autologoutlink="true" perms="email,user_birthday,status_update,publish_stream"></fb:login-button>
<style type="text/css">
    .box{
        margin: 5px;
        border: 1px solid #60729b;
        padding: 5px;
        width: 500px;
        height: 200px;
        overflow:auto;
        background-color: #e6ebf8;
    }
</style>

<div id="fb-root"></div>
    <script type="text/javascript" src="http://connect.facebook.net/en_US/all.js"></script>
     <script type="text/javascript">
       FB.init({
         appId  : '<?=$fbconfig['appid']?>',
         status : true, // check login status
         cookie : true, // enable cookies to allow the server to access the session
         xfbml  : true  // parse XFBML
       });
       
     </script>
    
<br />
    <h3>PHP SDK 3.0 & Graph API base FBConnect Tutorial</h3>
     
    
<?php if (!$user) { ?>
        You've to login using FB Login Button to see api calling result.
       <!-- <a onClick="window.open('<?=$loginUrl?>','mywindow','location=1,status=1,scrollbars=1, width=500,height=500');" href="#">Facebook Login</a>-->
        <a href="<?=$loginUrl?>">Facebook Login</a><br><br>
        <?=$loginUrl?><br><br>
    <?php } else { ?>
        <a href="<?=$logoutUrl?>">Facebook Logout</a>
    <?php } ?>

    <!-- all time check if user session is valid or not -->
    <?php if ($user){ ?>
    <table border="0" cellspacing="3" cellpadding="3">
        <tr>
            <td>
                <!-- Data retrived from user profile are shown here -->
                <div class="box">
                    <b>User Information using Graph API</b>
                    <?php d($userInfo); ?>
                </div>
            </td>
            <td>           
                <div class="box">
                    <b>User likes these movies | using graph api</b>
                     <?php d($movies); ?>
                </div>
            </td>
        </tr>
        <tr>
            <td>
                <div class="box">
                    <b>Wall Post & Invite Friends</b>
                    <br /><br />
                    <a href="<?=$fbconfig['baseurl']?>?publish=1">Publish Post using PHP </a>
                    <br />
                    You can also publish wall post to user's wall via Ajax.
                    <?php if (isset($_GET['success'])) { ?>
                        <br />
                        <strong style="color: red">Wall post published in your wall successfully!</strong>
                    <?php } ?>
                        
                    <br /><br />
                    <a href="#" onClick="publishStream(); return false;">Publish Wall post using Facebook Javascript</a>
                    
                    <br /><br />
                    <a href="#" onClick="newInvite(); return false;">Invite Friends</a>
                </div>
            </td>
            <td>
                <div class="box">
                    <b>FQL Query Example by calling Legacy API method "fql.query"</b>
                    <?php d($fqlResult); ?>
                </div>
            </td>
        </tr>
    </table>
    <div class="box">
        <form name="" action="<?=$fbconfig['baseurl']?>" method="post">
            <label for="tt">Status update using Graph API</label>
            <br />
            <textarea id="tt" name="tt" cols="50" rows="5">Write your status here and click 'Update My Status'</textarea>
            <br />
            <input type="submit" value="Update My Status" />
        </form>
        <?php if (isset($statusUpdate)) { ?>
            <br />
            <strong style="color: red">Status Updated Successfully! Status id is <?=$statusUpdate['id']?></strong>
         <?php } ?>
    </div>
    <?php } 
	
	echo '<pre>';
	print_r($_SESSION);
	
	?>

    </body>
</html>

fbmain.php

<?php

    //facebook application
    $fbconfig['appid' ]     = "######";
    $fbconfig['secret']     = "######";
    $fbconfig['baseurl']    = "######"; //"http://siteurl/index.php";

    //
    if (isset($_GET['request_ids'])){
        //user comes from invitation
        //track them if you need
    }
    
    $user  =   null; //facebook user uid
    try{
        include_once "facebook.php";
    }
    catch(Exception $o){
        error_log($o);
    }
	
    // 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,offline_access,publish_stream,user_birthday,user_location,user_work_history,user_about_me,user_hometown',
                'redirect_uri'  => $fbconfig['baseurl']
            )
    );
    
    $logoutUrl  = $facebook->getLogoutUrl();
   

    if ($user) {
		
		//===== directlt post on wall =====
		/* $publishStream = $facebook->api("/$user/feed", 'post', array(
                    'message' => "I am adding some texts here for message.
									This is second line :)", 
                    'link'    => 'https://vibhajadwani.wordpress.com/',
                    'picture' => 'http://www.gravatar.com/avatar/e4598142bb62019e652a59b067f66ef2.png',
                    'name'    => 'Vibha Jadwani',
                    'description'=> 'This is my description text on '.date('Y-m-d h:i a').'.... <br /> I found some of them are just awesome! <br /> <strong>HTML BOLD</strong> tried..'
                    )
                );
		 echo 'posted';*/
		 
		 
      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 is logged in and session is valid.
    if ($user){
        //get user basic description
        $userInfo           = $facebook->api("/$user");
        
        //Retriving movies those are user like using graph api
        try{
            $movies = $facebook->api("/$user/movies");
        }
        catch(Exception $o){
            d($o);
        }
        
        //update user's status using graph api
        //http://developers.facebook.com/docs/reference/dialogs/feed/
        if (isset($_GET['publish'])){
            try {
                $publishStream = $facebook->api("/$user/feed", 'post', array(
                    'message' => "I am adding some texts here for message.
									This is second line :)", 
                    'link'    => 'https://vibhajadwani.wordpress.com/',
                    'picture' => 'http://www.gravatar.com/avatar/e4598142bb62019e652a59b067f66ef2.png',
                    'name'    => 'Vibha Jadwani',
                    'description'=> 'This is my description text.... <br /> I found some of them are just awesome! <br /> <strong>HTML BOLD</strong> tried..'
                    )
                );
                //as $_GET['publish'] is set so remove it by redirecting user to the base url 
            } catch (FacebookApiException $e) {
                d($e);
            }
            $redirectUrl     = $fbconfig['baseurl'] . '/index.php?success=1';
            header("Location: $redirectUrl");
        }

        //update user's status using graph api
        //http://developers.facebook.com/docs/reference/dialogs/feed/
        if (isset($_POST['tt'])){
            try {
                $statusUpdate = $facebook->api("/$user/feed", 'post', array('message'=> $_POST['tt']));
            } catch (FacebookApiException $e) {
                d($e);
            }
        }

        //fql query example using legacy method call and passing parameter
        try{
            $fql    =   "select name, hometown_location, sex, pic_square from user where uid=" . $user;
            $param  =   array(
                'method'    => 'fql.query',
                'query'     => $fql,
                'callback'  => ''
            );
            $fqlResult   =   $facebook->api($param);
        }
        catch(Exception $o){
            d($o);
        }
    }
    
    function d($d){
        echo '<pre>';
        print_r($d);
        echo '</pre>';
    }
?>

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s