Jocky
Jocky

Reputation: 31

CLI CURL -> PHP CURL

How can I translate this curl command so that it works in a PHP script?

curl --request POST --data-binary '@import.xml' --header "Content-Type: application/atom+xml" --header "Content-Length: 378" "http://url.com"

this don't work:

$data = array('file'=>$filename);                    

    $headers = array(
        'Content-Type: application/atom+xml',
        'Content-Length: 378'
    );

$ch = curl_init(); 
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, 'httpL//url.com');
curl_setopt($ch, CURLOPT_BINARYTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);  
curl_exec($ch);

Upvotes: 3

Views: 2265

Answers (3)

FMaz008
FMaz008

Reputation: 11285

Try this:

$ch = curl_init(); 
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/atom+xml'
    ));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, 'http://siteurl.com');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, file_get_contents($filename));  
curl_exec($ch);

Upvotes: 4

Daniel Stenberg
Daniel Stenberg

Reputation: 58004

The correct thing would be to read the file into a string and then provide that string to the CURLOPT_POSTFIELDS options. That feature of reading into a string is not provided by libcurl but is done by the command line client and I don't think the PHP/CURL binding offers the equivalent.

The command line uses --data-binary which corresponds to a CURLOPT_POSTSFIELDS with a string, not a hash array as the array will turn the post in to a multipart post (which the command line does with -F, --form). Also, the custom request set to POST is totally superfluous.

Usually, running the command line with "--libcurl test.c" is a good way to get a first draft version of a C program using the C API, but as the PHP API is very similar that should work as decent start in most cases.

Edit: and custom changing/providing the "Content-Length:" header is never a good idea unless you know perfectly well what you're doing. libcurl will always provide one that is generated based on the data you pass on to it.

Upvotes: 0

Marc B
Marc B

Reputation: 360602

$data = array('file'=> '@' . $filename);                    

You need to prepend the filename with a '@' to tell CURL it's actually a filename and not just a string. The headers are not required either, as CURL will fill them in itself.

Upvotes: -1

Related Questions