使用curl和php发送字符串作为文件

问题描述:

我知道我可以使用这个syntaxt来使用php,post和curl发送文件。使用curl和php发送字符串作为文件

$post = array(
    "file_box"=>"@/path/to/myfile.jpg", 
); 
curl_setopt($ch, CURLOPT_POSTFIELDS, $post); 

如何获得一个字符串,构建一个临时文件并使用完全相同的语法发送它?

更新: 我宁愿使用tmpfile()或php://内存,所以我不必处理文件创建。

+1

重复这个问题:?POST在PHP中使用卷曲文件字符串(http://*.com/问题/ 3085990/post-a-file-string-using-curl-in-php)(你会在那里找到你的答案) – Lepidosteus 2011-05-27 09:03:01

+0

那里没有真正的答案。 @emil迄今为止提供了一个很好的解决方案。 – danidacar 2011-05-27 09:05:53

+0

嗯,是的,当你在一个字符串中包含内容时,通过curl发送一个文件是一个真正的答案。 Tatu的回答是涉及临时文件的不同解决方案(因此您不会将字符串作为文件发送,而是发送实际文件)。 – Lepidosteus 2011-05-27 09:07:48

您可以创建在temp目录中使用tempnam文件:

$string = 'random string'; 

//Save string into temp file 
$file = tempnam(sys_get_temp_dir(), 'POST'); 
file_put_contents($file, $string); 

//Post file 
$post = array(
    "file_box"=>'@'.$file, 
); 
curl_setopt($ch, CURLOPT_POSTFIELDS, $post); 

//do your cURL work here... 

//Remove the file 
unlink($file); 

您可以使用file_put_contents创建一个临时文件,只需确保目标目录是可写的。

$path = '/path/to/myfile.txt';  
file_put_contents($myData, $path); 

$post = array(
    "file_box"=>"@".$path, 
); 
curl_setopt($ch, CURLOPT_POSTFIELDS, $post); 

# Delete the file if you don't need it anymore 
unlink($path);