简体   繁体   中英

PHP if statement not working as expected with filter_var

I have a form which posts variables through to a PHP processing script.

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:

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:

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:

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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