PHP POST API no file received - php

Our team is working on developing a web application for accessing a 3D printer remotely in PHP. We tried implementing the POST print_job part using the multipart/form-data but it doesn't work, which shows no file received. This API would check id and key. Here is the code. Any help is appreciated!
It's running on Apache 2.4.39, PHP 7.3.5, XAMPP Control Panel 3.2.2.
The details are:
<?php
function callAPI($method, $url, $data){
$curl = curl_init();
switch ($method){
case "POST":
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_POST, 1);
if ($data)
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
case "PUT":
curl_setopt($curl, CURLOPT_HEADER, true);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
if ($data)
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
default:
if ($data)
$url = sprintf("%s?%s", $url, http_build_query($data));
}
$username = "";
$password = "";
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST);
curl_setopt($curl, CURLOPT_USERPWD, $username . ":" . $password);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl, CURLOPT_TIMEOUT, 90);
curl_setopt($curl, CURLINFO_HEADER_OUT, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
// EXECUTE:
$result = curl_exec($curl);
if(!$result){die("Connection Failure");}
curl_close($curl);
return $result;
}
?>
<?php
include('api.php');
$_SESSION['ip'] = "";
$_SESSION['url'] = "http://".$_SESSION['ip']."/api/v1";
$target_dir = "../uploads/";
$target_file = $target_dir . basename($_FILES["file"]["name"]);
move_uploaded_file($_FILES["file"]["tmp_name"], $target_file);
$filedata = $_FILES["file"]["tmp_name"];
echo $target_file;
$data_array = array(
"jobname" => "file",
"file" => "new \CURLFile(realpath($filedata))"
);
$_SESSION['size'] = $_FILES['file']['size'];
//$make_call = callAPI('POST', $_SESSION['url']."/print_job", $data_array);
$response = callAPI('POST', $_SESSION['url']."/print_job", $data_array);
$_SESSION['print'] = $response;
header('location: ../index.php');
?>
Ps: If I want to upload the file which was got from front-end to the remote API, I may have to store it locally. Then I tried it as the following code. It works.
file_put_contents("E:/xyz/test.gcode",file_get_contents("../uploads/".$_FILES["file"]["name"]));
$filedata='E:/xyz/test.gcode';
if(!is_readable(realpath($filedata))){throw new \RuntimeException("upload file not readable!");}
$data_array = array(
'jobname' => 'file',
'file' => new \CURLFile($filedata)
);

first off, don't set the Content-Type:multipart/form-data header manually because you'll corrupt the boundary if you do. the full header looks something like:
Content-Type: multipart/form-data; boundary=------------------------777d48028c332f50
so remove this:
$headers = array("Content-Type:multipart/form-data");
and let curl set it for you. (curl will automatically set that header, with the correct boundary, when setting CURLOPT_POSTFIELDS to array.)
second, you're not sending an actual file here, you're just sending the literal string
new \CURLFile(realpath($filedata))
.. if you want to send the file pointed to by $filedata , do
$data_array = array(
"jobname" => "test",
"file" => new \CURLFile(realpath($filedata))
);
instead.

Related

How to upload a photo using the Flickr API?

I'm unable to upload an image to Flickr using the Flickr API. I'm trying to do this in a web-based application running PHP.
I've tried DPZFlickr, which returns this, when trying to upload:
Array ( [stat] => fail [err] => Array ( ) )
Inspecting the Flickr API's response, it's the same as what is returned when trying Dantsu's version of phpFlickr, which returns this:
oauth_problem=signature_invalid&debug_sbs=...
I've rolled my own CURL, which returns this:
Upload result: HTTP/1.1 200 OK Date: Wed, 23 Jan 2019 16:09:39 GMT Content-Type: text/xml; charset=utf-8 Content-Length: 109 P3P: policyref="https://policies.yahoo.com/w3c/p3p.xml", CP="CAO...
Here's the full code I use for creating my CURL request (edited to use CurlFile):
$consumerSecret = $flickrApiSecret;
$ap_url = "https://up.flickr.com/services/upload/";
$apiKey = $flickrApiKey;
$oauth_nonce = time();
$oauthToken = $_SESSION["FlickrSessionOauthData"]["oauth_request_token"];
$oauthTokenSecret = $_SESSION["FlickrSessionOauthData"]["oauth_request_token_secret"];
$text = "Test";
$signatureMethod = "HMAC-SHA1";
$oauthVersion = "1.0";
$timestamp = time();
$parms = "description=".$text."&format=json&oauth_consumer_key=".$apiKey."&oauth_nonce=".$oauth_nonce;
$parms .= "&oauth_signature_method=".$signatureMethod."&oauth_timestamp=".$timestamp."&oauth_token=".$oauthToken;
$parms .= "&oauth_version=".$oauthVersion."&title=".$text;
$baseString = "";
$baseString .= "POST&".urlencode($ap_url)."&".urlencode($parms);
$hashkey = $consumerSecret."&".$oauthTokenSecret;
$apiSignature = base64_encode(hash_hmac('sha1', $baseString, $hashkey, true));
$filePath = "/path_to_file/0.jpg";
$postFields["description"] = $text;
$postFields["format"] = "json";
$postFields["photo"] = new \CurlFile($filePath, mime_content_type ( $filePath ), 'photo');
$postFields["title"] = $text;
print_r ($postFields);
print "<br />";
$url = "https://up.flickr.com/services/upload/";
$oauth_header = "oauth_consumer_key=".$apiKey.",oauth_nonce=".$oauth_nonce.",oauth_signature_method=".$signatureMethod.",oauth_timestamp=".$timestamp.",oauth_token=".$oauthToken.",oauth_version=".$oauthVersion.",oauth_signature=".$apiSignature;
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array("Authorization: OAuth ".$oauth_header));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_VERBOSE, 0);
curl_setopt($curl, CURLOPT_HEADER, 1);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_POST, TRUE);
curl_setopt($curl, CURLOPT_POSTFIELDS, $postFields);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SAFE_UPLOAD, true);
$response = curl_exec ($curl);
curl_close ($curl);
echo $response;
I'm at a loss. How to make this work?
This question and answer got me going in the right direction.
I still was unable to get my own CURL up and running, but I managed to hack a few lines of code in DPZFlickr's library to get that working.
I updated the httprequest function to this:
private function httpRequest($url, $parameters)
{
if (isset($parameters["photo"])) {
$p = $parameters["photo"];
$pf = substr($p, 1);
$parameters["photo"] = new \CurlFile($pf, mime_content_type ( $pf ), 'photo');
}
$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_TIMEOUT, $this->httpTimeout);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
if ($this->method == 'POST')
{
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, TRUE);
curl_setopt($curl, CURLOPT_POSTFIELDS, $parameters);
}
else
{
// Assume GET
curl_setopt($curl, CURLOPT_URL, "$url?" . $this->joinParameters($parameters));
}
$response = curl_exec($curl);
$headers = curl_getinfo($curl);
curl_close($curl);
$this->lastHttpResponseCode = $headers['http_code'];
return $response;
}
This includes one change:
Changing how the photo is included. Now through CurlFile.
I'm doing this on PHP 7.2. Apparently, the CURLOPT_SAFE_UPLOAD underwent some changes in PHP 5.x, while CurlFile became a requirement in PHP 7.1.

How to upload file into target directory with curl?

There is a file "/home/test.mp4" in my local machine,
I want to upload it into /var/www/ok.mp4 (the name changed when uploaded it). All the source file and target file are in the local machine.
How to fix my partial code ,to add something or to change something ?
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);
curl_exec($ch);
?>
Think to Ram Sharma, the code was changed as the following:
<?php
$request = curl_init('http://127.0.0.1/');
curl_setopt($request, CURLOPT_POST, true);
curl_setopt(
$request,
CURLOPT_POSTFIELDS,
array(
'file' => '#' . realpath('/home/test.mp4')
));
curl_setopt($request, CURLOPT_RETURNTRANSFER, true);
echo curl_exec($request);
// close the session
curl_close($request);
?>
An error message occur:
It works!
This is the default web page for this server.
The web server software is running but no content has been added, yet.
I have test with ftp_put,code1 works fine.
code1:
<?php
set_time_limit(0);
$host = 'xxxx';
$usr = 'yyyy';
$pwd = 'zzzz';
$src = 'd:/upload.sql';
$ftp_path = '/public_html/';
$des = 'upload_ftp_put.sql';
$conn_id = ftp_connect($host, 21) or die ("Cannot connect to host");
ftp_login($conn_id, $usr, $pwd) or die("Cannot login");
$upload = ftp_put($conn_id, $ftp_path.$des, $src, FTP_ASCII);
print($upload);
?>
The file d:/upload.sql in my local pc can be uploaded into my_ftp_ip/public_html/upload_ftp_put.sql with code1.
Now i rewite it with curl into code2.
code2:
<?php
set_time_limit(0);
$ch = curl_init();
$host = 'xxxx';
$usr = 'yyyy';
$pwd = 'zzzz';
$src = 'd:/upload.sql';
$ftp_path = '/public_html';
$dest = 'upload_curl.sql';
$fp = fopen($src, 'r');
curl_setopt($ch, CURLOPT_URL, 'ftp://user:pwd#host/'.$ftp_path .'/'. $dest);
curl_setopt($ch, CURLOPT_UPLOAD, 1);
curl_setopt($ch, CURLOPT_INFILE, $fp);
curl_setopt($ch, CURLOPT_INFILESIZE, filesize($src));
curl_exec ($ch);
$error_no = curl_errno($ch);
print($error_no);
curl_close ($ch);
?>
The error info output is 6 .Why can't upload my local file into the ftp with curl?How to fix it?
Use copy():
copy('/home/test.mp4', '/var/www/ok.mp4');
It does not make sense to run the file through the network stack (which is what cURL does), on any protocol (HTTP, FTP, …), when the manipulation can be done locally, through the file system. Using network is more complicated and error-prone.
It is a low level error.
curl_setopt($ch, CURLOPT_URL, "ftp://$usr:$pwd#$host$ftp_path/$dest");
try something like this and I feel instead of server directory path it would be http url.
// initialise the curl request
$request = curl_init('http://example.com/');
// send a file
curl_setopt($request, CURLOPT_POST, true);
curl_setopt(
$request,
CURLOPT_POSTFIELDS,
array(
'file' => '#' . realpath('test.txt')
));
// output the response
curl_setopt($request, CURLOPT_RETURNTRANSFER, true);
echo curl_exec($request);
// close the session
curl_close($request);
This code might help you:
<?php
$rCURL = curl_init();
curl_setopt($rCURL, CURLOPT_URL, 'http://www.google.com/images/srpr/logo11w.png');
curl_setopt($rCURL, CURLOPT_HEADER, 0);
curl_setopt($rCURL, CURLOPT_RETURNTRANSFER, 1);
$aData = curl_exec($rCURL);
curl_close($rCURL);
file_put_contents('bla.jpeg', $aData);
// file_put_contents('my_folder/bla.jpeg', $aData); /*You can use this too*/
Try to specify the MIME type of the file sent like this
curl_setopt(
$request,
CURLOPT_POSTFIELDS,
array(
'file' => '#' . realpath('/home/test.mp4') . ';type=video/mp4'
));
The code you posted is for the client side. If you want to upload a file using HTTP, you HTTP server must be able to handle this upload request and save the file where you want. The “error message” is probably the server’s default web page.
Sample server-side code in PHP, for your reference:
<?php
if ($_FILES) {
$filename = $_FILES['file']['name'];
$tmpname = $_FILES['file']['tmp_name'];
if (move_uploaded_file($tmpname,'/var/www/ok.mp4')) {
print_r('ok');
} else {
print_r('failure');
}
}
curl -X POST -F "image=#test.mp4" http://example.com/
You will also need a page that can process this request (POST)

Post JSON encoded and normal string data using CURL in PHP

I typically send an array of strings using CURL in PHP, something like this:
$data = array(
"key1" => $value,
"key2" => $value,
"key3" => $value,
"key4" => $value
);
Then, among other curl_setop settings, post using:
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
This all works fine. But now in addition to those strings, I have 1 dataset that is JSON encoded and I want to post it at the same time. JSON looks like this:
Array ( [ad_info] => {"MoPubAdUnitInteractions":"a","MoPubAdUnitConversations":"b","MoPubAdUnitGroups":"c"} )
I think I figured out how to do it by setting a header saying I'm going to be passing in JSON like this:
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
But then, can I simply add another line for the post, but in this case the JSON encoded value like this:
curl_setopt($curl, CURLOPT_POSTFIELDS, $json_data);
I'm kinda shooting in the dark, any suggestions on how I should be thinking about this?
Ok, here is the full example:
From Processing The Form Post:
$community_id = $_POST["communityid"];
$community_name = $_POST["communityname"];
$community_apns_name = $_POST["communityapnsname"];
$community_download_url = $_POST["communitydownloadurl"];
$community_open_tagging = $_POST["communityopentagging"];
$community_pull_content = $_POST["communitypullcontent"];
$community_push_content = $_POST["communitypushcontent"];
$community_ad_info = json_encode($_POST["ad_info"]);
$data = array(
"name" => $community_name,
"apns_name" => $community_apns_name,
"download_url" => $community_download_url,
"open_tagging" => $community_open_tagging,
"pull_content" => $community_pull_content,
"push_content" => $community_push_content,
);
$json_data = array("ad_info" => $community_ad_info);
$api_querystring = $gl_app_api_url . "communities";
$response = CallAPI('PATCH', $api_querystring, $data, $device_id = null, $community_id = null, $json_data);
And the Function in PHP I'm calling to do the CURL:
function CallAPI($method, $url, $data = false, $device_id = false, $community_id = false, $json_data = false) {
if (!$community_id) { // IF NO COMMUNITY ID IS PROVIDED
global $gl_community_id;
$community_id = $gl_community_id;
}
$curl = curl_init();
switch ($method)
{
case "POST":
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST');
if ($data)
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
case "PUT":
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PUT');
if ($data)
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
case "PATCH":
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PATCH');
if ($data)
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
default:
if ($data)
$url = sprintf("%s?%s", $url, http_build_query($data));
}
// Optional Authentication:
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_USERPWD, "XXXX:XXXXX");
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
// Disable the SSL verificaiton process
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
if ($device_id)
curl_setopt($curl, CURLOPT_HTTPHEADER, array("device_id:" . $device_id));
if ($community_id)
curl_setopt($curl, CURLOPT_HTTPHEADER, array("X-Afty-Community:" . $community_id));
if ($json_data)
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($curl, CURLOPT_POSTFIELDS, $json_data);
// Confirm cURL gave a result, if not, write the error
$response = curl_exec($curl);
if ($response === FALSE) {
die("Curl Failed: " . curl_error($curl));
} else {
return $response;
}
}
Any help is greatly appreciated.
You use wrong approach. Setting CURLOPT_POSTFIELDS option twice doesn't lead to result you expected since each setting call discards effect of previous one.
Instead of this, you have to append extra data ($community_ad_info) to the main POST data ($data) before passing it to CURLOPT_POSTFIELDS option.
...
$community_ad_info = json_encode($_POST["ad_info"]);
$data = array(
"name" => $community_name,
"apns_name" => $community_apns_name,
"download_url" => $community_download_url,
"open_tagging" => $community_open_tagging,
"pull_content" => $community_pull_content,
"push_content" => $community_push_content,
"ad_info" => $community_ad_info
);
$response = CallAPI('PATCH', $api_querystring, $data, $device_id = null, $community_id = null);
...
This is untested of course but it should do what you need.
function CallAPI($method, $url, $data = false, $device_id = false, $community_id = false, $json_data = false) {
if (!$community_id) { // IF NO COMMUNITY ID IS PROVIDED
global $gl_community_id;
$community_id = $gl_community_id;
}
$curl = curl_init();
switch ($method)
{
case "POST":
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
if ($data)
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
case "PUT":
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PUT');
if ($data)
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
case "PATCH":
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PATCH');
if ($data)
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
default:
if ($data)
$url = sprintf("%s?%s", $url, http_build_query($data));
}
// Optional Authentication:
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_USERPWD, "XXXX:XXXXX");
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
// Disable the SSL verificaiton process
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
if ($device_id)
curl_setopt($curl, CURLOPT_HTTPHEADER, array("device_id:" . $device_id));
if ($community_id)
curl_setopt($curl, CURLOPT_HTTPHEADER, array("X-Afty-Community:" . $community_id));
// Confirm cURL gave a result, if not, write the error
$response = curl_exec($curl);
if ($response === FALSE) {
die("Curl Failed: " . curl_error($curl));
} else {
return $response;
}
}
And now the actualy logic
$community_id = $_POST["communityid"];
$community_name = $_POST["communityname"];
$community_apns_name = $_POST["communityapnsname"];
$community_download_url = $_POST["communitydownloadurl"];
$community_open_tagging = $_POST["communityopentagging"];
$community_pull_content = $_POST["communitypullcontent"];
$community_push_content = $_POST["communitypushcontent"];
$community_ad_info = json_encode($_POST["ad_info"]);
$data = array(
"name" => $community_name,
"apns_name" => $community_apns_name,
"download_url" => $community_download_url,
"open_tagging" => $community_open_tagging,
"pull_content" => $community_pull_content,
"push_content" => $community_push_content,
"ad_info" => $community_ad_info
);
$api_querystring = $gl_app_api_url . "communities";
$response = CallAPI('PATCH', $api_querystring, $data, $device_id = null, $community_id = null);
The things to note here are,
the new content tyoe header tells it to be processed as a form post.
removal of the $json_data array, the "ad_info" key is not just added into the $data array
When you process this on the other side you can access the ad_info like this
$ad_info = json_decode($_POST['ad_info']);
You can access the other fields with
$apns_name = $_POST['apns_name'];

No PUT post data being received

I am sending out a PUT request to my site via PHP using cURL:
$data = array("a" => 'hello');
$ch = curl_init('http://localhost/linetime/user/1');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($data));
$response = curl_exec($ch);
var_dump($response);
I am then listening for this PUT request, but receiving no data with the request. Please can you tell me where I am going wrong?
$putData = '';
$fp = fopen('php://input', 'r');
while (!feof($fp)) {
$s = fread($fp, 64);
$putData .= $s;
}
fclose($fp);
echo $putData;
exit;
make sure to specify a content-length header and set post fields as a string
$data = array("a" => 'hello');
$fields = http_build_query($data)
$ch = curl_init('http://localhost/linetime/user/1');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
//important
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Length: ' . strlen($fields)));
curl_setopt($ch, CURLOPT_POSTFIELDS,$fields);
Use an HTTP client class to help send the requests. There are several available, but I have created one (https://github.com/broshizzledizzle/Http-Client) that I can give you help with.
Making a PUT request:
<?php
require_once 'Http/Client.php';
require_once 'Http/Method.php';
require_once 'Http/PUT.php';
require_once 'Http/Request.php';
require_once 'Http/Response.php';
require_once 'Http/Uri.php';
use Http\Request;
use Http\Response;
header('Content-type:text/plain');
$client = new Http\Client();
//GET request
echo $client->send(
Request::create()
->setMethod(new Http\PUT())
->setUri(new Http\Uri('http://localhost/linetime/user/1'))
->setParameter('a', 'hello')
)->getBody();
?>
Processing a PUT request:
//simply print out what was sent:
switch($_SERVER['REQUEST_METHOD']) {
case 'PUT':
echo file_get_contents('php://input');
break;
}
Note that I have an autoloader on my projects that will load all those includes for me, but you may want to consider making a file that will include everything if you don't want to go down that route.
Library-less:
//initialization code goes here
$requestBody = http_build_query(
array('a'=> 'hello'),
'',
'&'
);
$fh = fopen('php://memory', 'rw');
fwrite($fh, $requestBody);
rewind($fh);
curl_setopt($this->curl, CURLOPT_INFILE, $fh);
curl_setopt($this->curl, CURLOPT_INFILESIZE, strlen($requestBody));
curl_setopt($this->curl, CURLOPT_PUT, true);
//send request here
fclose($fh);
Note that you use a stream to send the data.

Uploading a picture to facebook

I am trying to upload a image to a gallery on a facebook fan page, here is my code thus far,
$ch = curl_init();
$data = array('type' => 'client_cred', 'client_id' => 'app_id','client_secret'=>'secret_key',' redirect_uri'=>'http://apps.facebook.com/my-application/'); // your connect url here
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, 'https://graph.facebook.com/oauth/access_token');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$rs = curl_exec($ch);
curl_close($ch);
$ch = curl_init();
$data = explode("=",$rs);
$token = $data[1];
$album_id = '1234';
$file= 'http://my.website.com/my-application/sketch.jpg';
$data = array(basename($file) => "#".realpath($file),
//filename, where $row['file_location'] is a file hosted on my server
"caption" => "test",
"aid" => $album_id, //valid aid, as demonstrated above
"access_token" => $token
);
$ch2 = curl_init();
$url = "https://graph.facebook.com/".$album_id."/photos";
curl_setopt($ch2, CURLOPT_URL, $url);
curl_setopt($ch2, CURLOPT_HEADER, false);
curl_setopt($ch2, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch2, CURLOPT_RETURNTRANSFER, false);
curl_setopt($ch2, CURLOPT_POST, true);
curl_setopt($ch2, CURLOPT_POSTFIELDS, $data);
$op = curl_exec($ch2);
When I echo $token, I seem to be getting the token, but when I run the script, I get this error, {"error":{"type":"OAuthAccessTokenException","message":"An access token is required to request this resource."} , I have NO idea why it is doing this!
Basically what I am doing in that code is getting the access token with curl, and then, uploading the photo to my album also via curl, but I keep getting that error!
Any help would be appreciated, thank you!
Ok, got it working, here is the code, assuming that you have a valid session going.
$token = $session['access_token'];
//upload photo
$file= 'photo.jpg';
$args = array(
'message' => 'Photo from application',
);
$args[basename($file)] = '#' . realpath($file);
$ch = curl_init();
$url = 'https://graph.facebook.com/me/photos?access_token='.$token;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $args);
$data = curl_exec($ch);
This will upload the specified image to the session holders gallery, it will create a album if there is not one present, also you can access the token via the session array as demonstrated above.
Hope this helps someone out.
Probably your application doesn't have needed permissions.
To request permissions via OAuth, use
the scope argument in your
authorization request, and include a
comma separated list of all the
permissions you want to request.
http://developers.facebook.com/docs/authentication/permissions

Categories