Upload image/video to facebook asynchronously usin

2019-06-05 03:03发布

I am trying to upload video/image to facebook albumb using php sdk 4 asynchronously.I googled and found that php asynchronous call be sent using fsockopen. However, it is not working for facebook request. I have two files, one for checking login and getting token. Then second file is called for uploading the file to facebook. Below is the code for first file:

// start session
session_start();

Yii::import('application.vendor.*');
require_once('facebook-4/autoload.php');

use Facebook\HttpClients\FacebookHttpable;
use Facebook\HttpClients\FacebookCurl;
use Facebook\HttpClients\FacebookCurlHttpClient;

use Facebook\Entities\AccessToken;
use Facebook\Entities\SignedRequest;

use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
use Facebook\FacebookResponse;
use Facebook\FacebookSDKException;
use Facebook\FacebookRequestException;
use Facebook\FacebookOtherException;
use Facebook\FacebookAuthorizationException;
use Facebook\GraphObject;
use Facebook\GraphSessionInfo;


// init app with app id and secret
FacebookSession::setDefaultApplication('xxxxx', 'yyyy');

// login helper with redirect_uri
$helper = new FacebookRedirectLoginHelper( 'http://website.com/user/login/page/view/fb-share-php1' );

// see if a existing session exists
if ( isset( $_SESSION ) && isset( $_SESSION['fb_token'] ) ) {
    // create new session from saved access_token
    $session = new FacebookSession( $_SESSION['fb_token'] );
    // validate the access_token to make sure it's still valid
    try {
        if ( !$session->validate() ) {
            $session = null;
        }
    }catch ( Exception $e ) {
        // catch any exceptions
        $session = null;
    }
}

if ( !isset( $session ) || $session === null ) {
    // no session exists
    try {
        $session = $helper->getSessionFromRedirect();
    } catch( FacebookRequestException $ex ) {
    // When Facebook returns an error
    // handle this better in production code
    print_r( $ex );
    } catch( Exception $ex ) {
        // When validation fails or other local issues
        // handle this better in production code
        print_r( $ex );
    }
}

// see if we have a session
if ( isset( $session ) ) {
    // save the session
    $_SESSION['fb'] = $session;
    $_SESSION['fb_token'] = $session->getToken();
    // create a session using saved token or the new one we generated at login
    //$session = new FacebookSession( $session->getToken() );
    // graph api request for user data
    //$request = new FacebookRequest( $session, 'GET', '/me' );
    //$response = $request->execute();
    backgroundPost('http://website.com/user/login/page/view/fb-share-php');
    // get response
    //$graphObject = $response->getGraphObject()->asArray();
    // print profile data
    //echo '<pre>' . print_r( $graphObject, 1 ) . '</pre>';
    // print logout url using session and redirect_uri (logout.php page should destroy the session)
    echo '<a href="' . $helper->getLogoutUrl( $session, 'http://website.com/user/login/page/view/fb-share-php1' ) . '">Logout</a>';
}else {
    // show login url
    echo '<a href="' . $helper->getLoginUrl( array( 'email', 'user_friends' ) ) . '">Login</a>';
}
function backgroundPost($url){
    $parts=parse_url($url);
    //print_r($parts);exit;

    $fp = fsockopen($parts['host'],
            isset($parts['port'])?$parts['port']:80,
            $errno, $errstr, 30);

    if (!$fp) {
        echo "test";
        return false;
    } else {
        $out = "POST ".$parts['path']." HTTP/1.1\r\n";
        $out.= "Host: ".$parts['host']."\r\n";
        $out.= "Content-Type: application/x-www-form-urlencoded\r\n";
        $out.= "Content-Length: ". 0 ."\r\n";
        $out .= "Cookie: PHPSESSID=" . $_COOKIE['PHPSESSID'] . "\r\n";
        $out .= "Connection: Close\r\n\r\n";
        if (isset($parts['query'])) $out.= $parts['query'];
        // print_r($out);exit;
        fwrite($fp, $out);
        fclose($fp);
        return true;
    }
}

And second file is:

 // start session
session_start();
Yii::import('application.vendor.*');
require_once('facebook-4/autoload.php');

use Facebook\HttpClients\FacebookHttpable;
use Facebook\HttpClients\FacebookCurl;
use Facebook\HttpClients\FacebookCurlHttpClient;

use Facebook\Entities\AccessToken;
use Facebook\Entities\SignedRequest;

use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
use Facebook\FacebookResponse;
use Facebook\FacebookSDKException;
use Facebook\FacebookRequestException;
use Facebook\FacebookOtherException;
use Facebook\FacebookAuthorizationException;
use Facebook\GraphObject;
use Facebook\GraphSessionInfo;



$session = $_SESSION['fb'] ;
file_put_contents('file.txt', serialize($session));
try {

    // Upload to a user's profile. The photo will be in the
    // first album in the profile. You can also upload to
    // a specific album by using /ALBUM_ID as the path
    $response = (new FacebookRequest(
            $session, 'POST', '/me/photos', array(
                    'source' => '@/var/www/website-root/images/add_more.png',
                    'message' => 'User provided message'
            )
    ))->execute()->getGraphObject();
    file_put_contents('files.txt', serialize($session));
    // If you're not using PHP 5.5 or later, change the file reference to:
    // 'source' => '@/path/to/file.name'

    //echo "Posted with id: " . $response->getProperty('id');

} catch(FacebookRequestException $e) {

    echo "Exception occured, code: " . $e->getCode();
    echo " with message: " . $e->getMessage();

}

1条回答
做个烂人
2楼-- · 2019-06-05 03:40

Finally, I figured out the way to achieve it. Now, I am using facebook javascript sdk with php sdk. Following is the process:

1)Get access token from javascript sdk(first file) and pass it to background along with the url of image/video. Code may be modified, if image/video is being uploaded through source.

2) php file(2nd file) containing function for executing backend-process(which is in third file) receives the posted data and and call the third file(in the form of url) and pass the data to it as well.

3) File(s) are uploaded to facebook through php sdk 4(third file)

Below is the code for first file containing javascript sdk code:

    <script> 

      (function(d, s, id){
         var js, fjs = d.getElementsByTagName(s)[0];
         if (d.getElementById(id)) {return;}
         js = d.createElement(s); js.id = id;
         js.src = "//connect.facebook.net/en_US/sdk.js";
         fjs.parentNode.insertBefore(js, fjs);
       }(document, 'script', 'facebook-jssdk'));
        window.fbAsyncInit = function() {
        FB.init({
          appId      : 'your app id',
          xfbml      : true,
          version    : 'v2.0'
        });
        FB.login(function(response){
            console.log(response);
            if (response.status === 'connected') {
                var data = new Array();

                alert('Logged into your app and Facebook.');
                //type: 0 for photo and type:1 for video. Create data array dynamically for real word applications
                data[0]= {url: 'http://url-of-video-file.mov',privacy : 'SELF', message: "title of video", type:1};
                data[1]= {url: 'http://url-to-image-file.png',privacy : 'SELF', message: "photo caption", type:0};
                $.ajax({
                    url: 'http://url-of-second-file/containing-code-for/backend-process',
                    data: {data: data, accessToken:response.authResponse.accessToken},
                    type: 'POST',
                    success:function(){
                        alert("photo uploaded");
                    }

                });


        },{scope:'email'});
    }

</script>

Now code of second file which receives data and execute back-end process:

<?php

//session_start();
ignore_user_abort(true);
set_time_limit(0);

function backgroundPost($url){
    $parts=parse_url($url);
    //print_r($parts);exit;

    $fp = fsockopen($parts['host'],
            isset($parts['port'])?$parts['port']:80,
            $errno, $errstr, 30);

    if (!$fp) {
        echo "test";
        return false;
    } else {
        $vars = $_POST;

        $content = http_build_query($vars);
        //file_put_contents('url.txt',$content);exit;
        $out = "POST ".$parts['path']." HTTP/1.1\r\n";
        $out.= "Host: ".$parts['host']."\r\n";
        $out.= "Content-Type: application/x-www-form-urlencoded\r\n";
        $out.= "Content-Length: ". strlen($content) ."\r\n";
        //$out .= "Cookie: PHPSESSID=" . $_COOKIE['PHPSESSID'] . "\r\n";
        $out .= "Connection: Close\r\n\r\n";
        if (isset($parts['query'])) $out.= $parts['query'];
        // print_r($out);exit;


        fwrite($fp, $out);
        fwrite($fp,$content);
        fclose($fp);
        return true;
    }
}
backgroundPost('http://link-to-third-file/containing-code-for-facebook-upload');

Now code of third file, which will actually upload the files. Please note, video files need to be downloaded before it can be uploaded.

<?php 

// start session
//session_start();
error_reporting(1);
ignore_user_abort(true);
set_time_limit(0);
@ini_set('display_errors', 1);


//include facebook library through autoload
require_once('facebook-4/autoload.php');

use Facebook\HttpClients\FacebookHttpable;
use Facebook\HttpClients\FacebookCurl;
use Facebook\HttpClients\FacebookCurlHttpClient;

use Facebook\Entities\AccessToken;
use Facebook\Entities\SignedRequest;

use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
use Facebook\FacebookResponse;
use Facebook\FacebookSDKException;
use Facebook\FacebookRequestException;
use Facebook\FacebookOtherException;
use Facebook\FacebookAuthorizationException;
use Facebook\GraphObject;
use Facebook\GraphSessionInfo;

// init app with app id and secret
FacebookSession::setDefaultApplication('app_id','secret_key' );
$session = new FacebookSession( $_POST['accessToken'] );

foreach($_POST['data'] as $key => $data){
    if($data['type'] == 1){
        $ext = substr($data['url'],strrpos($data['url'],'.'));
        $file = '/path/to/temp/location/for/saving/video/'.time().$ext;
        if(file_put_contents($file,file_get_contents($data['url']))){
            try {

                // Upload to a user's profile. The photo will be in the
                // first album in the profile. You can also upload to
                // a specific album by using /ALBUM_ID as the path
                $response = (new FacebookRequest(
                        $session, 'POST', '/me/videos', array(
                                'source' =>  '@'.$file,
                                'title' => $data['message'],
                                'privacy' => json_encode(array('value' => $data['privacy'])),
                                'published' => true
                        )
                ))->execute()->getGraphObject()->asArray();

                // If you're not using PHP 5.5 or later, change the file reference to:
                // 'source' => '@/path/to/file.name'

                //echo "Posted with id: " . $response->getProperty('id');

            } catch(FacebookRequestException $e) {

                echo "Exception occured, code: " . $e->getCode();
                echo " with message: " . $e->getMessage();
            }
        }
    }else{
        try {

            // Upload to a user's profile. The photo will be in the
            // first album in the profile. You can also upload to
            // a specific album by using /ALBUM_ID as the path
            $response = (new FacebookRequest(
                    $session, 'POST', '/me/photos', array(
                            'url' =>  $data['url'],
                            'message' => $data['message'],
                            'privacy' => json_encode(array('value' => $data['privacy'])),
                            'published' => true
                    )
            ))->execute()->getGraphObject()->asArray();

            // If you're not using PHP 5.5 or later, change the file reference to:
            // 'source' => '@/path/to/file.name'

            //echo "Posted with id: " . $response->getProperty('id');

        } catch(FacebookRequestException $e) {

            echo "Exception occured, code: " . $e->getCode();
            echo " with message: " . $e->getMessage();
        }
    }
}
    ?>
查看更多
登录 后发表回答