2011-08-05 50 views
0

明文我知道張貼只是二進制一起:後從可變二進制使用捲曲和PHP

$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變量。

+0

剛剛保存文件並將其刪除後發生了什麼問題? – Robus

+0

好吧,好像是一個不必要的步驟,你必須選擇一個獨特的文件名等。 – mb21

+0

@ mb21:'tempnam()'會爲你做到這一點。 –

回答

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