简体   繁体   English

PHP if语句无法与filter_var一起正常工作

[英]PHP if statement not working as expected with filter_var

I have a form which posts variables through to a PHP processing script. 我有一种形式,可以将变量发布到PHP处理脚本中。

Before the processing script begins I would like to sanitize the posted variables: 在处理脚本开始之前,我要清理发布的变量:

$Contact_Name = filter_var($_POST['contactName'], FILTER_SANITIZE_STRING);
$Company = filter_var($_POST['company'], FILTER_SANITIZE_STRING);
$Telephone = filter_var($_POST['telephone'],FILTER_SANITIZE_NUMBER_INT);

So far. 至今。 So good. 这么好。

But sanitizing and validating the email is a real pain. 但是,对电子邮件进行消毒和验证是一个真正的难题。

$Email = $_POST['email'];
$Sanitised_Email = filter_var($Email, FILTER_SANITIZE_EMAIL);
$Email_is_valid = filter_var($Email, FILTER_VALIDATE_EMAIL);

If $Sanitised_Email isn't the same as $Email , I want to go back to the form page: 如果$Sanitised_Email$Email ,我想返回到表单页面:

if ($Sanitised_Email != $Email) {
header('Location: http://'.$_SERVER['HTTP_HOST'].'/form.php');
}

If $Email_is_valid is false , I want to go back to the form page: 如果$Email_is_validfalse ,我想返回到表单页面:

if ($Email_is_valid == FALSE) {
header('Location: http://'.$_SERVER['HTTP_HOST'].'/form.php');
}

Neither of these two if statements work when I enter an email which is both invalid and in need of sanitisation such as: 当我输入无效且需要卫生的电子邮件时,这两个if语句都不起作用,例如:

i.am.(totally)invalid@asanemailaddress

What am I doing wrong? 我究竟做错了什么? Have I messed up my syntax somewhere? 我在某处弄乱了语法吗?

Syntax seems good. 语法似乎不错。 I think your problem is that you are not ending your script after setting header. 我认为您的问题是,设置标头后您没有结束脚本。 Change it to: 更改为:

if (condition) {
        header('Location: www.example.com');
        exit();
}

Learn how to debug your code, you can simply echo something to know if you are entering a structure or not. 了解如何调试代码,您可以简单地回显某些信息,以了解是否要输入结构。 A good practice is also to create a function to redirect pages, it's quick, clean and save some lines: 一个好的做法是创建一个重定向页面的函数,它快速,干净并节省了一些行:

function redirect($page){
        header('Location: http://'.$_SERVER['HTTP_HOST']."/$page.php");
        exit();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM