PDA

View Full Version : rotating random link



JimmyHumbled
10-21-2008, 06:51 PM
Hello - this is my first post and I am quite new to using PHP, I have nevver made a script of my own but feel competent making amends to open source ones I download.

I am quite an experienced HTML developer and designer and am working on a project where I have had a request to inset a text link on a page that will change at random between a selection of text links that are in a text file hosted on the server.

I have decided it will be a good investment to start to learn php and have downloaded a few tutorials and signed up to some forums but for the purpose of this page I wondered if anyone could advise me of a script that might be out there that could look at a text file located at www.randomurl.com/urls.txt and pull in a site at random or in rotation?

Thanks for taking the time to read

NXArmada
10-21-2008, 07:22 PM
Here is a simple script you can use. Provided for learning purposes. Place each <a> links on there own lines in the text file. I am sure there's better ways of doing.



<?php
$adfile = "urls.txt";
$ads = array();

$fh = fopen($adfile, "r");
while(!feof($fh)) {
$line = fgets($fh, 10240);
$line = trim($line);
if($line != "") {
$ads[] = $line;
}
}

$num = count($ads);
$idx = rand(0, $num-1);
echo $ads[$idx];
?>

BabblingIdjit
10-22-2008, 12:07 AM
Taking the same approach as NXArmada, you can trim the code down a bit.



<?php
$adfile = "urls.txt";

$ads = file($adfile);
$rand_ad = array_rand($ads);

echo $ads[$rand_ad];
?>

Nile
10-22-2008, 12:27 AM
Do you want random, or rotating. Both of the above are rotating.