尝试在同一页面上显示错误。我怎么做?现在看来,每次出现错误时,都会生成一个空白页面,其中列出了所有错误。
我不想要那个。
这是我从教程test.php
中删除的基本表单:
<?php session_start(); ?>
<html>
<head>
<title></title>
</head>
<body>
<form name="form1" method="post" action="test2.php">
Name: <br/>
<input type="text" name="name" value="<?php echo $_POST['name']; ?>" size="50" /><br/><br/>
Email Address: <br/>
<input type="text" name="email" value="<?php echo $_POST['email']; ?>" size="50"/> <br/><br/>
Home Page: <br/>
<input type="text" name="homepage" value="<?php echo $_POST['homepage']; ?>" size="50" /> <br/><br/>
Message: <br/>
<textarea name="message" rows="5" cols="50"><?php echo $_POST['message']; ?></textarea>
<br/>
<input type="submit" name="Submit" />
</form>
</body>
</html>
这里的PHP代码也从教程中删除,即test2.php
:
<?php
session_start();
if (isset($_POST['Submit'])) {
if ($_POST['name'] != "") {
$_POST['name'] = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
if ($_POST['name'] == "") {
$errors .= 'Please enter a valid name.<br/><br/>';
}
} else {
$errors .= 'Please enter your name.<br/>';
}
if ($_POST['email'] != "") {
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors .= "$email is <strong>NOT</strong> a valid email address.<br/><br/>";
}
} else {
$errors .= 'Please enter your email address.<br/>';
}
if ($_POST['homepage'] != "") {
$homepage = filter_var($_POST['homepage'], FILTER_SANITIZE_URL);
if (!filter_var($homepage, FILTER_VALIDATE_URL)) {
$errors .= "$homepage is <strong>NOT</strong> a valid URL.<br/><br/>";
}
} else {
$errors .= 'Please enter your home page.<br/>';
}
if ($_POST['message'] != "") {
$_POST['message'] = filter_var($_POST['message'], FILTER_SANITIZE_STRING);
if ($_POST['message'] == "") {
$errors .= 'Please enter a message to send.<br/>';
}
} else {
$errors .= 'Please enter a message to send.<br/>';
}
if (!$errors) {
$mail_to = 'me@somewhere.com';
$subject = 'New Mail from Form Submission';
$message = 'From: ' . $_POST['name'] . "\n";
$message .= 'Email: ' . $_POST['email'] . "\n";
$message .= 'Homepage: ' . $_POST['homepage'] . "\n";
$message .= "Message:\n" . $_POST['message'] . "\n\n";
mail($to, $subject, $message);
echo "Thank you for your email!<br/><br/>";
} else {
echo '<div style="color: red">' . $errors . '<br/></div>';
}
}
?>
注意,我在这两个页面中添加了session_start
,因为我希望通过该页面而不是GET
完成错误。
如何在test.php
表单上显示错误?
答案 0 :(得分:0)
我会使用会话来表示同一页面上的错误。
在test2.php上启动会话
session_start();
然后在您需要的if语句中创建会话错误
$_SESSION['error'] = 'error message here';
header('location:test1.php');
exit;
然后在test1.php上,像这样
<?php
session_start();
if (!empty($_SESSION['error'])){
?>
<div class="alert"> //you could then style this div to present error message better
<?php
echo $_SESSION['error'];
unset($_SESSION['error']);
}
?>
</div>
或者在一个php语句中没有div只是简单地回显错误。
希望我帮助过。