使用curl和php将变量与纯文本一起发布

时间:2011-08-05 16:53:44

标签: php curl

我知道只发布二进制文件:

$file_contents = file_get_contents("http://example.org/image.jpg");
curl_setopt($ch, CURLOPT_POSTFIELDS, $file_contents); 

以及在磁盘上的文件中发布文本和二进制文件:

curl_setopt($ch, CURLOPT_POSTFIELDS, array(
  "name" => "peter",
  "msg" => "hello",
  "foo" => "@file/on/disk/image.jpg"
));

但我无法弄清楚如何直接从变量(例如$ file_contents)和纯文本键值对发布二进制数据。这是卷曲吗?

我问的原因是我正在使用facebook API来创建事件,并且需要在事件数据的其余部分上传图像。因为我从互联网上获取图像,如果我不必在发布之前将它们保存在磁盘上,然后将它们从磁盘中删除,而是直接使用file_get_contents()中的数据保存在php变量。

1 个答案:

答案 0 :(得分:1)

您可以在url中将参数作为查询字符串传递,并在postfields中传递二进制数据。 在接收端,可以从$ _REQUEST

中检索所有参数
$file_contents = file_get_contents("http://example.org/image.jpg");

$c = curl_init();
curl_setopt($c, CURLOPT_URL, 'http://example.com/test.aspx?name=peter&msg=hello');
curl_setopt($c, CURLOPT_POSTFIELDS, $file_contents);
curl_setopt($c, CURLOPT_POST, 1);
curl_setopt($c, CURLOPT_VERBOSE, 0);
curl_setopt($c, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($c, CURLOPT_FOLLOWLOCATION, 0);
$cResponse = curl_exec($c);
curl_close($c);