Skip to content
Advertisement

Send string as a file using curl and php

I know I can use this syntaxt to send a file using php, post and curl.

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

How can I take a string, build a temp file and send it using the exact same syntax ?

Update: I would prefer using tmpfile() or php://memory so I don’t have to handle file creation.

Advertisement

Answer

You can create a file using tempnam in your temp directory:

$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);
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement