curl_setopt_array

(PHP 5 >= 5.1.3, PHP 7, PHP 8)

curl_setopt_arrayCURL 転送用の複数のオプションを設定する

説明

curl_setopt_array(CurlHandle $handle, array $options): bool

cURL セッション用の複数のオプションを設定します。 この関数が便利なのは大量の cURL オプションを設定する場合で、 何度も繰り返して curl_setopt() をコールせずにすみます。

パラメータ

handle

curl_init() が返す cURL ハンドル。

options

設定するオプションとその値を指定した配列。キーとして使用できるのは、 有効な curl_setopt() 定数か、 その定数に対応する整数値だけです。

戻り値

すべてのオプションがうまく設定できた場合に true を返します。 うまく設定できないオプションがあった時点で即時に false が返され、options 配列に含まれるそれ以降のオプションは無視されます。

変更履歴

バージョン 説明
8.0.0 handleCurlHandle クラスのインスタンスを期待するようになりました。 これより前のバージョンでは、resource を期待していました。

例1 新規に CURL セッションを初期化、ウェブページを取得する

<?php
// 新しい cURL リソースを作成します
$ch = curl_init();

// URL その他のオプションを適切に設定します
$options = array(CURLOPT_URL => 'http://www.example.com/',
CURLOPT_HEADER => false
);

curl_setopt_array($ch, $options);

// URL の内容を取得し、ブラウザに渡します
curl_exec($ch);

// cURL リソースを閉じ、システムリソースを開放します
curl_close($ch);
?>

注意

注意:

curl_setopt() と同様、配列を CURLOPT_POST に渡すとデータを multipart/form-data でエンコードします。 一方 URL エンコードされた文字列を渡すと、データを application/x-www-form-urlencoded でエンコードします。

参考

add a note add a note

User Contributed Notes 10 notes

up
17
Lionel
9 years ago
If you are writing a mini API for your library, and if you are doing merging of options, remember to use the union operator (+) !

So something like this will definitely fail. This is because array_merge effectively resets all the keys in the array into running numbers:

<?php
function post($url, $options = array) {
   
$ch = curl_init();
   
curl_setopt_array($ch, array_merge(array(
       
CURLOPT_HEADER => 1,
       
CURLOPT_RETURNTRANSFER => 1,
        .....
     )));
?>

Rather, this is the correct way of doing it:

<?php
function post($url, $options = array) {
   
$ch = curl_init();
   
curl_setopt_array($ch, array(
       
CURLOPT_HEADER => 1,
       
CURLOPT_RETURNTRANSFER => 1,
        .....
     ) + (array)
$options);
?>
up
16
maran dot emil at gmail dot com
15 years ago
In case that you need to read SSL page content from https with curl, this function can help you:

<?php

function get_web_page( $url,$curl_data )
{
   
$options = array(
       
CURLOPT_RETURNTRANSFER => true,         // return web page
       
CURLOPT_HEADER         => false,        // don't return headers
       
CURLOPT_FOLLOWLOCATION => true,         // follow redirects
       
CURLOPT_ENCODING       => "",           // handle all encodings
       
CURLOPT_USERAGENT      => "spider",     // who am i
       
CURLOPT_AUTOREFERER    => true,         // set referer on redirect
       
CURLOPT_CONNECTTIMEOUT => 120,          // timeout on connect
       
CURLOPT_TIMEOUT        => 120,          // timeout on response
       
CURLOPT_MAXREDIRS      => 10,           // stop after 10 redirects
       
CURLOPT_POST            => 1,            // i am sending post data
          
CURLOPT_POSTFIELDS     => $curl_data,    // this are my post vars
       
CURLOPT_SSL_VERIFYHOST => 0,            // don't verify ssl
       
CURLOPT_SSL_VERIFYPEER => false,        //
       
CURLOPT_VERBOSE        => 1                //
   
);

   
$ch      = curl_init($url);
   
curl_setopt_array($ch,$options);
   
$content = curl_exec($ch);
   
$err     = curl_errno($ch);
   
$errmsg  = curl_error($ch) ;
   
$header  = curl_getinfo($ch);
   
curl_close($ch);

 
//  $header['errno']   = $err;
  //  $header['errmsg']  = $errmsg;
  //  $header['content'] = $content;
   
return $header;
}

$curl_data = "var1=60&var2=test";
$url = "https://www.example.com";
$response = get_web_page($url,$curl_data);

print
'<pre>';
print_r($response);

?>
up
3
bendavis78 at gmail dot com
18 years ago
You can use CURLOPT_HEADERFUNCTION  with a callback inside an object.  This makes is it easy to capture the headers for later use.  For example:

<?php
class Test
{
    public
$headers;

   
//...

   
public function exec($opts)
    {
       
$this->headers = array();
       
$opts[CURLOPT_HEADERFUNCTION] = array($this, '_setHeader');
       
$ch = curl_init();
       
curl_setopt_array($ch, $opts);
        return
curl_exec($ch);
    }

    private function
_setHeader($ch, $header)
    {
       
$this->headers[] = $header;
        return
strlen($header);
    }

   
}

$test = new Test();
$opts = array(
  
//... your curl opts here
);
$data = $test->exec($opts);
print_r($test->headers);
?>

...something like that

(This works in php v. 5.1.4)
up
1
lawrence at dub3solutions dot com
5 years ago
This function does not mix with `curl_file_create` (`CURLFile` object) and `CURLOPT_POSTFIELDS`. Took me forever to figure out, but essentially I was getting an "Invalid filename" PHP warning and the files weren't being sent. I was able to correct the issue in a matter like so:

curl_setopt_array($curl, $curlOpts);
curl_setopt($curl, CURLOPT_POSTFIELDS, $postFields);

I removed the `$postFields` value from `$curlOpts` and set it separately using `curl_setopt`.
up
2
Al
7 years ago
You might be tempted to use array_merge with arrays where CURLOPT constants are the keys, but beware.

<?php
array_merge
([], [CURLOPT_FOO => "foo"], [CURLOPT_BAR => "bar"]);
?>

Since these constants are numeric, array_merge will happily reindex:

<?php
[0 => "foo", 1 => "bar"];
?>
up
1
anthon at piwik dot org
14 years ago
Starting in PHP 5.2.0, CURLOPT_FOLLOWLOCATION can't be set via curl_setopt_array() (or curl_setopt()) when either safe_mode is enabled or open_basedir is set.  In these cases, the order of CURLOPT_* settings in the array can be important.
up
1
mad_elf at maranelda dot org
2 years ago
Important note: the option CURLINFO_HEADER_OUT is *ignored* by curl_setopt_array(). You *must* use curl_setopt() to set this option.

(True in PHP v7.3.27 at least)
up
0
Alexander
8 years ago
Once upon a time I've got an error like "Problem with the SSL CA cert (path? access rights?)". Since what I was doing was pretty much an administrative task with no actual security issues involved, I decided to disallow certificate validation and this is where the most interesting stuff began.

First I did it like this and it worked:

        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);

Next I thought, "But hey, I don't want any hardcoded stuff here. Let's use it in a configurable way!". And so I did something like this:

// in configuration
$CURL_OPTIONS = array(CURLOPT_SSL_VERIFYPEER => 0, CURLOPT_SSL_VERIFYHOST => 0);

...........

// in place of two direct calls from earlier
            curl_setopt_array($ch, $CURL_OPTIONS);

And I was so happy, there was no error anymore... and do you think I was happy for a long time? If so, then you're wrong. It stopped giving an error, while it didn't start to work!

I checked the actual data but they were allright. Then I thought: "Is it the curl_setopt_array() problem? Let's make it a cycle." The way it is mentioned in this help, actually.

            foreach ($CURL_OPTIONS as $name => $value)
            {
                curl_setopt($ch, $name, $value);
            }

And... it did not work the same way as with the curl_setopt_array() call. And the data were still allright...

So, if by chance you can't set CURL options with the curl_setopt_array() call, then now you know what to do and you know it is definitely not you who is to blame.

P.S.
By the way, the configuration used was:
Linux i-ween.com 3.2.0-4-amd64 #1 SMP Debian 3.2.73-2+deb7u3 x86_64
PHP Version 5.5.17
up
-7
fnjordy at gmail dot com
16 years ago
There is no CURLOPT_MAXFILESIZE in the PHP module but it's function only works with Content-Length headers anyway.  There are two ways of checking download sizes, one is after the download is complete using filesize(), the other is as the download is running allowing you to terminate before wasting time and disk space.

<?php
$GLOBALS
['file_size'] = 0;
$GLOBALS['max_file_size'] = 1024 * 1024;
function
on_curl_header($ch, $header)
{
   
$trimmed = rtrim($header);   
    if (
preg_match('/^Content-Length: (\d+)$/', $trimmed, $matches))
    {
       
$file_size = $matches[1];
        if (
$file_size > $GLOBALS['max_file_size']) {
           
// handle error here.
       
}
    }
    return
strlen($header);
}

function
on_curl_write($ch, $data)
{
   
$bytes = strlen($data);
   
$GLOBALS['file_size'] += $bytes;
    if (
$GLOBALS['file_size'] > $GLOBALS['max_file_size']) {
       
// handle error here.
   
}
    return
$bytes;
}

$ch = curl_init();
$options = array(CURLOPT_URL        => 'http://www.php.net/',
        
CURLOPT_HEADER        => false,
        
CURLOPT_HEADERFUNCTION    => 'on_curl_header',
        
CURLOPT_WRITEFUNCTION    => 'on_curl_write');
curl_setopt_array($ch, $options);
curl_exec($ch);
// ...
?>
up
-8
loop4u at gmail dot com
13 years ago
it should be noted that when using CURLOPT_POSTFIELDS in a loop, CURLOPT_POSTFIELDS appends to the sting. You can use unset() if you don't want this sort of behavior.

<?php
//this will append postfields

while(true) {
   
$options = array(CURLOPT_POSTFIELDS => 'foo=bar&foo2=bar');
   
$ch = curl_init("http://www.example.com");
   
curl_setopt_array($ch, $options);
   
curl_exec($ch);
   
curl_close($ch);
}

//this will NOT append postfields
while(true) {
   
$options = array(CURLOPT_POSTFIELDS => 'foo=bar&foo2=bar');
   
$ch = curl_init("http://www.example.com");
   
curl_setopt_array($ch, $options);
   
curl_exec($ch);
   
curl_close($ch);
    unset(
$options[CURLOPT_POSTFIELDS]);
}
?>
To Top