Truthworthy
Truthworthy

Reputation: 1

Random link php

I am trying to setup this code that loads a random link but I have one problem:

$links = file('myfile.txt');
$rand_link = $links[ mt_rand(0, count($links) - 1) ];
echo '<div class="link"><a href="' . $rand_link . '"><img src="button.png" border="0"></a></div>';

It sometimes shows the pages it has shown earlier. I want it to remember what sites it has displayed and don’t show it again until the user starts from the beginning. Thanks appreciate your help.

Upvotes: 0

Views: 1209

Answers (2)

Samuel Herzog
Samuel Herzog

Reputation: 3611

finally the enhanced version with multiple sites in history

// Predefinitions
$links = file('myfile.txt');
$currentPage = $_SERVER['PHP_SELF'];

// make sure links are pure and no whitespaces are left
foreach ( $links as &$link )
{
    $link = trim($link);
}

// prepare for history
if ( ! array_key_exists('visited_links', $_SESSION) )
{
    $_SESSION['visited_links'] = array();
}
// add current site to visited links if it wasnt visited earlier
if ( ! in_array($currentPage, $_SESSION['visited_links']) )
{
    $_SESSION['visited_links'][] = $currentPage; 
}

// get all those links which weren't visited yet kinda $links = $allLinks - $visitedLinks
$potentialLinks = array_diff($links, $_SESSION['visited_links']);

$randomLinkId = mt_rand(0, count($potentialLinks)-1);
$randomLinkIds = array_keys($potentialLinks);
$randomLink = $potentialLinks[$randomLinkIds[$randomLinkId]];


echo '<div class="link"><a href="'.$randomLink.'"><img src="button.png" border="0"></a></div>';

there could be potential errors if the format of $_SERVER['PHP_SELF'] and this of your linklist differ, you can evaluate this with some quick var_dumps. As far as I know Wordpress automatically starts an session, this should explain your errormessage. This script assumes that the session is already started.

Upvotes: 2

Zhasulan Berdibekov
Zhasulan Berdibekov

Reputation: 1087

Try this code. May be errors, I have not tested on the server. And I use the session to preserve already viewed pages.

$links = file('myfile.txt');
$show_links = array();

session_start();

if( $_SESSION['show_links'] )
foreach($_SESSION['show_links'] as $key=>$value){
    $show_links[$key] = $value;
}

$random_link_number = mt_rand(0, count($links) - 1);

if(count($show_links) != count($links)){
while(   !in_array($random_link_number, $show_links)   ){
   $random_link_number = mt_rand(0, count($links) - 1);
}
}
else{
    unset($show_links);
}

$show_links[] = $random_link_number;
$_SESSION['show_links'] = $show_links;

$rand_link = $links[ $random_link_number ];

Upvotes: 0

Related Questions