Help encoding a cURL argument (works fine from the command line, but not from a PHP script)
I am working with the Facebook API, and successfully use the following command via terminal to post a message to another users wall.
curl -F 'access_token=XXXXXXXXXX' \
-F 'message=Hello World' \
-F 'to={["id":XXXXXXX]}' \
https开发者_开发技巧://graph.facebook.com/me/feed
This works great. I am trying to do the same via php with this code;
$fields = array(
'access_token' => $t,
'message' => $message,
'to' => '{["id":'.$id.']}'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_exec($ch);
curl_close($ch);
This code successfuly posts a message, but it does it to my OWN wall (i.e. it is ignoring the 'to' parameter). I'm new to cURL, and I'm sure I am encoding it wrong, or maybe missing a cURL flag, but I've been through several tutorials on POSTing via cURL, including a few SO answers, and I can't see what I'm missing.
Really appreciate any help!
What does this print out?
if ( 'POST' == $_SERVER[ 'REQUEST_METHOD' ]) {
echo 'Posted: ';
print_r( $_POST );
exit;
}
$t = '121';
$message = 'helo Worlds';
$id = 1234;
$fields = array(
'access_token' => $t,
'message' => $message,
'to' => '{["id":'.$id.']}'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://localhost:8888/testbed/' ); // THIS script
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE );
$out = curl_exec($ch);
curl_close($ch);
echo 'Received[ ' . $out . ' ]';
Prints this on my local box:
Received[ Posted: Array ( [access_token] => 121 [message] => helo Worlds [to] => {[\"id\":1234]} ) ]
UPDATED:
$fields should be a GET like string
para1=val1¶2=val2&...
or an array:
The full data to post in a HTTP "POST" operation. To post a file, prepend a filename with @ and use the full path. The filetype can be explicitly specified by following the filename with the type in the format ';type=mimetype'. This parameter can either be passed as a urlencoded string like 'para1=val1¶2=val2&...' or as an array with the field name as key and field data as value. If value is an array, the Content-Type header will be set to multipart/form-data. As of PHP 5.2.0, files thats passed to this option with the @ prefix must be in array form to work.
精彩评论