homepage Welcome to WebmasterWorld Guest from 54.204.77.26
register, free tools, login, search, subscribe, help, library, announcements, recent posts, open posts,
Subscribe to WebmasterWorld
Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
Forum Library, Charter, Moderators: coopster & jatar k

PHP Server Side Scripting Forum

    
Using php curl to fetch URLs.
Jesse_Smith




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

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!

 

rocknbil




msg:4125137
 7:10 pm on Apr 30, 2010 (gmt 0)

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.

Global Options:
 top home search open messages active posts  
 

Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved