我正在建立一个基于推荐的网站,只希望它被输入有效推荐代码的人访问。登陆页面将只是一个简单的输入框和一个转按钮。一旦他们输入了正确的代码,他们就会被重定向到一个特定的URL,这取决于他们输入的代码。否则,它们将得到一条错误消息。
我写的代码都在一个页面使用HTML和PHP。
一切按计划进行,除了一件事…不管输入什么,它们都会被重定向到主页。即使你什么也不输入,你最终也会进入首页。
任何建议,我做错了什么,或者也许一个更好的方法将非常感激。
<?php
/*
Template Name: landingpage1
*/
?>
<?php
if (isset($_POST['suche'])) {
if ($_POST['suche'] == ‘REFERRAL3’) {
echo '<script type="text/javascript">
window.location = “MY-URL-1”
</script>';
} elseif ($_POST['suche'] == ‘REFERRAL1’) {
echo '<script type="text/javascript">
window.location = “MY-URL-2”
</script>';
} elseif ($_POST['suche'] == ‘REFERRAL2’) {
echo '<script type="text/javascript">
window.location = “MY-URL-3”
</script>';
} else {
echo 'Error: You put in the wrong code.';
}
} else {
echo '';
}
?>
<div id="page" class="page">
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Enter referral code: <input name="suche" type="text"><br>
<input type="submit" value="Go">
</form>
</div>
为什么不使用php的header()
函数重定向?它也节省了很多。除此之外,您的错误消息仅在设置$_POST['suche']
时显示。您可以将它移动到if
之后,因为header
会重定向。
if (isset($_POST['suche'])) {
if ($_POST['suche'] == "REFERRAL3") {
header("Location: MY-URL-1");
} elseif ($_POST['suche'] == "REFERRAL1") {
header("Location: MY-URL-2");
} elseif ($_POST['suche'] == "REFERRAL2") {
header("Location: MY-URL-3");
}
echo 'Error: You put in the wrong code.';
}
或者使用switch
代替许多if
。最好保持。
if (isset($_POST['suche'])) {
switch( $_POST['suche'] ) {
case "REFERRAL1":
header("Location: MY-URL-1");
break;
case "REFERRAL2":
header("Location: MY-URL-2");
break;
case "REFERRAL3":
header("Location: MY-URL-3");
break;
default:
echo 'Error: You put in the wrong code.';
break;
}
}
在您的代码<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>
将返回index.php,您的表单不提交到相同的模板文件。它被提交到index.php。
为了在提交时保持在同一页面上,您只需在表单标签中填写action=""
。
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<form method="post" action="">
您可以使用header('Location: http://www.example.com/');在php中用于重定向就像这样
if ($_POST['suche'] == ‘REFERRAL3’) {
header('Location: MY-URL-1');
}