Facebook:php上传照片并张贴在墙上

时间:2011-03-02 17:04:50

标签: php facebook

php新手请原谅我的愚蠢问题。

我正在创建我的第一个fb应用。它允许用户浏览本地驱动器并选择照片。一旦提交,它将重定向到下一页并处理到存储到我的服务器上,然后发布到用户的墙上。

应用程序实际上并没有那么多。用户浏览和将照片存储到我的服务器上的应用程序正在运行,但它无法从我的服务器上取回照片并将其发布到用户的墙上。

的config.php:

 <?php
require_once 'facebook.php';

$app_id = "";
$app_key = "";
$app_secret = "";
$canvas_url = "";

$facebook = new Facebook(array(
'appId'  => $app_id,
'secret' => $app_secret,
'cookie' => true
));

$session = $facebook->getSession();

if (!$session) {

        $url = $facebook->getLoginUrl(array(
        'canvas' => 1,
        'fbconnect' => 0,
        'req_perms' => 'publish_stream, user_photos, read_stream, read_friendlists'
        ));

        echo "<script type='text/javascript'>top.location.href = '$url';</script>";

    }//end if session user 
else
{

        try {

        $uid = $facebook->getUser();
        $me = $facebook->api('/me');

        $updated = date("l, F j, Y", strtotime($me['updated_time']));

        echo "Hello " . $me['name'] . "<br />";
        echo "You last updated your profile on " . $updated  . "<br />" ;
        echo "<img src='https://graph.facebook.com/".$uid."/picture'/>"; 
        }//end try getUser 
        catch (FacebookApiException $e) {

        echo "Error:" . print_r($e, true);

        }//end catch getUser 
}//end else user

index.php包含以下形式:

<form enctype="multipart/form-data" action="uploader.php" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="1000000" />
Choose a file to upload: <input name="uploadedfile" type="file" /><br />
<input type="submit" value="Upload File" />
</form>

uploader.php运行流程

$target_path = "uploads/";
        $target_path = $target_path . basename( $_FILES['uploadedfile']['name']); 

        if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
            echo "The file ".  basename( $_FILES['uploadedfile']['name']). 
            " has been uploaded" . "<br />";
        } else{
            echo "There was an error uploading the file, please try again!" . "<br />";
        }
        try {
    $post_id = $facebook->api("/".$uid."/feed", "post", array("picture"=>$target_path));
    if(isset($post_id))
        echo "A new post to your wall has been posted with id: $post_id";
  } catch (FacebookApiException $e) {
    error_log($e);
  }

我一直在尝试许多不同的方式,我可以在网上找到,但它不起作用。我试过添加$ facebook-&gt; setFileUploadSupport(true);但收到错误。

请告诉我如何将照片上传到用户墙上。 非常感谢你

5 个答案:

答案 0 :(得分:2)

您好兄弟这段代码完全适用于我。这个代码你做了什么,它会将帖子发布到你的专辑或应用专辑中。

if(isset($_POST['upload']))
{
    if ( isset($_FILES["file"]) && $_FILES["file"]["error"]==0 )
    {
        $file='images/'.$_FILES["file"]['name'];
        if( move_uploaded_file($_FILES["file"]["tmp_name"],$file))
        {
            $facebook->setFileUploadSupport(true);
            $post_data = array(
            'name'=>$_POST['album'],
            'description'=>$_POST['album']
            );
            $data['album'] = $facebook->api("/me/albums", 'post', $post_data); 
            //$file = $file_name;
            $post_data = array(
            "message" => $_POST['message'],
            "source" => '@' . realpath($file)
            );
            $album_id = $data['album']['id'];
            $data['photo'] = $facebook->api("/$album_id/photos", 'post', $post_data);
        }
    }
    /**/

}

当您从应用程序上传任何图片时,Facebook会在您的个人资料中创建一个名为您的应用程序的相册。但是此代码会将图片发布到您的相册中。

$_POST['album']
是我在文本字段中输入的专辑名称。然后我发布表单并上传照片。我希望这会对你有帮助

答案 1 :(得分:1)

认为这应该有效:

$target_folder = "uploads/";
$target_path = $target_folder . basename( $_FILES['uploadedfile']['name']); 
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
    echo "The file ".  basename( $_FILES['uploadedfile']['name']). 
    " has been uploaded" . "<br />";

    $file_path = $target_folder . $_FILES['uploadedfile']['name'];
    $arr = array();
    $arr["image"] = '@' . realpath($file_path);
    try {
        $post_id = $facebook->api("/".$uid."/feed", "post", $arr);
        if(isset($post_id))
        echo "A new post to your wall has been posted with id: $post_id";
    } catch (FacebookApiException $e) {
        error_log($e);
    }
} else{
    echo "There was an error uploading the file, please try again!" . "<br />";
}

答案 2 :(得分:1)

getSession()替换为getUser() 因为旧的PHP版本无法识别getSession()函数。

答案 3 :(得分:0)

$session = $facebook->getSession();
use getUser();

答案 4 :(得分:0)

使用此代码,它将适合您作为Facebook文档在这里How-To: Use the Graph API to Upload Photos to a user’s profile

<?php

       $app_id = "YOUR_APP_ID";
       $app_secret = "YOUR_APP_SECRET";
       $post_login_url = "YOUR_POST-LOGIN_URL";
       $album_name = 'YOUR_ALBUM_NAME';
       $album_description = 'YOUR_ALBUM_DESCRIPTION';

       $code = $_REQUEST["code"];

       //Obtain the access_token with publish_stream permission 
       if(empty($code))
         {
           $dialog_url= "http://www.facebook.com/dialog/oauth?"
           . "client_id=" . $app_id 
           . "&redirect_uri=" . urlencode($post_login_url)
           . "&scope=publish_stream";
           echo("<script>top.location.href='" . $dialog_url . 
           "'</script>");
       } 
       else {
         $token_url= "https://graph.facebook.com/oauth/"
         . "access_token?"
         . "client_id=" .  $app_id 
         . "&redirect_uri=" . urlencode( $post_login_url)
         . "&client_secret=" . $app_secret
         . "&code=" . $code;
         $response = file_get_contents($token_url);
         $params = null;
         parse_str($response, $params);
         $access_token = $params['access_token'];

         // Create a new album
         $graph_url = "https://graph.facebook.com/me/albums?"
         . "access_token=". $access_token;

         $postdata = http_build_query(
         array(
          'name' => $album_name,
          'message' => $album_description
            )
          );
         $opts = array('http' =>
         array(
          'method'=> 'POST',
          'header'=>
            'Content-type: application/x-www-form-urlencoded',
          'content' => $postdata
          )
         );
         $context  = stream_context_create($opts);
         $result = json_decode(file_get_contents($graph_url, false, 
           $context));

         // Get the new album ID
         $album_id = $result->id;

         //Show photo upload form and post to the Graph URL
         $graph_url = "https://graph.facebook.com/". $album_id
           . "/photos?access_token=" . $access_token;
         echo '<html><body>';
         echo '<form enctype="multipart/form-data" action="'
         .$graph_url. ' "method="POST">';
         echo 'Adding photo to album: ' . $album_name .'<br/><br/>';
         echo 'Please choose a photo: ';
         echo '<input name="source" type="file"><br/><br/>';
         echo 'Say something about this photo: ';
         echo '<input name="message" type="text"
            value=""><br/><br/>';
         echo '<input type="submit" value="Upload" /><br/>';
         echo '</form>';
         echo '</body></html>';
      }
 ?>

响应示例

{
   "id": "1001207389476"
}