Demo entry 6677910

multi_curl_example

   

Submitted by Synkc on Dec 04, 2017 at 19:59
Language: PHP. Code size: 1.1 kB.

<?php
	function fetch_multi_url( $urls, $timeout = 5 ){

		$mh = curl_multi_init();
		$conn = array();

		foreach( $urls as $i => $url) {
			$conn[$i] = curl_init( $url );
			curl_setopt( $conn[$i], CURLOPT_RETURNTRANSFER, true);
			curl_setopt( $conn[$i], CURLOPT_SSL_VERIFYPEER, false );
			curl_setopt( $conn[$i], CURLOPT_SSL_VERIFYHOST, false );

			if ( $timeout ){
			  curl_setopt( $conn[$i], CURLOPT_TIMEOUT, $timeout );
			}

			curl_multi_add_handle( $mh, $conn[$i] );
		}

		$health = null;
		
		do {
			usleep( 10000 );
			$mrc = curl_multi_exec( $mh, $health );
		} while( $health > 0 );

		$res = array();
		foreach( $urls as $i => $url ){
			$res[] = curl_multi_getcontent( $conn[$i] );
			curl_multi_remove_handle( $mh, $conn[$i] );
		}
		
		curl_multi_close($mh);
		return $res;
	}
	
	//URL
    $url_list = array(
        'https://naver.com',
        'https://daum.net'
        );

	//timeout 생략가능
    $curl_data = multi_url($url_list);
	
	//naver
	echo $curl_data[0];
	
	//daum
	echo $curl_data[1];
?>

This snippet took 0.01 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).