curl_multi_setopt()

1. 定义

该函数为一个curl批量会话中的所有传输句柄同时设置一个选项。

2. 语法

curl_multi_setopt ( resource $mh , int $option , mixed $value ) : bool

3. 参数说明

参数 可选性 数据类型 描述
$mh 必需 资源类型 通过函数curl_multi_init()打开的curl资源句柄
$option 必需 整型 CURLMOPT_*常量之一
$value 必需 mixed $option选项的值

4. 示例

<?php

// curl_multi_setopt()
// 为一个curl批量会话中的所有传输句柄同时设置一个选项

$urls = [
    'http://loripsum.net/api/5/short/headers',
    'http://loripsum.net/api/2/short/a/b/i'
];
$count = count($urls);
$mh = curl_multi_init();
foreach ($urls as $key => $value) {
    $ch[$key] = curl_init();
    curl_setopt($ch[$key], CURLOPT_URL, $value);
    curl_setopt($ch[$key], CURLOPT_RETURNTRANSFER, true);// 该项配置不允许在函数`curl_multi_setopt`中使用
    curl_multi_add_handle($mh, $ch[$key]);
}

curl_multi_setopt($mh, CURLMOPT_PIPELINING, 3);// 批量配置选项

// 批处理
$running = null;
do {
    curl_multi_exec($mh, $running);
}while($running > 0);

// 获取响应结果
foreach ($ch as $key => $value) {
    curl_multi_remove_handle($mh, $value);
}

// 关闭所有句柄
curl_multi_close($mh);