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

标签 php post curl

我知道我可以使用此语法通过 php、post 和 curl 发送文件。

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

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

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

最佳答案

您可以使用 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);

关于php - 使用 curl 和 php 将字符串作为文件发送,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6149985/

相关文章:

php - 如何使多维数组唯一?

php - 性能批量插入或切片多批量插入的最佳选择是什么?

php - POST 调用无法正常工作

Java - 从 HttpURLConnection 读取 POST 抛出响应代码 400

json - 将外部数据文件上传到 Apache Solr 的方法

php - curl 的多项操作

php - 在PayPal对话框中,有没有办法指定是否扩展 "Have PayPal Account"或 "Don' t have PayPal account”?

php - HTML 表单发送 get 和 post。使用 302 重定向

linux - Curl 不会提交表单。为什么不?

php - 如何在我的 Laravel 5 应用程序中使用 Illuminate\Support\Str::slug?