From 80ab3216d54c3aa22288d60a40c7fd0dafac77cb Mon Sep 17 00:00:00 2001 From: Joshua Ramon Enslin Date: Thu, 12 Aug 2021 13:57:25 +0200 Subject: [PATCH] Allow setting headers when running MD_STD::runCurl --- src/MD_STD.php | 34 ++++++++++++++++++++++------------ 1 file changed, 22 insertions(+), 12 deletions(-) diff --git a/src/MD_STD.php b/src/MD_STD.php index 0e78530..1aec7da 100644 --- a/src/MD_STD.php +++ b/src/MD_STD.php @@ -288,15 +288,20 @@ final class MD_STD { /** * Wrapper for curling contents from the web. * - * @param string $url URL to query. - * @param integer $timeout Timeout in milliseconds. + * @param string $url URL to query. + * @param integer $timeout Timeout in milliseconds. + * @param array $headers HTTP headers to pass on. + * Analogous to CURLOPT_HTTPHEADER. * * @return string */ - public static function runCurl(string $url, int $timeout = 1200):string { + public static function runCurl(string $url, int $timeout = 1200, array $headers = []):string { $curl = self::curl_init($url, $timeout); \curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); + if (!empty($headers)) { + \curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); + } $result = \curl_exec($curl); @@ -317,38 +322,43 @@ final class MD_STD { * * @param array $urls URL to query. * @param integer $timeout Timeout in milliseconds. + * @param array $headers HTTP headers to pass on. + * Analogous to CURLOPT_HTTPHEADER. * * @return array */ - public static function runCurlMulti(array $urls, int $timeout = 1200):array { + public static function runCurlMulti(array $urls, int $timeout = 1200, array $headers = []):array { - $mh = curl_multi_init(); + $mh = \curl_multi_init(); $curl_array = []; foreach($urls as $i => $url) { $curl_array[$i] = self::curl_init($url, $timeout); - curl_setopt($curl_array[$i], CURLOPT_RETURNTRANSFER, true); - curl_multi_add_handle($mh, $curl_array[$i]); + \curl_setopt($curl_array[$i], CURLOPT_RETURNTRANSFER, true); + if (!empty($headers)) { + \curl_setopt($curl_array[$i], CURLOPT_HTTPHEADER, $headers); + } + \curl_multi_add_handle($mh, $curl_array[$i]); } $running = null; do { - usleep(10000); - curl_multi_exec($mh, $running); + \usleep(10000); + \curl_multi_exec($mh, $running); } while($running > 0); $res = []; foreach($urls as $i => $url) { - $res[$i] = curl_multi_getcontent($curl_array[$i]) ?: ''; + $res[$i] = \curl_multi_getcontent($curl_array[$i]) ?: ''; } foreach($urls as $i => $url){ - curl_multi_remove_handle($mh, $curl_array[$i]); + \curl_multi_remove_handle($mh, $curl_array[$i]); } - curl_multi_close($mh); + \curl_multi_close($mh); return $res;