如何使JavaScript或PHP有条件重定向


How to make a JavaScript or PHP conditionally redirect?

基本上页面通过url http://sitename.com?c1=xxx&c2=yyy接收变量。

如果c1小于40,我想重定向到一个链接,否则转到主链接。

我如何编写这样的程序?

在PHP中使用

Header("Location: theurltoredirectto.com");

javascript的解决方案是

window.location = "http://www.theurltoredirectto.com/"

PHP中:

if ($_GET['c1'] < 40) {
   Header("Location: http://sitename.com/onelink");
} else {
   Header("Location: http://sitename.com");
}

在PHP中,它实际上是:

<?php
$c1 = int($_GET['c1']);
if ($c1 < 40)
    header('Location: http://new-location');
?>

执行完这段代码后,退出脚本

在javascript中可以使用top.location.href='http://your.url.here'window.location.href=...

在PHP中,您将希望在脚本的顶部使用以下代码,任何向页面输出数据的内容(如echo, print等)之前,因为头必须在任何其他数据之前发送:

<?php
if (is_numeric($_GET["c1"]) and $_GET["c1"] < 40) { //Checks if the c1 GET command is a number that is less than 40
    header("Location: /path/to/page2.php"); //Send a header to the browser that will tell it to go to another page
    die(); //Prevent the script from running any further
}

您可以将/path/to/page2.php位设置为通常用于<a>标记的任何位。

我不建议在JavaScript或HTML中进行重定向,因为如果有人在浏览器中单击Back,他们将被带回到该页面并被重定向到下一页。

Ad@m