Facebook api php sdk 4.0 - 使用“new curlfile”将照片上传到Facebook

时间:2014-07-22 14:38:13

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

我正在尝试通过此Facebook应用程序将我保存在服务器上的照片上传到我的脸书上。

我的facebook请求最初是:

$response = (new FacebookRequest(
    $session,
    'POST',
    '/me/photos',
    array(
        'source' =>  '@' . $_FILES['file']['tmp_name'] ,
    )
))->execute()->getGraphObject()->asArray();

/* handle the result */
print_r($response);

但显然语法现在已经改变了,我需要有这样的东西:

'source'=> new CURLFile(' '),

不确定要放什么参数,因为我的图片存储在我服务器的文件夹中 我的应用程序允许用户从他们的计算机浏览和提交照片。这将在发布到Facebook之前保存到服务器上。我使用了multiform / part:

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

我必须将照片上传到服务器的代码如下:

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

1 个答案:

答案 0 :(得分:2)

CURLFILE方法接受一个主要参数,即路径和文件名。修改您的代码如下:

$response = (new FacebookRequest(
    $session,
    'POST',
    '/me/photos',
    array(
        'source' =>  new CURLFile( $_FILES['file']['tmp_name'] )
    )
))->execute()->getGraphObject()->asArray();