curl_multi_add_handle
(PHP 5)
curl_multi_add_handle — Добавляет обычный cURL дескриптор к набору cURL дескрипторов
Описание
int curl_multi_add_handle
( resource
$mh
, resource $ch
)
Добавляет дескриптор ch
к набору дескрипторов
mh
Список параметров
-
mh
-
Мульти-дескриптор cURL, полученный из curl_multi_init().
-
ch
-
Дескриптор cURL, полученный из curl_init().
Возвращаемые значения
Возвращает 0 при успехе, или один из кодов ошибок CURLM_XXX
.
Примеры
Пример #1 Пример использования curl_multi_add_handle()
Этот пример создаст два дескриптора cURL, добавит их в набор дескрипторов, а затем запустит их паралелльно.
<?php
// создаем оба ресурса cURL
$ch1 = curl_init();
$ch2 = curl_init();
// устанавливаем URL и другие соответствующие опции
curl_setopt($ch1, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch1, CURLOPT_HEADER, 0);
curl_setopt($ch2, CURLOPT_URL, "http://www.php.net/");
curl_setopt($ch2, CURLOPT_HEADER, 0);
//создаем набор дескрипторов cURL
$mh = curl_multi_init();
//добавляем два дескриптора
curl_multi_add_handle($mh,$ch1);
curl_multi_add_handle($mh,$ch2);
$running=null;
//запускаем дескрипторы
do {
curl_multi_exec($mh,$running);
} while($running > 0);
//закрываем все дескрипторы
curl_multi_remove_handle($mh, $ch1);
curl_multi_remove_handle($mh, $ch2);
curl_multi_close($mh);
?>
Смотрите также
- curl_multi_remove_handle() - Удаляет cURL дескриптор из набора cURL дескрипторов
- curl_multi_init() - Создает набор cURL-дескрипторов
- curl_init() - Инициализирует сеанс cURL
- PHP Руководство
- Функции по категориям
- Индекс функций
- Справочник функций
- Другие службы
- Клиентская библиотека работы с URL
- curl_close
- curl_copy_handle
- curl_errno
- curl_error
- curl_escape
- curl_exec
- curl_file_create
- curl_getinfo
- curl_init
- curl_multi_add_handle
- curl_multi_close
- curl_multi_exec
- curl_multi_getcontent
- curl_multi_info_read
- curl_multi_init
- curl_multi_remove_handle
- curl_multi_select
- curl_multi_setopt
- curl_multi_strerror
- curl_pause
- curl_reset
- curl_setopt_array
- curl_setopt
- curl_share_close
- curl_share_init
- curl_share_setopt
- curl_strerror
- curl_unescape
- curl_version
Коментарии
The 'do' loop in this example will cycle indefinitely until all curl downloads complete, needlessly using CPU cycles. A much better way is to block while dowloads are in progress. Refer to the example code on the curl_multi_exec() page instead, which does this!
$nodes = array('http://www.google.com', 'http://www.microsoft.com', 'http://yahoo.com');
$node_count = count($nodes);
$curl_arr = array();
$master = curl_multi_init();
for($i = 0; $i < $node_count; $i++)
{
$url =$nodes[$i];
$curl_arr[$i] = curl_init($url);
curl_setopt($curl_arr[$i], CURLOPT_RETURNTRANSFER, true);
curl_multi_add_handle($master, $curl_arr[$i]);
}
do {
curl_multi_exec($master,$running);
} while($running > 0);
echo "results: ";
for($i = 0; $i < $node_count; $i++)
{
$results = curl_multi_getcontent ( $curl_arr[$i] );
echo( $i . "\n" . $results . "\n");
}
echo 'done';
Sometime with arrays and loops (i.e. for or do while or foreach) curl_multi_init loses some hits, to work around this problem it is necessary to divide the loop into two parts: the start with key number zero and than, all the rest. In this way the curl_multi_init doesn't lose any hits. I did a lot of test and it seems to work well enough.
<?php
function set_option($x, $y){
curl_setopt($x, CURLOPT_URL, $y);
curl_setopt($x, CURLOPT_HEADER, 0);
curl_setopt($x, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($x, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($x, CURLOPT_ENCODING, "gzip,deflate");
}
$nodes = array('http://php.net/manual/it/function.curl-multi-add-handle.php',
'function.curl-multi-init',
'function.curl-multi-setopt'
);
$node_count = count($nodes);
$curl_arr = array();
$master = curl_multi_init();
/*
now I put the first part of the array with the start key number zero, add all
options and add the curl_multi_add_handle;
it is necessary to detach this first part to avoid to lose some handles and than running
the loop with the start key number one.
In this way the curl_multi_init doesn't lose anything and seems to be very stable.
*/
$curl_arr[0] = curl_init($nodes[0]);
set_option($curl_arr[0], $nodes[0]);
curl_multi_add_handle($master, $curl_arr[0]);
/*
now the loop can start with key number one
*/
$i = 1;
do {
if ($i!==0){
$curl_arr[$i] = curl_init($nodes[$i]);
set_option($curl_arr[$i], $nodes[$i]);
curl_multi_add_handle($master, $curl_arr[$i]);
}
$i++;
}while($i < $node_count);
$running = NULL;
do {
curl_multi_exec($master,$running);
} while($running);
$results = array();
$q = 0;
do{
$results[$q] = curl_multi_getcontent($curl_arr[$q]);
curl_multi_remove_handle($master, $curl_arr[$q]);
$q++;
}while($q < $node_count);
foreach($results as $value){
echo $value;
}
?>
Разрешение на строительство — это официальный документ, выписываемый полномочными органами государственного аппарата или местного управления, который позволяет начать строительную деятельность или осуществление строительных операций.
<a href=https://rns-50.ru/>Разрешение на строительство</a> формулирует юридические основы и стандарты к строительным операциям, включая допустимые категории работ, разрешенные материалы и подходы, а также включает строительные инструкции и комплекты безопасности. Получение разрешения на возведение является необходимым документов для строительной сферы.
Разрешение на строительство — это государственный удостоверение, предоставленный правомочными ведомствами государственного управления или территориального самоуправления, который дает возможность начать стройку или исполнение строительного процесса.
<a href=https://rns-50.ru/>Получение разрешения на строительство</a> предписывает законодательные основания и стандарты к строительству, включая разрешенные категории работ, предусмотренные материалы и методы, а также включает строительные нормативные акты и комплексы охраны. Получение разрешения на строительную деятельность является обязательным документов для строительной сферы.
Fatiguing hemp products has been perfectly the journey. As someone keen on unpretentious remedies, delving into the in every respect of hemp has been eye-opening. From THC tinctures to hemp seeds and protein competency, I've explored a miscellany of goods. Teeth of the misunderstanding adjoining hemp, researching and consulting experts receive helped navigate this burgeoning field. Entire, my sophistication with hemp has been favourable, sacrifice holistic well-being solutions and sustainable choices.
Trying https://www.nothingbuthemp.net/online-store/THC-EDIBLES-c133547252 has been somewhat the journey. As someone pointed on unpretentious remedies, delving into the in every respect of hemp has been eye-opening. From THC tinctures to hemp seeds and protein powder, I've explored a type of goods. Regard for the disorder surrounding hemp, researching and consulting experts have helped pilot this burgeoning field. Overall, my sophistication with hemp has been despotic, contribution holistic well-being solutions and sustainable choices.