July 16, 2014 2:53 am

How to upload image on Facebook with Graph API using PHP

On demand of my readers I have written this tutorial on how can you upload an Image on Facebook using Graph API. This tutorial is a simple and easy to integrate on your website, we have already covers many features of Facebook Graph API like status of user or Page oAuth Login etc. This tutorial contains a live demo and complete demo source code download for free.

How to upload image on Facebook with Graph API using PHP

[wpdm_file id=107]DEMO

For its implementation and app creation you need to refer my previous tutorial How to Login with Facebook Graph API in PHP in this tutorial I have explained that how to create an app and configure it so you must check this before implementing this tutorial for complete understanding.

PHP Code

<?php
session_start();
require 'src/config.php'; // application credential open this file and add your app credentials and call back url
require 'src/facebook.php';

$facebook = new Facebook(array(
  'appId'  => $config['App_ID'],
  'secret' => $config['App_Secret'],
  'cookie' => true
)); // create Object of Facebook


if(isset($_POST['upload']))
{
    $target = "upload/";
    $allowedTypes = array(IMAGETYPE_PNG, IMAGETYPE_JPEG, IMAGETYPE_GIF);
    $detectedType = exif_imagetype($_FILES['file']['tmp_name']);
    if(!in_array($detectedType, $allowedTypes))
    {
        $message = "Invalid File.";
    }
    else
    {
        $target = $target . basename( $_FILES['file']['name']) ; 
        if(move_uploaded_file($_FILES['file']['tmp_name'], $target)) 
        {
            try
            {
                $image['access_token']  = $_SESSION['token'];
                $image['message']       = 'Upload this image using www.phpgang.com tutorial demo!!';
                $image['image']         = '@'.realpath("upload/".$_FILES['file']['name']);
                $facebook->setFileUploadSupport(true);
                $img = $facebook->api('/me/photos', 'POST', $image);
                $message = "Image Uploaded on facebook <a href='https://www.facebook.com/photo.php?fbid=10202356836865359".$img['id']."' target='_blank'>Click Here</a> to view!!";
            }
            catch(FacebookApiException $e)
            {
                $message = "Sorry, there was a problem uploading your file please try again.";
            }
        } 
        else
        {
            $message = "Sorry, there was a problem uploading your file please try again.";
        }
    }
    $content = '
    <style>
    #form
    {
        margin-left:auto;
        margin-right:auto;
        width: 220px;
    }
    </style>
    
    <form action="index.php" id="form" method="post" enctype="multipart/form-data" >
    <div>'.$message.'</div><br><br>
    <input type="file" name="file" /><br />
    <input type="submit" name="upload" value="  U P L O A D  " style="padding: 5px;" />
    <form>';
}
elseif(isset($_GET['fbTrue']))
{
    $token_url = "https://graph.facebook.com/oauth/access_token?"
       . "client_id=".$config['App_ID']."&redirect_uri=" . urlencode($config['callback_url'])
       . "&client_secret=".$config['App_Secret']."&code=" . $_GET['code']; 

    $response = file_get_contents_curl($token_url);

    $params = null;
    parse_str($response, $params);
    $_SESSION['token'] = $params['access_token'];
    
    $content = '
    <style>
    #form
    {
        margin-left:auto;
        margin-right:auto;
        width: 220px;
    }
    </style>
    <form action="index.php" id="form" method="post" enctype="multipart/form-data" >
    <input type="file" name="file" /><br />
    <input type="submit" name="upload" value="  U P L O A D  " style="padding: 5px;" />
    <form>';
     
}
else
{
    $content = '<a href="https://www.facebook.com/dialog/oauth?client_id='.$config['App_ID'].'&redirect_uri='.$config['callback_url'].'&scope=email,user_likes,publish_stream"><img src="./images/login-button.png" alt="Sign in with Facebook"/></a>';
}

echo $content;


function file_get_contents_curl($url) { // function used to replace file_get_content and fopen
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //Set curl to return the data instead of printing it to the browser.
    curl_setopt($ch, CURLOPT_URL, $url);

    $data = curl_exec($ch);
    curl_close($ch);

    return $data;
}
?>

First of all this script shows you Facebook connect button when you click on it it will ask you for permission as shown in our tutorial How to Login with Facebook Graph API in PHP, after your authentication it will redirect to the same page with input field and an upload button. When you upload image it will save that image on server and after that it will run the Facebook image upload function with that image path.

$image['access_token']  = $_SESSION['token'];
$image['message']       = 'Upload this image using www.phpgang.com tutorial demo!!';
$image['image']         = '@'.realpath("upload/".$_FILES['file']['name']);
$facebook->setFileUploadSupport(true);
$img = $facebook->api('/me/photos', 'POST', $image);

The above code is used to upload image on facebook its very simple and easy to understand $image is an array contains access token, image path and message of image.  $facebook->setFileUploadSupport(true); used to set application for upload image, $facebook->api(‘/me/photos’, ‘POST’, $image); this function used to post image to /me/photos area.

[wpdm_file id=107]DEMO

I hope this tutorial helps you in your application please don’t forget to share it with your friends and subscribe or follow us on Twitter and Facebook for more updates.

Author Huzoor Bux

I am Huzoor Bux from Karachi (Pakistan). I have been working as a PHP Developer from last 5+ years, and its my passion to learn new things and implement them as a practice. Basically I am a PHP developer but now days exploring more in HTML5, CSS and jQuery libraries.


Tutorial Categories:

11 responses to “How to upload image on Facebook with Graph API using PHP”

  1. fondillusions says:

    Hi, this is for the old facebook sdk. Do you know how to do the same thing but using the latest facebook sdk? Thanks

  2. ashulbha12 says:

    when i upload the image it show this error : Call to undefined function exif_imagetype()

  3. Amit says:

    When i uploaded image then it gives #324 (Requires uploaded file) error plz help me sir.

  4. Jatin Gupta says:

    Its works without SSL server on normal shared hosting or must required SSL server?

  5. Max John says:

    I have just tested it on your server through the demo and after the upload, Facebook said

    This content is currently unavailable
    The
    page you requested cannot be displayed right now. It may be temporarily
    unavailable, the link you clicked on may have expired, or you may not
    have permission to view this page.

  6. Deepak Gautam says:

    Sorry, there was a problem uploading your file please try again.

    error when i upload png format pic

  7. Roshan says:

    Sorry, there was a problem uploading your file please try again.

Leave a Reply

Your email address will not be published. Required fields are marked *