Facebook API sdk 4.0 - 将照片发布到Facebook上 [英] Facebook API sdk 4.0 - post a photo onto facebook

查看:112
本文介绍了Facebook API sdk 4.0 - 将照片发布到Facebook上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个应用程序,用户可以从他们的电脑浏览照片并将其提交到他们的Facebook上。为此,他们将首先将他们的照片上传到服务器上,然后使用Facebook的请求,将该图像发布到Facebook上。我正在使用multipart / form-data。

I am trying to create an application where the user can browse and submit a photo from their computer onto their facebook. For this, they will first have to upload their photo onto the server and then using a facebook request, post this image onto facebook. I am using multipart/form-data.

这是我迄今为止所做的,假设我有一个有效的会话,我的api请求:

This is what I have so far for this, assuming I have a valid session, my api request:

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

我不知道如何替换图像数据与。

I am not sure what to replace image-data with.

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

For the uploading photo, my code is as follows:

   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,一个新手编码。任何帮助或建议将不胜感激。谢谢。

I am new to facebook api, and a novice at coding. Any help or advice will be much appreciated. Thanks.

整个代码:

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


     ?>


推荐答案

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

OK, there are two main issues with your code.

FIRST

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

Remove session_destroy() from your code. It's the reason why the session is being deleted. You can then remove the second use of $session = new FacebookSession( $_SESSION['fb_token']); from your code. You only need to do that bit once!

更改:

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

SECOND

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

Append @ to your source and you will find that the image uploads correctly. E.g.:

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

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

CURLFile only works on PHP 5.5+. For earlier version of PHP, set source to:

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

这篇关于Facebook API sdk 4.0 - 将照片发布到Facebook上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆