Jesse James Richard
Jesse James Richard

Reputation: 493

What is the cURL -T option in PHP

I'm trying to post to a file service with CDN translating the cli -T option to PHP code, but I don't really know what the equivalent is, or what is the corresponding code that would replicate it. I've seen a options around CURLOPT_HTTPHEADER, but that doesn't seem to work in correspondence to other headers.

The exact thing I'm trying to replicate is this:

curl -XPUT -T "test.png" -v -H "X-Auth-Token:MYTOKEN" -H"Content-Type: text/plain" "https://somecdn.com"

I think it's something like this, but I'm unsure:

    $ch = curl_init();

    // Set up the options
    curl_setopt($ch, CURLOPT_URL, "https://mycdn.com/test.txt");
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                                                "X-Auth-Token: mytoken",
                                                "Content-type: text/plain"
                                            )
                                        );

    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, array("file" => "@test.txt") );
    curl_setopt($ch, CURLINFO_HEADER_OUT, true);

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    $response = curl_exec($ch);

    $info = curl_getinfo($ch);

    curl_close($ch);

I'm surprised, I suppose, that -T flag doesn't have a similar curl_setopt.

So the precise question is this:

What is the proper way to replicate cURL CLI -T "test.png" in PHP?

Upvotes: 3

Views: 1478

Answers (1)

felipsmartins
felipsmartins

Reputation: 13549

Take into consideration as PHP 5.5 uploading file this way (@filename) is deprecated.
Also, PHP 5.5 introduces a new option/flag regarding upload process, called by CURLOPT_SAFE_UPLOAD:

TRUE to disable support for the @ prefix for uploading files in CURLOPT_POSTFIELDS, which means that values starting with @ can be safely passed as fields. CURLFile may be used for uploads instead.
Added in PHP 5.5.0 with FALSE as the default value. PHP 5.6.0 changes the default value to TRUE.

So if you've PHP 5.5+ you must set CURLOPT_SAFE_UPLOAD (though 5.5 is false by default) to false:

curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);

Another option is using the CURLFile class.

And remember: Filename MUST be absolute path.

Upvotes: 1

Related Questions