Created
December 18, 2012 06:55
-
-
Save mgng/4325675 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* fetch_multi_url | |
* | |
* @param array $urls URLの配列 | |
* @param integer $timeout タイムアウト秒数、default0秒(タイムアウトなし) | |
* @return array 結果レスポンス一覧 | |
*/ | |
function fetch_multi_url( $urls, $timeout = 0 ){ | |
$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_FAILONERROR, 1 ); | |
curl_setopt( $conn[$i], CURLOPT_FOLLOWLOCATION, 1 ); | |
curl_setopt( $conn[$i], CURLOPT_MAXREDIRS, 3 ); | |
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]); | |
} | |
$running = null; | |
do { | |
usleep( 10000 ); | |
curl_multi_exec( $mh, $running ); | |
} while( $running > 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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
1355813678 | |
1355813681 | |
1355813684 | |
1355813687 | |
--------------- | |
Array | |
( | |
[0] => 1355813691 | |
[1] => 1355813691 | |
[2] => 1355813691 | |
[3] => 1355813691 | |
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
require_once 'fetch_multi_url.php'; | |
$urls = array( | |
'http://localhost/test.php?1', | |
'http://localhost/test.php?2', | |
'http://localhost/test.php?3', | |
'http://localhost/test.php?4', | |
); | |
// 一個ずつ | |
foreach( $urls as $url ) { | |
echo file_get_contents( $url ), "\n"; | |
} | |
echo "---------------\n"; | |
// まとめて | |
print_r( fetch_multi_url( $urls, 5) ); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
sleep(3); | |
echo time(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment