Saturday 7 December 2019

How to Validate email address in PHP?


How to Validate email address in PHP?


Following are in built PHP function to validate the email address and Ip Address.


Validate Email - Example 1
$email='helo@gmail.com';
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
  echo $email. ' - Invalid'; 
}else{
echo $email. ' - Valid';     
}

helo@gmail.com - Valid

Validate Email - Example 2
$email='464646@gmail.com';
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
  echo $email. '- Invalid'; 
}else{
echo $email. ' - Valid';     
}

464646@gmail.com - Valid

Validate Email - Example 3
$email='arunkumar.com';
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
  echo $email. ' - Invalid'; 
}else{
echo $email. ' - Valid';     
}


arunkumar.com - Invalid



Validate IP Address - Example 1
Question: How to Validate IP Address?
$ipAddress = '127.0.0.1';
if (!filter_var($ipAddress, FILTER_VALIDATE_IP)) {
    echo "$ipAddress is In-valid.";
}else{
    echo "$ipAddress is Valid.";
}

127.0.0.1 is Valid

Validate IP Address - Example 2
$ipAddress = '127.test.0.0.1';
if (!filter_var($ipAddress, FILTER_VALIDATE_IP)) {
    echo "$ipAddress is In-valid.";
}else{
    echo "$ipAddress is In-Valid.";
}

127.test.0.0.1 is Valid


Validate URL - Example 1
$ipAddress = '127.test.0.0.1';
$website = 'https://www.web-technology-experts-notes.in';
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {
  echo   "Invalid URL";
}else{
echo   "Valid URL";
}

Valid URL