View Full Version : PHP pulling random line
jollyhumper
2021-08-24, 04:15 AM
Hi
Let's say a text document has 30 lines in it.
How could PHP be used to randomly pull one of those lines, each time the web page is built?
I'm looking to pull a random category or partner, or something, on my pages.
PHP is not my strongest side :)
Thanks anyhow
J|bow|lly
Greenguy
2021-08-24, 07:53 AM
I actually know this one!!! (not that I wrote it lol)
<?php
$file = "/home/domain.com/public_html/textfile.txt";
$banners = file($file);
srand((float) microtime() * 1235689);
$selected = array_rand($banners);
$SelBanner = trim($banners[$selected]);
if ($SelBanner=="") {
$SelBanner = trim($banners[0]);
};
echo $SelBanner;
?>
That will pull 1 line from the text file & insert it on the page. I've used it as a cheap banner rotator for years:
https://www.link-o-rama.com/greenguy/mlinks.htm
Greenguy
2021-08-24, 07:53 AM
...and yes I know there's useless code in there |couch|
jollyhumper
2021-08-24, 11:46 AM
Thanks! |shake|
I will try it as soon as I can. Hopefully this week.
|bow|
J|banana|lly
jollyhumper
2021-11-24, 12:55 PM
I actually know this one!!! (not that I wrote it lol)
It took a while before I tested it, but FYI, it works :-)
(Of course you knew it worked, I mean, it works for me too :-D )
Thanks again, appreciated
J|JollyHumper|lly
Greenguy
2021-11-25, 10:42 AM
|thumb
balas
2022-01-16, 11:27 AM
<?php
$f_contents = file("random_source.txt");
$line = $f_contents[rand(0, count($f_contents) - 1)];
?>
vBulletin® v3.8.1, Copyright ©2000-2026, Jelsoft Enterprises Ltd.