Search code examples
phpfacebook-php-sdkfacebook-sdk-4.0save-image

Saving User's Profile Picture from facebook API - PHP SDK V.5


Scenario: I am working on an app through which i need to download the user's profile picture from Facebook, apply a specific filter and then re-upload and set it as profile picture, which is possible using this trick. 'makeprofile=1'

http://www.facebook.com/photo.php?pid=xyz&id=abc&makeprofile=1 

Problem: So the problem i am facing is while downloading the picture from the received URL via API. I am obtaining the picture URL this way:

$request = $this->fb->get('/me/picture?redirect=false&width=9999',$accessToken); // 9999 width for the desired size image

// return object as in array form
$pic = $request->getGraphObject()->asArray();

// Get the exact url
$pic = $pic['url'];

Now i want to save the image from obtained URL to a directory on my server, so that i can apply the filter and re-upload it. When i use file_get_contents($pic) it throws following error

file_get_contents(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed 

I have tried a few other methods as well but could not get this fixed. Any help would be appreciated :)

NOTE: I am doing this through Codeigniter and on localhost for now.


Solution

  • So i found the solution myself and decided to answer so that if that can help someone else facing the same problem.

    We need to pass a few parameters to the file_get_contents() function

    $arrContextOptions=array(
                    "ssl"=>array(
                        "verify_peer"=>false,
                        "verify_peer_name"=>false,
                    ),
    );
    $profile_picture = @file_get_contents($profile_picture, false, stream_context_create($arrContextOptions));
    // Use @ to silent the error if user doesn't have any profile picture uploaded
    

    Now the $profile_picture has the picture, we can save it anywhere in the following way.

    $path = 'path/to/img';  //E.g assets/images/mypic.jpg
    
    file_put_contents($path, $profile_picture); 
    

    That's all :-)