Welcome to WebmasterWorld Guest from 54.198.93.179

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

Using php curl to fetch URLs.

     
6:11 pm on Apr 30, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Is this code correct for getting and executing multiple URLs, and is there any way to shorten it to having the $ch fetch each URL instead of making a new $ch for each URL?

<?php
$ch = curl_init('http://www.whatever.com/');
curl_exec($ch);
curl_close($ch);

$ch2 = curl_init('http://www.whatever.com');
curl_exec($ch2);
curl_close($ch2);

$ch3 = curl_init('http://www.whatever.com');
curl_exec($ch3);
curl_close($ch3);
?>

I'm just trying to have one php script be the file my servers cron job get's instead of a bunch of different URLs, and so I don't have to come on SSH and update the cron file every time I wanna change it. FTPs much easier!
7:10 pm on Apr 30, 2010 (gmt 0)

WebmasterWorld Senior Member rocknbil is a WebmasterWorld Top Contributor of All Time 10+ Year Member



First, no need for $ch, $ch2, $ch3. As you execute inline like that, you can recycle each variable, you no longer need the previous value so let the next one overwrite it.

With that in mind,


<?php
//
$urls = Array(
'http://www.example.com/',
'http://www.example2.com/'
'http://www.example3.com/'
);
//
foreach ($urls as $url) {
$ch = curl_init($url);
curl_exec($ch);
curl_close($ch);
}
?>


If there are specific actions for each url, like stored in different files, etc., use an associative array instead.


<?php
//
$urls = Array(
'example.txt' => 'http://www.example.com/',
'example2.txt' => 'http://www.example2.com/'
'example3.txt' => 'http://www.example3.com/'
);
//
foreach ($urls as $text=>$url) {
$ch = curl_init($url);
curl_exec($ch);
curl_close($ch);
// Stoe $ch in $text
}
?>


Of course, in this case it's as easy to build '', "2", and "3" on the fly, but you get the point . . . )

Take it one step further, if there's tons of URL's, read them from a database or a delimited text file to build the arrays, just easier to maintain.
 

Featured Threads

Hot Threads This Week

Hot Threads This Month