Facebook Integration in Codeigniter framework

Now day, for many social media application there is requirement that what we write in application should directly posted to Facebook. We can say – sharing things on Facebook with custom application. I search many thing for PHP CodeIgniter frame work, but it’s integration seems to be difficult. I found a simple solution for Facebook Integration in Codeigniter framework by combining CURL, AUTH and CODEIGNITER. You can easily set this code in your CodeIgniter files. You can use this code for your Front End, Back End or Web services effectively and post your thoughts, Images, videos on Facebook. For that you need to follow few steps and done!

PHASE I: Making Facebook Application

Initially, you should know how to create Facebook application. It is quite simple, just you must have account in Facebook.

Visit : https://developers.facebook.com/apps     and get registered yourself as Developer.

For registration you need to verify your account.

Complete all three steps for registration, and give all rights to application to have full control.

Once it completes, you can see Create New App button to top-right corner.

Now, you are Facebook application developer and can create your application.

You can see your application APP ID/API KEY and App Secrete Key. Using this, you can post/GET via this application. Still you need one more thing to post your stuff on Facebook that is ACCESS_TOKEN.

 https://developers.facebook.com/tools/explorer?method=GET&path=100001282354035%3Ffields%3Did%2Cname

From the above URL you can easily get your access token easily. Now, you can get access, update, and post anything on you r account with this access token. If you want to write on other person’s wall then you need to have his/her access token.

PHASE II: Facebook Integration in Codeigniter framework

Our point is to post directly on my Facebook wall throw other application using Codeigniter PH framework.

You need just copy simple code in your controller file, where you need this feature and put some file in your library folder and it’s done!

 

Step 1:

Copy files from library.zip and past to your library folder.

 

Step 2:

You need to load this library. You can directly load this in the controller file or you can set it “Autoload” by putting word’ facebook’ in config/autoload.php file.

$autoload['libraries'] = array(‘database’,’session’,’language’,‘facebook’);

Hence this library will be auto loaded.

Step 3: Controller file function.

function postToFaceBook($adduserThoughts){

extract($adduserThoughts);

$facebook = new Facebook(array(‘appId’ => Your application ID,’secret’ => Application secrete key));

// This model function bring stored access_token code from Database from userID.

$fbAccessToken=$this->activity_model->getFbAccessToken($userID);

// MSG

$msg=$vActivityText;

if($vIamAt!=””)$msg=$msg.” at “.$vIamAt;

if($vImWithflname!=””)$msg=$msg.” with “.$vImWithflname;

// IMAGES

if($vType_of_content==”game” && $vGameImageName!=””)

$picture=USER_IMAGE_PATH.’games/’.$vGameImageName;

elseif($vType_of_content==”image” && $vimageName!=””)

$picture=USER_IMAGE_PATH.’photogallary/’.$vimageName;

else

$picture=””;

 

if($vType_of_content==”video” && $vVideoName!=””)

$link=USER_IMAGE_PATH.’videos/’.$vVideoName;

else

$link=””;

 

if($fbAccessToken!=””){

try

{

$attachment = array(‘message’ =>$msg,

‘access_token’ =>$fbAccessToken,

‘link’ => $link,

‘name’ => “”,

‘description’ => “”,

‘picture’ =>$picture,

‘caption’=>””

);

$result = $facebook->api(‘/me/feed/’, ‘post’, $attachment);

$data['msg']=’msg posted successfully’;

}

catch(FacebookApiException $e)

{

$data['msg']=’cant post same msg again’;

}

}

else{

$data['msg']=’Access Token Null!’;

}

// echo json_encode($data);

}

 

Step 3.1: If you want to upload video/image and set format for captions,descriptions,name. Then you can use below controller function instead of previous one. The above code is useful only when if you want to show your post as a shared post.

 

function postToFaceBook($adduserThoughts){

// mprd($adduserThoughts);

extract($adduserThoughts);

$facebook = new Facebook(array(‘appId’ => ‘Ypur app ID’,’secret’ => ‘your app secret key’));

$fbAccessToken=$this->activity_model->getFbAccessToken($userID);

// MSG

$msg=$vActivityText;

// vIamAt is location name

if($vIamAt!=””)$msg=$msg.” at “.$vIamAt;

// vImWithflname is list first name of other friends/famility member/any one with me

if($vImWithflname!=””)$msg=$msg.” with “.$vImWithflname;

if(($vType_of_content==”activity” || $vType_of_content==”location” || $vType_of_content==”music”) && $profilePicfullPath!=””)

$picture=$profilePicfullPath;

else

$picture=””;

 

if($vType_of_content==”video” && $vVideoName!=””)

// USER_IMAGE_PATH is path where we store uploaded files

$link=USER_IMAGE_PATH.’videos/’.$vVideoName;

else

$link=””;

if($fbAccessToken!=””){

try

{

if($vType_of_content==”video”){

$file= “../admin/files/videos/$vVideoName”;

$args = array(

‘description’ => $vActivityText,’title’=>$vActivityText=”Video Posting Using YOUR APPLICATION NAME ”

);

$args[basename($file)] = ‘@’ . realpath($file);

$ch = curl_init();

$url = ‘https://graph.facebook.com/videos?access_token=’.$fbAccessToken;

curl_setopt($ch, CURLOPT_URL, $url);

curl_setopt($ch, CURLOPT_HEADER, false);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

curl_setopt($ch, CURLOPT_POST, true);

curl_setopt($ch, CURLOPT_POSTFIELDS, $args);

$data = curl_exec($ch);

//returns the photo id

// print_r(json_decode($data,true));

}

elseif($vType_of_content==”image”){

// echo “Hi”;exit;

// echo $file= USER_IMAGE_PATH.’photogallary/’.$vimageName;

$file= “../admin/files/photogallary/$vimageName”;

$args = array(

‘message’ => $vActivityText,’name’=>$vActivityText

);

$args[basename($file)] = ‘@’ . realpath($file);

$ch = curl_init();

$url = “https://graph.facebook.com/photos?access_token=$fbAccessToken”;

curl_setopt($ch, CURLOPT_URL, $url);

curl_setopt($ch, CURLOPT_HEADER, false);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

curl_setopt($ch, CURLOPT_POST, true);

curl_setopt($ch, CURLOPT_POSTFIELDS, $args);

$data = curl_exec($ch);

 

// print_r(json_decode($data,true));

}

elseif($vType_of_content==”location”){

$attachment = array(/*’message’ =>$data2['msg'],        */

‘message’ =>$vActivityText,

‘access_token’ =>$fbAccessToken,

‘link’ => “”,

‘name’ => $admin_fname.” via YOUR APPLICATION NAME”,

‘description’ => $msg,

‘picture’ =>$picture,

‘caption’=>” ”

);

// mprd($attachment);

$result = $facebook->api(‘/me/feed/’,’post’,$attachment);

$data['msg']=’msg posted successfully’;

}

elseif($vType_of_content==”music”){

$attachment = array(/*’message’ =>$data2['msg'],        */

‘message’ =>$vMusicName,

‘access_token’ =>$fbAccessToken,

‘link’ => “”,

‘name’ => $admin_fname.” via YOUR APPLICATION NAME “,

‘description’ => “Music :”.$msg,

‘picture’ =>$picture,

‘caption’=>” ”

);

// mprd($attachment);

$result = $facebook->api(‘/me/feed/’,’post’,$attachment);

$data['msg']=’msg posted successfully’;

}

else{

$attachment = array(/*’message’ =>$data2['msg'],        */

‘message’ =>$vActivityText,

‘access_token’ =>$fbAccessToken,

‘link’ => “”,

‘name’ => $admin_fname.” via YOUR APPLICATION NAME “,

‘description’ => $msg,

‘picture’ =>$picture,

‘caption’=>” ”

);

// mprd($attachment);

$result = $facebook->api(‘/me/feed/’,’post’,$attachment);

$data['msg']=’msg posted successfully’;

 

}

}

catch(FacebookApiException $e)

{

$data['msg']=’cant post same msg again’;

}

}

else{

$data['msg']=’Access Token Null!’;

}

// echo json_encode($data);

}

 

adduserThoughts array is parameter where we have grabbed REQUEST information that are coming from user. It includes userID, vType_of_content(could be text,image,video link, game with score), vActivityText(text what you post), vImWiths(email IDs to tag other users-it’s comma separated list of emailIDS).

Code use sample:  controller file

 

// ***************************************************************

            //1.  ADD TEXT THOUGHTS

    // ***************************************************************

    function addThoughts($adduserThoughts){

        extract($adduserThoughts);

        $addThoughtsResp=$this->activity_model->addUsersThoughts($adduserThoughts);       

        if($addThoughtsResp!=”)

        {  

            $settings=$this->getUserSetup($userID);

            if($settings['facebook']!=”Authenticate”)

                $PostToFaceBook=$this->postToFaceBook($adduserThoughts);

    }

I have used this code in many iPhone web-services. It works perfectly.

Tags:
3 Responses to “Facebook Integration in Codeigniter framework”
  1. [...] Just like Facebook Integration in Codeigniter framwork [...]

  2. [...] and link),I have discuss about sharing and posting text, photos and videos on Twitter & Facebook Integration in Codeigniter framework. In this post, we have another social media and that is [...]

  3. Rushik Kansara says:

    A PHP Error was encountered

    Severity: Warning

    Message: Missing argument 1 for Facebook::__construct(), called in F:\wamp\www\wallpaper_webservice\system\core\Loader.php on line 950 and defined

    Filename: libraries/facebook.php

    Line Number: 35

    —————————————————————————————-

    A PHP Error was encountered

    Severity: Notice

    Message: Undefined variable: config

    Filename: libraries/facebook.php

    Line Number: 39

    ———————————————————————-
    how to solve these errors?

    • Jaimin Vaja says:

      Hi Rushik,

      $facebook = new Facebook(array(‘appId’ => ‘your app id’,’secret’ => ‘your app secrete’));

      I think you have wrongly defined this one.
      Please refer library of facebook.php
      it’s necessary to set config array for facebook Lib.
      I have been using this Lib more than 1 and half year, it works great even right now.

      I have used same code for : http://www.facebook.com/suviapp application.

      Your error ,itself shows solution.

      Best of Luck

Leave a Reply