[英]PHP, submit form and redirect using header and echo out a success message?
我试图在用户提交表单后在下一页上回显div,并显示消息“表单提交成功”。
我正在尝试通过使用$ _GET ['success']来执行此操作,但似乎无法显示该消息,有人可以向我指出正确的方向。
码:
submit_form.php:
session_start();
$_SESSION['success'] = "<div class='success'>Form Submitted Successfully</div>;
header("Location: index.php?success=$success");
index.php文件:
<?php
$_GET['success'] ?>
session_start();
$_SESSION['success'] = "<div class='success'>Form Submitted Successfully</div>;
header("Location: index.php");
您正在设置带有文本消息的会话,因此您所需要做的就是在index.php页面上回显会话变量
<?php
if(isset($_SESSION['success']))
{
echo $_SESSION['success'];
}
?>
还放session_start();
在每一页的开头。
由于您已经设置了session
变量,因此只需在index.php文件中将其echo
session_start();
<?php echo $_SESSION['success']; ?>
您将值存储在变量$_SESSION['success']
并传递未定义的$success
,因此会引发错误
用以下代码替换您的代码:
session_start();
$success = "<div class='success'>Form Submitted Successfully</div>"; // use the $success
//encode the URL parameter as :
$success = urlencode($success);
header("Location: index.php?success=$success");
而在index.php中,只需将成功回显为:
<?php
echo isset($_GET['success'])?$_GET['success']:'Error!';
?>
希望这会有所帮助!
第一页中无需使用前两行。 只需在第三行中使用重定向即可,并在下一页“ index.php”上显示消息,如下所示:
第一页:
header("Location: index.php?success=done");
Index.php页面:
if(isset($_REQUEST['success'])=="done")
{
echo "<div class='success'>Form Submitted Successfully</div>";
}
您的代码中的错误数量巨大:
submit_form.php:
<?php
session_start();
$_SESSION['success'] = "<div class='success'>Form Submitted Successfully</div>"; // added " at the end
header("Location: index.php?success"); //Do NOT pass HTML in here. That makes an XSS security vulnerability
?>
index.php文件:
<?php
session_start(); //ALWAYS start with session_start if you use sessions. session_start should be at the very beginning of your page.
if(isset($_GET['success']))
echo $_SESSION['success']; //you put your data in _SESSION, you echo it from _SESSION
?>
它应该工作100%。
第一页:
header("Location: index.php?success=done");
Index.php页面:
if(isset($_REQUEST['success'])=="done")
{
echo "<div class='success'>Form Submitted Successfully</div>";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.