PHP: Verify And Sanitize Email Address

by Vivek Gite · 3 comments

Q. How do I verify input data such as email address under PHP programming language?

A. You need to use PHP Filters designed for safely dealing with input parameters. It can validate and filter data coming from some insecure source, such as user input via filter extension. This extension is part of PHP Core version 5.20 and above, but you can always install it under Linux. You can use filters to validate following type of data:

=> regex
=> url
=> email
=> strings
=> magic_quotes
=> regular data types such as int, float etc

Validate email address

Here is a sample code:

<?
$email="vivek@nixcraft.com";
if ( filter_var($email, FILTER_VALIDATE_EMAIL)  == TRUE) {
	echo 'Valid Email Address';
}
else
{
	echo 'Invalid Email Address';
}
?>

filter_var() will filter a variable with a specified filter. In this case you've used FILTER_VALIDATE_EMAIL filter. You may also want to sanitizes the e-mail using following code:

$out=filter_var($email, FILTER_SANITIZE_EMAIL);

Here is another sample:

<?php
// form.php
//....
//......
$_POST['email'] = stripslashes(trim($_POST['email']));
$tmpEmail=filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
if ( filter_var($tmpEmail, FILTER_VALIDATE_EMAIL)  == TRUE) {
	// callSmtp
	fireSmtp();
}
else{
	//show error
	echo 'Invalid Input - an error has occurred when trying to send this email';
}
///....	
 
?>

Further readings:

Featured Articles:

Want to read Linux tips and tricks, but don't have time to check our blog everyday? Subscribe to our daily email newsletter to make sure you don't miss a single tip/tricks. Subscribe to our weekly newsletter here!

{ 3 comments… read them below or add one }

1 Abhisek 09.20.08 at 12:30 am

thanks. much it easier it seems.

2 apriyanda 09.21.08 at 10:30 am

please verify my e-mail

3 rocelle 09.25.09 at 7:16 am

how verify email address
thankss….

Leave a Comment

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Previous FAQ:

Next FAQ:

nixCraft FAQ PDF Collection Now Available To All