3

There are lots of answers to "upload file with php curl", and they all require that a physical file exists on the machine. It's uploaded by referencing the @ symbol before the filename in the POST fields.

However, I have the file data already in a PHP variable: $data. How can I upload this directly without needing to first write it to a file?

I tried this:

$ch = curl_init();
curl_setopt_array($ch, [
    CURLOPT_URL => SERVER_URL . '/test.php?abc=def&ghi=jkl',
    CURLOPT_RETURNTRANSFER => 1,
    CURLOPT_TIMEOUT => 120,
    CURLOPT_POST => 1,
    CURLOPT_CUSTOMREQUEST => "POST",
    CURLOPT_POSTFIELDS => ['file' => $data],
    CURLOPT_HTTPHEADER => ["Content-type: multipart/form-data"],
    CURLOPT_HEADER => true,
    CURLOPT_INFILESIZE => strlen($data)
]);

$response = curl_exec($ch);

But my server gives an error that POST Content-Length exceeds the server limit of 8388608 bytes. However, in my php.ini file on the server, I have upload_max_filesize = 500M. So it looks like this POST is not being treated as a multipart file upload, but instead is trying to jam all the file data into the POST request.

1 Answer 1

1

You could first write your string to a file in the /tmp folder. I'm not certain, but I think you might be required to do this if you want to post a file. The documentation says :

7.0.0 Support for disabling the CURLOPT_SAFE_UPLOAD option has been removed. All curl file uploads must use CURLFile.

EDIT: Please check the docs on post_max_size:

post_max_size integer

Sets max size of post data allowed. This setting also affects file upload. To upload large files, this value must be larger than upload_max_filesize. Generally speaking, memory_limit should be larger than post_max_size...

Sign up to request clarification or add additional context in comments.

2 Comments

I know I can write the data to a file... I was trying to avoid that extra step. If it's not possible, I will do it. I just felt like I was missing something obvious. Thanks
@RyanGriggs try adjusting your post_max_size value to something large enough to accommodate the file (or attempt a smaller test file) and see if it works. It just might -- although that "all curl file uploads must use CURLFile" warning for php 7.0.0 seems pretty ominous for forward-compatibility. You could also consider altering your script that handles the upload to accept the information as a string. You would probably want to base64 encode it to make sure it survives transit from curl to server.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.