Upload image / video to facebook asynchronously using php sdk 4

I am trying to upload a video / image to facebook albumb using php sdk 4 asynchronously.I googled and found that php asynchronous call will be sent using fsockopen . However, it does not work for facebook request. I have two files: one for checking the input and receiving the token. Then a second file is called to upload the file to facebook. Below is the code for the 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 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 the second 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; $session = $_SESSION['fb'] ; file_put_contents('file.txt', serialize($session)); try { // Upload to a user 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
source share
1 answer
Finally, I figured out how to achieve this. Now I am using javascript sdk on facebook with php sdk. The following is the process:

1) Get the access token from javascript sdk (first file) and transfer it to the background along with the image / video URL. The code can be changed if the image / video is downloaded through the source.

2) php file (2nd file), containing a function for executing the backend process (which is in the third file), receives the published data and calls the third file (in the form of a URL) and transfers data to it.

3) The file is uploaded to facebook via php sdk 4 (third file)

Below is the code for the first file containing the 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 the code of the second file that receives the data and executes the internal 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 the code for the third file, which will actually download the files. Please note that video files must be downloaded before they can be downloaded.

 <?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 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 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(); } } } ?> 
0
source

Source: https://habr.com/ru/post/969757/


All Articles