The example below simulates the multithreading mechanism by initializating a new session and returns a cURL handle, sets the options for the http://www.google.ro and http://ro.yahoo.com/?p=us URLs, executes the cURL session and then prints the results using the curl_getinfo method:
<:!--?php
// Creating an array of URLs that will be used below
$urls_array = array('http://www.google.ro',' http://ro.yahoo.com/?p=us');
$curl_array = array();
// Initializes a new session and return a cURL multi handle for use with the curl_setopt(), curl_exec() and curl_close() functions
$curl_multi_handle = curl_multi_init();
// Use the urls_array array for initialize a single session, set the transfer and to add a normal cURL handle to a cURL multi handle
for($i = 0; $i < count($urls_array); $i++)
{
$url =$urls_array[$i];
//Initialize a single cURL session
$curl_array[$i] = curl_init($url);
//Setting the option for a cURL transfer
curl_setopt($curl_array[$i], CURLOPT_RETURNTRANSFER, true);
//Add a normal cURL handle to a cURL multi handle
curl_multi_add_handle($curl_multi_handle, $curl_array[$i]);
}
do {
//Run the sub-connections of the current cURL handle
curl_multi_exec($curl_multi_handle,$running);
} while($running > 0) ;
echo "results: ";
for($i = 0; $i < count($urls_array); $i++)
{
//Return the content of a cURL handle if CURLOPT_RETURNTRANSFER is set
$results = curl_multi_getcontent ( $curl_array[$i] );
echo $results;
}
?>
Figure 3: The above application simulates the cURL mechanism using some control structures and some of the most important cURL methods like curl_setopt, curl_multi_exec and curl_multi_getcontent.
Conclusion
In this article you have seen how to make the libcurl library functional in PHP, how to executes cURL sessions, how to print curl info like HTTP response code and content type, and how to simulates the cURL mechanism.
About the Author
Octavia Andreea Anghel is a senior PHP developer currently working as a primary trainer for programming teams that participate at national and international software-development contests. She consults on developing educational projects at a national level. She is a coauthor of the book "XML Technologies: XML in Java" (Albastra, ISBN 978-973-650-210-1), for which she wrote the XML portions. In addition to PHP and XML, she's interested in software architecture, web services, UML, and high-performance unit tests. to e-mail her.