curl_setopt
(PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8)
curl_setopt — cURL 転送用オプションを設定する
説明
指定した cURL セッションハンドルのオプションを設定します。
パラメータ
handle
curl_init() が返す cURL ハンドル。
option
-
The
CURLOPT_*
option to set. value
-
option
に設定する値。 それぞれの定数の値が期待する型の詳細については、CURLOPT_*
定数を参照ください。
変更履歴
例
例1 新規に cURL セッションを初期化、ウェブページを取得する
<?php
// 新しい cURL リソースを作成します
$ch = curl_init();
// URL その他のオプションを適切に設定します
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_HEADER, false);
// URL の内容を取得し、ブラウザに渡します
curl_exec($ch);
// cURL リソースを閉じ、システムリソースを開放します
curl_close($ch);
?>
注意
注意:
配列を
CURLOPT_POSTFIELDS
に渡すと、データを multipart/form-data でエンコードします。 一方 URL エンコードされた文字列を渡すと、データを application/x-www-form-urlencoded でエンコードします。
+add a note
User Contributed Notes 64 notes
rmckay at webaware dot com dot au ¶
12 years ago
Please everyone, stop setting CURLOPT_SSL_VERIFYPEER to false or 0. If your PHP installation doesn't have an up-to-date CA root certificate bundle, download the one at the curl website and save it on your server:
http://curl.haxx.se/docs/caextract.html
Then set a path to it in your php.ini file, e.g. on Windows:
curl.cainfo=c:\php\cacert.pem
Turning off CURLOPT_SSL_VERIFYPEER allows man in the middle (MITM) attacks, which you don't want!
joey ¶
8 years ago
It is important that anyone working with cURL and PHP keep in mind that not all of the CURLOPT and CURLINFO constants are documented. I always recommend reading the cURL documentation directly as it sometimes contains better information. The cURL API in tends to be fubar as well so do not expect things to be where you would normally logically look for them.
curl is especially difficult to work with when it comes to cookies. So I will talk about what I found with PHP 5.6 and curl 7.26.
If you want to manage cookies in memory without using files including reading, writing and clearing custom cookies then continue reading.
To start with, the way to enable in memory only cookies associated with a cURL handle you should use:
curl_setopt($curl, CURLOPT_COOKIEFILE, "");
cURL likes to use magic strings in options as special commands. Rather than having an option to enable the cookie engine in memory it uses a magic string to do that. Although vaguely the documentation here mentions this however most people like me wouldn't even read that because a COOKIEFILE is the complete opposite of what we want.
To get the cookies for a curl handle you can use:
curl_getinfo($curl, CURLINFO_COOKIELIST);
This will give an array containing a string for each cookie. It is tab delimited and unfortunately you will have to parse it yourself if you want to do anything beyond copying the cookies.
To clear the in memory cookies for a cURL handle you can use:
curl_setopt($curl, CURLOPT_COOKIELIST, "ALL");
This is a magic string. There are others in the cURL documentation. If a magic string isn't used, this field should take a cookie in the same string format as in getinfo for the cookielist constant. This can be used to delete individual cookies although it's not the most elegant API for doing so.
For copying cookies I recommend using curl_share_init.
You can also copy cookies from one handle to another like so:
foreach(curl_getinfo($curl_a, CURLINFO_COOKIELIST) as $cookie_line)
curl_setopt($curl, CURLOPT_COOKIELIST, $cookie_line);
An inelegant way to delete a cookie would be to skip the one you don't want.
I only recommend using COOKIELIST with magic strings because the cookie format is not secure or stable. You can inject tabs into at least path and name so it becomes impossible to parse reliably. If you must parse this then to keep it secure I recommend prohibiting more than 6 tabs in the content which probably isn't a big loss to most people.
A the absolute minimum for validation I would suggest:
/^([^\t]+\t){5}[^\t]+$/D
Here is the format:
#define SEP "\t" /* Tab separates the fields */
char *my_cookie =
"example.com" /* Hostname */
SEP "FALSE" /* Include subdomains */
SEP "/" /* Path */
SEP "FALSE" /* Secure */
SEP "0" /* Expiry in epoch time format. 0 == Session */
SEP "foo" /* Name */
SEP "bar"; /* Value */
ashw1 - at - no spam - post - dot - cz ¶
17 years ago
In case you wonder how come, that cookies don't work under Windows, I've googled for some answers, and here is the result: Under WIN you need to input absolute path of the cookie file.
This piece of code solves it:
<?php
if ($cookies != '')
{
if (substr(PHP_OS, 0, 3) == 'WIN')
{$cookies = str_replace('\\','/', getcwd().'/'.$cookies);}
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookies);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookies);
}
?>
Steve Kamerman ¶
13 years ago
If you want cURL to timeout in less than one second, you can use CURLOPT_TIMEOUT_MS, although there is a bug/"feature" on "Unix-like systems" that causes libcurl to timeout immediately if the value is < 1000 ms with the error "cURL Error (28): Timeout was reached". The explanation for this behavior is:
"If libcurl is built to use the standard system name resolver, that portion of the transfer will still use full-second resolution for timeouts with a minimum timeout allowed of one second."
What this means to PHP developers is "You can use this function without testing it first, because you can't tell if libcurl is using the standard system name resolver (but you can be pretty sure it is)"
The problem is that on (Li|U)nix, when libcurl uses the standard name resolver, a SIGALRM is raised during name resolution which libcurl thinks is the timeout alarm.
The solution is to disable signals using CURLOPT_NOSIGNAL. Here's an example script that requests itself causing a 10-second delay so you can test timeouts:
<?php
if (!isset($_GET['foo'])) {
// Client
$ch = curl_init('http://localhost/test/test_timeout.php?foo=bar');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_NOSIGNAL, 1);
curl_setopt($ch, CURLOPT_TIMEOUT_MS, 200);
$data = curl_exec($ch);
$curl_errno = curl_errno($ch);
$curl_error = curl_error($ch);
curl_close($ch);
if ($curl_errno > 0) {
echo "cURL Error ($curl_errno): $curl_error\n";
} else {
echo "Data received: $data\n";
}
} else {
// Server
sleep(10);
echo "Done.";
}
?>
qwertz182 ¶
4 years ago
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.
Philippe dot Jausions at 11abacus dot com ¶
18 years ago
Clarification on the callback methods:
- CURLOPT_HEADERFUNCTION is for handling header lines received *in the response*,
- CURLOPT_WRITEFUNCTION is for handling data received *from the response*,
- CURLOPT_READFUNCTION is for handling data passed along *in the request*.
The callback "string" can be any callable function, that includes the array(&$obj, 'someMethodName') format.
-Philippe
JScott jscott401 at gmail dot com ¶
14 years ago
Some additional notes for curlopt_writefunction. I struggled with this at first because it really isn't documented very well.
When you write a callback function and use it with curlopt_writefunction it will be called MULTIPLE times. Your function MUST return the ammount of data written to it each time. It is very picky about this. Here is a snippet from my code that may help you
<?php
curl_setopt($this->curl_handle, CURLOPT_WRITEFUNCTION, array($this, "receiveResponse"));
// later on in the class I wrote my receive Response method
private function receiveResponse($curlHandle,$xmldata)
{
$this->responseString = $xmldata;
$this->responseXML .= $this->responseString;
$this->length = strlen($xmldata);
$this->size += $this->length;
return $this->length;
}
?>
Now I did this for a class. If you aren't doing OOP then you will obviously need to modify this for your own use.
CURL calls your script MULTIPLE times because the data will not always be sent all at once. Were talking internet here so its broken up into packets. You need to take your data and concatenate it all together until it is all written. I was about to pull my damn hair out because I would get broken chunks of XML back from the server and at random lengths. I finally figured out what was going on. Hope this helps
cmatiasvillanueva at gmail dot com ¶
7 years ago
What is not mentioned in the documentation is that if you want to set a local-port or local-port-range to establish a connection is possible by adding CURLOPT_LOCALPORT and CURLOPT_LOCALPORTRANGE options.
Ex:
$conn=curl_init ('example.com');
curl_setopt($conn, CURLOPT_LOCALPORT, 35000);
curl_setopt($conn, CURLOPT_LOCALPORTRANGE, 200);
CURLOPT_LOCALPORT: This sets the local port number of the socket used for the connection.
CURLOPT_LOCALPORTRANGE: The range argument is the number of attempts libcurl will make to find a working local port number. It starts with the given CURLOPT_LOCALPORT and adds one to the number for each retry. Setting this option to 1 or below will make libcurl do only one try for the exact port number.
Interface can be also configured using CURLOPT_INTERFACE:
Ex:
curl_setopt($conn, CURLOPT_INTERFACE, "eth1");
sgamon at yahoo dot com ¶
16 years ago
If you are doing a POST, and the content length is 1,025 or greater, then curl exploits a feature of http 1.1: 100 (Continue) Status.
See http://www.w3.org/Protocols/rfc2616/rfc2616-sec8.html#sec8.2.3
* it adds a header, "Expect: 100-continue".
* it then sends the request head, waits for a 100 response code, then sends the content
Not all web servers support this though. Various errors are returned depending on the server. If this happens to you, suppress the "Expect" header with this command:
<?php
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:'));
?>
See http://www.gnegg.ch/2007/02/the-return-of-except-100-continue/
mw+php dot net at lw-systems dot de ¶
12 years ago
The description of the use of the CURLOPT_POSTFIELDS option should be emphasize, that using POST with HTTP/1.1 with cURL implies the use of a "Expect: 100-continue" header. Some web servers will not understand the handling of chunked transfer of post data.
To disable this behavior one must disable the use of the "Expect:" header with
curl_setopt($ch, CURLOPT_HTTPHEADER,array("Expect:"));
Ed Cradock ¶
14 years ago
PUT requests are very simple, just make sure to specify a content-length header and set post fields as a string.
Example:
<?php
function doPut($url, $fields)
{
$fields = (is_array($fields)) ? http_build_query($fields) : $fields;
if($ch = curl_init($url))
{
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Length: ' . strlen($fields)));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return (int) $status;
}
else
{
return false;
}
}
if(doPut('http://example.com/api/a/b/c', array('foo' => 'bar')) == 200)
// do something
else
// do something else.
?>
You can grab the request data on the other side with:
<?php
if($_SERVER['REQUEST_METHOD'] == 'PUT')
{
parse_str(file_get_contents('php://input'), $requestData);
// Array ( [foo] => bar )
print_r($requestData);
// Do something with data...
}
?>
DELETE can be done in exactly the same way.
Victor Jerlin ¶
15 years ago
Seems like some options not mentioned on this page, but listed on http://curl.haxx.se/libcurl/c/curl_easy_setopt.html is actually supported.
I was happy to see that I could actually use CURLOPT_FTP_CREATE_MISSING_DIRS even from PHP.
dweingart at pobox dot com ¶
21 years ago
If you want to Curl to follow redirects and you would also like Curl to echo back any cookies that are set in the process, use this:
<?php curl_setopt($ch, CURLOPT_COOKIEJAR, '-'); ?>
'-' means stdout
-dw
yann dot corno at free dot fr ¶
22 years ago
About the CURLOPT_HTTPHEADER option, it took me some time to figure out how to format the so-called 'Array'. It fact, it is a list of strings. If Curl was already defining a header item, yours will replace it. Here is an example to change the Content Type in a POST:
<?php curl_setopt ($ch, CURLOPT_HTTPHEADER, Array("Content-Type: text/xml")); ?>
Yann