1

Я пытаюсь загрузить видео/изображения на Facebook albumb с помощью PHP SDK 4 asynchronously.I гугле и нашел, что PHP асинхронный вызов направляется с помощью fsockopen. Однако он не работает для запроса facebook. У меня есть два файла: один для проверки входа и получения токена. Затем вызывается второй файл для загрузки файла в facebook. Ниже приведен код для первого файла:Загрузить изображение/видео facebook асинхронно с использованием PHP SDK 4

// 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; 
    } 
} 

И второй файл:

// 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(); 

} 

ответ

0

Наконец, я понял, способ ее достижения. Теперь я использую javascript sdk в facebook с php sdk. Ниже приведен процесс:

1) Получить токен доступа из javascript sdk (первый файл) и передать его на задний план вместе с URL-адресом изображения/видео. Код может быть изменен, если изображение/видео загружается через источник.

2) Файл php (2-й файл), содержащий функцию для выполнения бэкэнд-процесса (который находится в третьем файле), получает размещенные данные и вызывает третий файл (в виде URL-адреса) и передает данные ему как Что ж.

3) Файл (ы) будут загружены в facebook через PHP SDK 4 (третий файл)

Ниже приведен код для первого файла, содержащего яваскрипт кода SDk:

<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> 

Теперь код второго файла который получает данные и выполняет внутренний процесс:

<?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'); 

Теперь код третьего файла, который фактически загрузит файлы. Обратите внимание, что видеофайлы необходимо загружать, прежде чем их можно будет загрузить.

<?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(); 
     } 
    } 
} 
    ?> 
Смежные вопросы