note 125490 added to function.curl-setopt
| From: | qwertz182@php.net | Date: | Fri, 06 Nov 2020 11:18:48 +0000 |
| Subject: | note 125490 added to function.curl-setopt | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-215816@lists.php.net to get a copy of this message | ||
As the "example #2 Uploading file" says it is deprecated as of PHP 5.5.0 but doesn't
tell you how it's done right,
here is a really easy example using the CURLFile class:
<?php
$request = [
'firstName' => 'John',
'lastName' => 'Doe',
'file' => new CURLFile('example.txt', 'text/plain') // or use
curl_file_create()
];
$curlOptions = [
CURLOPT_URL => 'http://example.com/upload.php',
CURLOPT_POST => true,
CURLOPT_HEADER => false,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POSTFIELDS => $request,
];
$ch = curl_init();
curl_setopt_array($ch, $curlOptions);
$response = curl_exec($ch);
?>
This is just like posting a html form with an input[type=file] field.
The result on windows could look like this:
<?php
// $_POST
Array
(
[firstName] => John
[lastName] => Doe
)
// $_FILES
Array
(
[file] => Array
(
[name] => example.txt
[type] => text/plain
[tmp_name] => C:\wamp64\tmp\php3016.tmp
[error] => 0
[size] => 14
)
)
?>
Since the request is an array (and not a string), curl will automatically encode the data as
"multipart/form-data".
Please be aware that if you pass an invalid file path to CURLFile, setting the CURLOPT_POSTFIELDS
option will fail.
So if you are using curl_setopt_array for setting the options at once, according to the manual,
"If an option could not be successfully set, FALSE is immediately returned, ignoring any future
options in the options array.".
So you should make sure that the file exists or set CURLOPT_POSTFIELDS with curl_setopt() and check
if it returns false and act accordingly.
----
Server IP: 45.112.84.4
Probable Submitter: 185.85.3.174 (proxied: 93.217.220.185)
----
Manual Page -- http://php.net/manual/en/function.curl-setopt.php
Edit -- https://master.php.net/note/edit/125490
Del: integrated -- https://master.php.net/note/delete/125490/integrated
Del: useless -- https://master.php.net/note/delete/125490/useless
Del: bad code -- https://master.php.net/note/delete/125490/bad+code
Del: spam -- https://master.php.net/note/delete/125490/spam
Del: non-english -- https://master.php.net/note/delete/125490/non-english
Del: in docs -- https://master.php.net/note/delete/125490/in+docs
Del: other reasons-- https://master.php.net/note/delete/125490
Reject -- https://master.php.net/note/reject/125490
Search -- https://master.php.net/manage/user-notes.php