随机链接php

时间:2011-01-09 08:40:22

标签: php random

我正在尝试设置加载随机链接的代码,但我有一个问题:

$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>';

它有时会显示之前显示的页面。我想让它记住它显示的网站,并且在用户从头开始之前不再显示它。谢谢你的帮助。

2 个答案:

答案 0 :(得分:2)

最后是历史上有多个网站的增强版

// 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>';

如果$_SERVER['PHP_SELF']的格式与您的链接列表的格式不同,则可能存在潜在错误,您可以使用一些快速的var_dump来评估此错误。 据我所知,Wordpress会自动启动会话,这可以解释您的错误消息。此脚本假定会话已启动。

答案 1 :(得分:0)

试试这段代码。可能是错误,我还没有在服务器上测试过。我使用会话来保存已经查看的页面。

$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 ];