以下代码出现问题:
<?php
$con = mysql_connect("localhost","","");
if (!$con){
die('Could not connect: ' . mysql_error());
}
mysql_select_db("abcdatabase", $con);
$ids = intval($_GET['id']);
if ($ids==0){
$id = rand (0,50);
header("Location: http://index.php/?id=$id");
}
?>
它运行良好。但我想要更多的东西。当我在浏览器中放入index.php
时,它会随机转到类似index.php?id=30
的页面。但在转到页面index.php?id=30
之后,如果我按下浏览器的刷新按钮,它仍然保持在同一页面中。我希望每次刷新页面时,它都会用随机id
加载新页面。但是,如果有人试图访问页面index.php?id=30
,他将获得具有id=30
的页面。
我是个程序员新手。任何人都请帮我提出这个问题。
如果您每次都想要一个随机页面,请不要执行重定向:
$ids = rand (1, 50);
// continue with your code here
顺便说一句,rand()
适用于包含的范围,所以您必须使用[1, 50]
,以免有时会得到0
。
好吧,在重新生成新ID之前,您可以检查$_GET['id']
是否为零。删除该代码,即可设置:
if (isset($_GET['id'])) {
$id = rand (0,50);
header("Location: http://index.php?id=$id");
}
现在,只要$_GET['id']
在那里,它就会生成一个新页面。如果你没有在URL中给出ID,你会得到一个普通的页面。
然而,这将导致一个无休止的循环。为什么要使用header
?就像这样:
$id = rand(0,50);
// use your ID to do whatever you want to do
您可以使用会话变量来存储加载的最后一个页面的id。如果你不跟踪$_GET['id'],你就有无限重定向的风险。
<?php
session_start();
$con = mysql_connect("localhost","","");
if (!$con){
die('Could not connect: ' . mysql_error());
}
mysql_select_db("abcdatabase", $con);
$ids = intval($_GET['id']);
if ($ids==0 || (isset($_SESSION['last_loaded']) && $_SESSION['last_loaded'] == $ids)){
$id = rand (0,50);
$_SESSION['last_loaded'] = $id;
header("Location: http://index.php/?id=$id");
exit;
}
?>
在header("Location: http://index.php/?id=$id");
之后添加exit()
header("Location: http://index.php/?id=$id");
exit();
免责声明:这就是我在喝了太多朗姆酒后凌晨2点的做法。
<?php
// If I don't have an id or the current uri == referrer uri then redirect
if (!isset($_GET["id"]) ||
(isset($_SERVER['HTTP_REFERER']) && $_SERVER['HTTP_REFERER'] ==
$_SERVER["REQUEST_URI"])){
header("Location: http://index.php/?id=".rand(1,50));
exit();
}
$con = mysql_connect("localhost","","");
if (!$con){
die('Could not connect: ' . mysql_error());
}
mysql_select_db("abcdatabase", $con);
// query and show the goods here
?>
这应该在地址栏中保留一个可导航的uri,并在刷新时显示一个新的随机值。评论中引用的许多优化也是集成的。