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

dan*_*car 2 php post curl

我知道我可以使用这个语法合成器使用php,post和curl发送文件.

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

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

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

Emi*_*röm 9

您可以在临时目录中使用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);
Run Code Online (Sandbox Code Playgroud)