【问题标题】:Facebook API sdk 4.0 - post a photo onto facebookFacebook API sdk 4.0 - 将照片发布到 Facebook
【发布时间】:2014-09-13 04:18:26
【问题描述】:

我正在尝试创建一个应用程序,用户可以在其中浏览并从他们的计算机将照片提交到他们的 Facebook 上。为此,他们首先必须将他们的照片上传到服务器,然后使用 facebook 请求,将这张图片发布到 facebook。我正在使用多部分/表单数据。

这是我到目前为止所拥有的,假设我有一个有效的会话,我的 api 请求:

$request = new Facebook{
$session,
'POST',
'/me/photos',
array (
    'source' => '{image-data}',
    )
    );
    $response = $request->execute();
    $graphObject = $response->getGraphObject();
    /* handle the result*/

我不确定用什么替换图像数据。

对于上传照片,我的代码如下:

   if(isset($_POST['submit'])){

$file_type = $_FILES['file']['type']; //returns the file type

$allowed = array("image/jpeg", "image/gif", "image/png", "image/jpg"); //specifies allowed file types
if(!in_array($file_type, $allowed)) {
        $error_message = 'Only jpeg, jpg, gif, and png files are allowed. <br> 
        Please click back and try again.';
        echo $error_message;

        exit();
    }

$name       = $_FILES['file']['name'];  //original path of the uploaded file
$temp_name  = $_FILES['file']['tmp_name'];  //contains the path to the temporary file that resides on the server
if(isset($name)){
    if(!empty($name)){      
        $location = 'uploads/'; //save photo to the folder: uploads
        if(move_uploaded_file($temp_name, $location.$name)){
            echo 'Photo was successfully uploaded.';
        }
    }       
}  else {
    echo 'Photo was unsuccessfully uploaded, click back and try again.';
 }
 }

我是 facebook api 的新手,也是编码新手。任何帮助或建议将不胜感激。谢谢。

完整代码:

     <?php

  require_once( 'Facebook/HttpClients/FacebookHttpable.php' );
  require_once( 'Facebook/HttpClients/FacebookCurl.php' );
  require_once( 'Facebook/HttpClients/FacebookCurlHttpClient.php' );

  require_once( 'Facebook/Entities/AccessToken.php' );
  require_once( 'Facebook/Entities/SignedRequest.php' );
  require_once( 'Facebook/FacebookSession.php' );
  require_once( 'Facebook/FacebookRedirectLoginHelper.php' );
  require_once( 'Facebook/FacebookRequest.php' );
  require_once( 'Facebook/FacebookResponse.php' );
  require_once( 'Facebook/FacebookSDKException.php' );
  require_once( 'Facebook/FacebookRequestException.php' );
  require_once( 'Facebook/FacebookServerException.php' );
  require_once( 'Facebook/FacebookOtherException.php' );
  require_once( 'Facebook/FacebookAuthorizationException.php' );
  require_once( 'Facebook/GraphObject.php' );
  require_once( 'Facebook/GraphSessionInfo.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\FacebookServerException;
  use Facebook\FacebookOtherException;
  use Facebook\FacebookAuthorizationException;
  use Facebook\GraphObject;
  use Facebook\GraphSessionInfo;


 // start session
 session_start();

// init app with app id and secret
FacebookSession::setDefaultApplication( 'xxxxxxxxxx','xxxxxxxxxxxxx' );

// login helper with redirect_uri
$helper = new FacebookRedirectLoginHelper( 'https://apps.facebook.com/myapp' );

// 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_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();
// get response
$graphObject = $response->getGraphObject()->asArray();



// print logout url using session and redirect_uri (destroy the session)
echo '<a href="' . $helper->getLogoutUrl( $session, 'http://localhost/app/index.php', session_destroy() ) .    '">Logout</a>';

} else {
  // show login url
  echo '<a href="' . $helper->getLoginUrl( array( 'email', 'user_friends', 'publish_actions' ) ) . '">Login</a>';

}


 ?>

  <html>
     <head>
        <title> My App</title>
    </head>

    <body>
    <div>


    <form method="post" enctype="multipart/form-data">
    Please select a photo to upload <input type="file" name="file" id="file"><br><br>
    <input type="submit" value="Upload" name="submit">

    </form>
    </div>

   </body>
 </html>
 <?php
    if(isset($_POST['submit'])){

    $file_type = $_FILES['file']['type']; //returns the file type

    $allowed = array("image/jpeg", "image/gif", "image/png", "image/jpg"); //specifies allowed file types
    if(!in_array($file_type, $allowed)) {
        $error_message = 'Only jpeg, jpg, gif, and png files are allowed. <br> 
        Please click back and try again.';
        echo $error_message;

        exit();
    }

     $name       = $_FILES['file']['name'];  //original path of the uploaded file
     $temp_name  = $_FILES['file']['tmp_name'];  //contains the path to the temporary file that resides on the server
     if(isset($name)){
     if(!empty($name)){      
        $location = 'uploads/'; //save photo to the folder: uploads
        if(move_uploaded_file($temp_name, $location.$name)){
            echo 'Photo was successfully uploaded.';
        }
    }       
 }  else {
    echo 'Photo was unsuccessfully uploaded, click back and try again.';
 }

$session = new FacebookSession( $_SESSION['fb_token']);
$request = new FacebookRequest(
 $session,
 'POST',
 '/me/photos',
 array (
    'source' => file_get_contents($location.$name),
 )
 );

  $response = $request->execute();
  $graphObject = $response->getGraphObject();
    print_r($response);
  }

    $token = $_GET['code'];
    echo $token;


     ?>

【问题讨论】:

    标签: php facebook facebook-graph-api facebook-sdk-4.0


    【解决方案1】:

    好的,您的代码有两个主要问题。

    第一

    从您的代码中删除 session_destroy()。这就是会话被删除的原因。然后,您可以从代码中删除 $session = new FacebookSession( $_SESSION['fb_token']); 的第二次使用。你只需要做一次!

    变化:

    echo '<a href="' . $helper->getLogoutUrl( $session, 'http://localhost/app/index.php', session_destroy() ) .    '">Logout</a>';
    

    echo '<a href="' . $helper->getLogoutUrl( $session, 'http://localhost/app/index.php' ) .    '">Logout</a>';
    

    第二次

    @ 附加到您的source,您会发现图片上传正确。例如:

    $request = new FacebookRequest(
      $session,
      'POST',
      '/me/photos',
      array (
        'source' => new CURLFile( $location.$name ),
      )
    );
    

    CURLFile 仅适用于 PHP 5.5+。对于早期版本的 PHP,将源设置为:

    'source' => '@' . $location.$name
    

    【讨论】:

    • 感谢您的回答。我仍然收到错误:不推荐使用:curl_setopt_array():不推荐使用@filename API 进行文件上传。请在第 66 行的 C:\xampp\htdocs\app\Facebook\HttpClients\FacebookCurl.php 中使用 CURLFile 类 致命错误:未捕获的异常 'Facebook\FacebookSDKException' 带有消息 'couldn't open file "uploads/983710_10154252423865510_7686584102535451506_n.jpg "' 在 C:\xampp\htdocs\app\Facebook\HttpClients......................
    • 我已经更新了我的答案,改为使用 CURLFile。此外,请确保上传文件夹和文件具有正确的权限以允许读取。我测试了 CURLFile 版本,它对我有用。
    • 我收到此错误:致命错误:未捕获异常 'Facebook\FacebookSDKException' 并在 C:\xampp\htdocs\app\Facebook 中显示消息“无法打开文件“uploads/983710_10154252423865510_7686584102535451506_n.jpg” \HttpClients\FacebookCurlHttpClient.php:142 堆栈跟踪:#0 C:\xampp\htdocs\app\Facebook\FacebookRequest.php(248): Facebook\HttpClients\FacebookCurlHttpClient->send('graph.f...', ' POST', Array) #1 C:\xampp\htdocs\app\index.php(180): Facebook\FacebookRequest->execute() #2 {main} 在 C:\xampp\htdocs\app\Facebook\HttpClients 中抛出\FacebookCurlHttpClient.php 在第 142 行。
    • 我已经检查了权限,文件夹和文件都允许读取......你知道它不适合我的任何其他原因吗?并感谢您将答案更改为使用 CURLFILE,我不知道如何将变量作为参数。
    • 可能是缺少 PHP CURL 扩展并且它正在使用 Facebook 客户端,这可能会导致问题。验证 CURL 是否已启用。
    【解决方案2】:

    假设用户已经正确上传了图片并且$location.$name是路径:

     $request = new FacebookRequest(
         $session,
         'POST',
         '/me/photos',
         array (
            'source' => file_get_contents($location.$name),
         )
      );
    
     $response = $request->execute();
     $graphObject = $response->getGraphObject();
    

    或者另一种可能性是通过 URL:

     $request = new FacebookRequest(
       $session,
       'POST',
       '/me/photos',
       array (
         'url' => $the_url_to_the_image,
       )
     );
    
     $response = $request->execute();
     $graphObject = $response->getGraphObject();
    

    您在上传后执行的 API 调用由用户完成,但这不过是合乎逻辑的。

    【讨论】:

    • 我认为语法是新的 CURLFIle...?反正我试过了。我在上传照片代码的最后两个大括号内执行了 api 请求,但出现错误:可捕获的致命错误:传递给 Facebook\FacebookRequest::__construct() 的参数 1 必须是 Facebook\FacebookSession 的实例,给定 null,调用在第 180 行的 C:\xampp\htdocs\app\index.php 中并在第 182 行的 C:\xampp\htdocs\app\Facebook\FacebookRequest.php 中定义。当我将它放在外面和之后时,我也会遇到同样的错误提交/上传代码。
    • 这不可能是会话问题,因为我能够在我的提要上发布消息..?
    • $session 未设置比。你能展示整个代码吗?
    • 嗯.. 但我能发消息?但是,是的,我会发布整个代码。 :) 感谢您的宝贵时间
    • 我感到困惑的另一件事是当我通过本地主机 url 加载页面时。我单击登录,您可以在我的 url 中看到代码,然后出现注销按钮。我浏览并上传了一张图片,然后注销按钮又回到了登录状态。现在,当我单击它时,我会被定向到一个空白页面。我很困惑。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-11
    • 2012-01-15
    • 1970-01-01
    • 1970-01-01
    • 2011-05-14
    • 2016-07-08
    相关资源
    最近更新 更多