【问题标题】:random(non- repeating) file generator on click of button in php单击 php 中的按钮时随机(非重复)文件生成器
【发布时间】:2018-09-29 19:15:54
【问题描述】:

我想随机显示 5 个 php 文件内容,但 不重复 当使用 php/javascript(也适用于 php 桌面)单击按钮 [NEXT] 时。

我使用的代码在页面加载时确实显示了随机网页,但我确实遇到了重复的网页

这是我用于 index.php 文件的代码:

<?php
$RandomList = array();
$RandomList[] = "/review/review-a1.php";
$RandomList[] = "/review/review-a2.php";
$RandomList[] = "/review/review-a3.php";
$RandomList[] = "/review/review-a4.php";
readfile($_SERVER['DOCUMENT_ROOT'].$RandomList[rand(0,count($RandomList)-1)]);
?>

请建议如何获取非重复文件。

【问题讨论】:

  • $RandomList 中选择一个文件后,当您随机重新选择一个文件时,只需将其从该列表中删除即可。使用unset()。如果您想将列表保留在多个浏览量中,您需要使用sessions
  • 您能否详细说明一下,因为我是这些代码的新手!

标签: php random webpage


【解决方案1】:

只需保存您已在session 中使用的路径:

//Read visited paths from session or create a new list. 
//?? works only in PHP7+. Use isset()?: instead of ?? for previous versions
$visitedPaths = $_SESSION['visitedPaths'] ?? [];

//Your list, just slightly changed syntax. Same thing
$randomList = [
    "/review/review-a1.php",
    "/review/review-a2.php",
    "/review/review-a3.php",
    "/review/review-a4.php"
];

//Remove all paths that were already visited from the randomList
$randomList = array_diff($randomList, $visitedPaths);

//You need to check now if there are paths left
if (!empty($randomList)) {
    //The user did not load all files, so we can show him the next one
    //Use array_rand() rather than $array[rand(0, count($array) -1)]
    $randomPath = $randomList[array_rand($randomList)];
    readfile($_SERVER['DOCUMENT_ROOT'] . $randomPath);

    //Now we need to save, that the user loaded this file
    $visitedPaths[] = $randomPath;

    //And we need to save the new list in the session
    $_SESSION['visitedPaths'] = $visitedPaths;
} else {
    //TODO: Add some logic in case all paths have been visited
}

【讨论】:

  • 感谢您的帮助,我已将链接添加到 final 5th - 最后一页到 else 部分............ ........但我仍然得到访问页面的代表!!!
  • 还有一件事,现在我刚刚将$randomList = [ "/review/review-a1.php", "/review/review-a2.php", "/review/review-a3.php", "/review/review-a4.php" ]; 更改为$randomList = [ "review1.php", "review2.php", "review3.php", "review4.php", ];
  • 试过你编辑的版本。但仍然得到----> 警告:readfile**([my-local-url-of-the-file-here]):**无法打开流:没有这样的文件或目录在第 23 行的 [my-local-url-of-the-file-here] 中
  • 在此服务器上未找到请求的 URL /rnd-norep.php。 在 wamp 上使用时显示。 .................. 上述之前讨论过的代码我一直在 php desktop 环境 上运行
  • @user9616292 嘿。 “警告:readfile() 无法打开流。” 表示您尝试打开的路径不存在。该文件不存在或存储在不同的文件夹中。试试var_dump( [my-local-url-of-the-file-here])(debug),看看需要的路径是不是真的就是存放文件的路径。第二个问题是等价的。遗憾的是,我怀疑我们是否可以帮助您解决这些问题,但它们通常可以通过调试轻松解决
猜你喜欢
  • 1970-01-01
  • 2017-11-05
  • 2011-11-24
  • 2013-02-14
  • 1970-01-01
  • 2014-06-10
  • 1970-01-01
  • 2016-07-21
  • 1970-01-01
相关资源
最近更新 更多