0

I'm trying to use PHP curl to submit a payload with some files. Here's my submit.php

<?php

$url = "http://example.com/receive.php";

$payload = array();
$payload['resource_name'] = 'hello world';
$payload['resource_file'] = curl_file_create("test-pdf.pdf");

$headr = array();
//$headr[] = 'Content-Type: multipart/form-data';

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headr);
curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($payload));

// Receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($ch);

curl_close ($ch);
print_r($response);
echo "\n";

And this is my http://example.com/receive.php

<?php
print_r($_REQUEST);
print_r($_FILES);

When I run php submit.php from command line I get this result:

Array
(
    [resource_name] => hello world
    [resource_file] => Array
        (
            [name] => test-pdf.pdf
            [mime] =>
            [postname] =>
        )

)
Array
(
)

Why is my $_FILES array empty?

If I enable the multipart/form-data line, then both $_REQUEST and $_FILES is empty. What am I doing wrong? How do I populate both the $_REQUEST and $_FILES array in receive.php?

1
  • 1
    There are lots of previous examples of this online - see here. Have you tried anything from your research? stackoverflow.com/questions/21905942/… seems to be the canonical SO answer on this topic. Commented Aug 10, 2021 at 22:24

1 Answer 1

1

Remove http_build_query and problem solved.

curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);

The reason is that http_build_query will generate URL-encoded query string for x-www-form-urlencoded

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

Comments

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.