我正在尝试通过PHP验证电子邮件。我是PHP的新手,所以如果它非常简单,我会事先道歉。
我的页面加载没有错误,但我可以继续使用错误的格式化电子邮件提交表单。我希望页面刷新并弹出一条消息,提示用户使用有效的电子邮件地址。
提前致谢
<?php
session_start();
require 'database.php';
$message = '';
if (isset($_POST['email']) == true && empty($_POST['email']) == false) {
$email = $_POST['email'];
if(filter_var($email, FILTER_VALIDATE_EMAIL) == true){
echo 'That\'s a valid email address';
} else {
echo'Not a valid email address';
}
}
if(!empty($_POST['email']) && !empty($_POST['phonenumber']) && !empty($_POST['postcode']) && !empty($_POST['Name'])):
$stmt = $conn->prepare('SELECT email FROM noodles_gamification WHERE email = :email');
$stmt->execute(array(':email' => $_POST['email']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if(!empty($row['email'])){
$message = 'email provided is already in use.';
} else {
$sql = "INSERT INTO noodles_gamification (email, phonenumber, postcode, Name) VALUES (:email, :phonenumber, :postcode, :Name)";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':email', $_POST['email']);
$stmt->bindParam(':phonenumber', $_POST['phonenumber']);
$stmt->bindParam(':postcode', $_POST['postcode']);
$stmt->bindParam(':Name', $_POST['Name']);
if( $stmt->execute() ){
$_SESSION['email'] = $_POST['email'];
header("Location: ../");
}
}
endif;
?>
<!DOCTYPE html>
<html>
<head>
<title>Register</title>
<link rel="stylesheet" stype="text/css" href="style.css">
<link href="https://fonts.googleapis.com/css?family=Comfortaa" rel="stylesheet">
</head>
<body>
<div class="header">
<a href="../index.php"> Your App Name</a>
</div>
<?php if(!empty($message)): ?>
<p><?= $message ?></p>
<?php endif; ?>
<h1>Need a few details before you start the game</h1>
<form action="register.php" method="POST">
<input type="text" placeholder="Enter Your Full Name" name="Name">
<input type="text" placeholder="Enter Your Email" name="email">
<input type="text" placeholder="Phone Number" name="phonenumber">
<input type="text" placeholder="Post Code" name="postcode">
<input type="submit">
</body>
</html>
答案 0 :(得分:1)
您正在编写验证电子邮件的代码
if (isset($_POST['email']) == true && empty($_POST['email']) == false) {
$email = $_POST['email'];
if(filter_var($email, FILTER_VALIDATE_EMAIL) == true){
echo 'That\'s a valid email address';
} else {
echo'Not a valid email address';
}
}
但在验证之后,您正在显示消息,并且您的脚本会进一步执行。而在显示电子邮件错误后您应该停止。所以使用这个
$emailError=false;
if (isset($_POST['email']) == true && empty($_POST['email']) == false) {
$email = $_POST['email'];
if(filter_var($email, FILTER_VALIDATE_EMAIL) == true){
echo 'That\'s a valid email address';
} else {
echo'Not a valid email address';
$emailError=true;
}
}
然后检查emailError是否为false然后再进一步
if(!$emailError){
//your code to save the data or manipulate the data
}
答案 1 :(得分:1)
在PHP中验证电子邮件的简单方法如下,
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
// invalid emailaddress
}
您可以参考链接How to validate an Email in PHP
谢谢。