Verifying the email address is a hardest but mandatory task in the web world. A valid email can help to make your marketing profitable. But an invalid email increases your marking cost and effects on the email client’s reputation. Similarly, the email validation is the common and useful functionality on the web application. Before working with the email address, it needs to be verified and checked whether the email is valid or not.
Validate email in PHP can be easily done by using filter_var() function with FILTER_VALIDATE_EMAIL filter. It will check if the format of the given email address is valid. But only this filter is not enough to check whether an email address exists. In this tutorial, we will show you how to check if an email address is real and exists using PHP.
In the PHP email verification script, we will validate an email address by checking MX DNS Record and domain. This script is very useful to verify the user’s email address before sending an email or insert in the database. You can differentiate real and invalid email address, and accept only the valid email address from the user.
PHP Email Verification Library
The VerifyEmail class is used to check if an email address is valid and real using SMTP protocol in PHP. You need to use one function of VerifyEmail class to verify the email address in PHP.
check()
- Validate the format of the email address.
- Get MX records of the domain of the email address.
- Connect to the SMTP server by the MX records.
- Based on the response code:
- Check if given recipient email address is valid.
- Check if the user of email’s domain exists.
- Check the delivery of the message.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 |
<?php /** * Class to validate the email address * * @author mywebcode.com <[email protected]> * @copyright Copyright (c) 2019, mywebcode.com * @url https://www.mywebcode.com */ class VerifyEmail { protected $stream = false; /** * SMTP port number * @var int */ protected $port = 25; /** * Email address for request * @var string */ protected $from = 'root@localhost'; /** * The connection timeout, in seconds. * @var int */ protected $max_connection_timeout = 30; /** * Timeout value on stream, in seconds. * @var int */ protected $stream_timeout = 5; /** * Wait timeout on stream, in seconds. * * 0 - not wait * @var int */ protected $stream_timeout_wait = 0; /** * Whether to throw exceptions for errors. * @type boolean * @access protected */ protected $exceptions = false; /** * The number of errors encountered. * @type integer * @access protected */ protected $error_count = 0; /** * class debug output mode. * @type boolean */ public $Debug = false; /** * How to handle debug output. * Options: * * `echo` Output plain-text as-is, appropriate for CLI * * `html` Output escaped, line breaks converted to `<br>`, appropriate for browser output * * `log` Output to error log as configured in php.ini * @type string */ public $Debugoutput = 'echo'; /** * SMTP RFC standard line ending. */ const CRLF = "\r\n"; /** * Holds the most recent error message. * @type string */ public $ErrorInfo = ''; /** * Constructor. * @param boolean $exceptions Should we throw external exceptions? */ public function __construct($exceptions = false) { $this->exceptions = (boolean) $exceptions; } /** * Set email address for SMTP request * @param string $email Email address */ public function setEmailFrom($email) { if (!self::validate($email)) { $this->set_error('Invalid address : ' . $email); $this->edebug($this->ErrorInfo); if ($this->exceptions) { throw new verifyEmailException($this->ErrorInfo); } } $this->from = $email; } /** * Set connection timeout, in seconds. * @param int $seconds */ public function setConnectionTimeout($seconds) { if ($seconds > 0) { $this->max_connection_timeout = (int) $seconds; } } /** * Sets the timeout value on stream, expressed in the seconds * @param int $seconds */ public function setStreamTimeout($seconds) { if ($seconds > 0) { $this->stream_timeout = (int) $seconds; } } public function setStreamTimeoutWait($seconds) { if ($seconds >= 0) { $this->stream_timeout_wait = (int) $seconds; } } /** * Validate email address. * @param string $email * @return boolean True if valid. */ public static function validate($email) { return (boolean) filter_var($email, FILTER_VALIDATE_EMAIL); } /** * Get array of MX records for host. Sort by weight information. * @param string $hostname The Internet host name. * @return array Array of the MX records found. */ public function getMXrecords($hostname) { $mxhosts = array(); $mxweights = array(); if (getmxrr($hostname, $mxhosts, $mxweights) === FALSE) { $this->set_error('MX records not found or an error occurred'); $this->edebug($this->ErrorInfo); } else { array_multisort($mxweights, $mxhosts); } /** * Add A-record as last chance (e.g. if no MX record is there). * Thanks Nicht Lieb. * @link http://www.faqs.org/rfcs/rfc2821.html RFC 2821 - Simple Mail Transfer Protocol */ if (empty($mxhosts)) { $mxhosts[] = $hostname; } return $mxhosts; } /** * Parses input string to array(0=>user, 1=>domain) * @param string $email * @param boolean $only_domain * @return string|array * @access private */ public static function parse_email($email, $only_domain = TRUE) { sscanf($email, "%[^@]@%s", $user, $domain); return ($only_domain) ? $domain : array($user, $domain); } /** * Add an error message to the error container. * @access protected * @param string $msg * @return void */ protected function set_error($msg) { $this->error_count++; $this->ErrorInfo = $msg; } /** * Check if an error occurred. * @access public * @return boolean True if an error did occur. */ public function isError() { return ($this->error_count > 0); } /** * Output debugging info * Only generates output if debug output is enabled * @see verifyEmail::$Debugoutput * @see verifyEmail::$Debug * @param string $str */ protected function edebug($str) { if (!$this->Debug) { return; } switch ($this->Debugoutput) { case 'log': //Don't output, just log error_log($str); break; case 'html': //Cleans up output a bit for a better looking, HTML-safe output echo htmlentities( preg_replace('/[\r\n]+/', '', $str), ENT_QUOTES, 'UTF-8' ) . "<br>\n"; break; case 'echo': default: //Normalize line breaks $str = preg_replace('/(\r\n|\r|\n)/ms', "\n", $str); echo gmdate('Y-m-d H:i:s') . "\t" . str_replace( "\n", "\n \t ", trim($str) ) . "\n"; } } /** * Validate email * @param string $email Email address * @return boolean True if the valid email also exist */ public function check($email) { $result = FALSE; if (!self::validate($email)) { $this->set_error("{$email} incorrect e-mail"); $this->edebug($this->ErrorInfo); if ($this->exceptions) { throw new verifyEmailException($this->ErrorInfo); } return FALSE; } $this->error_count = 0; // Reset errors $this->stream = FALSE; $mxs = $this->getMXrecords(self::parse_email($email)); $timeout = ceil($this->max_connection_timeout / count($mxs)); foreach ($mxs as $host) { /** * suppress error output from stream socket client... * Thanks Michael. */ $this->stream = @stream_socket_client("tcp://" . $host . ":" . $this->port, $errno, $errstr, $timeout); if ($this->stream === FALSE) { if ($errno == 0) { $this->set_error("Problem initializing the socket"); $this->edebug($this->ErrorInfo); if ($this->exceptions) { throw new verifyEmailException($this->ErrorInfo); } return FALSE; } else { $this->edebug($host . ":" . $errstr); } } else { stream_set_timeout($this->stream, $this->stream_timeout); stream_set_blocking($this->stream, 1); if ($this->_streamCode($this->_streamResponse()) == '220') { $this->edebug("Connection success {$host}"); break; } else { fclose($this->stream); $this->stream = FALSE; } } } if ($this->stream === FALSE) { $this->set_error("All connection fails"); $this->edebug($this->ErrorInfo); if ($this->exceptions) { throw new verifyEmailException($this->ErrorInfo); } return FALSE; } $this->_streamQuery("HELO " . self::parse_email($this->from)); $this->_streamResponse(); $this->_streamQuery("MAIL FROM: <{$this->from}>"); $this->_streamResponse(); $this->_streamQuery("RCPT TO: <{$email}>"); $code = $this->_streamCode($this->_streamResponse()); $this->_streamResponse(); $this->_streamQuery("RSET"); $this->_streamResponse(); $code2 = $this->_streamCode($this->_streamResponse()); $this->_streamQuery("QUIT"); fclose($this->stream); $code = !empty($code2)?$code2:$code; switch ($code) { case '250': /** * http://www.ietf.org/rfc/rfc0821.txt * 250 Requested mail action okay, completed * email address was accepted */ case '450': case '451': case '452': /** * http://www.ietf.org/rfc/rfc0821.txt * 450 Requested action not taken: the remote mail server * does not want to accept mail from your server for * some reason (IP address, blacklisting, etc..) * Thanks Nicht Lieb. * 451 Requested action aborted: local error in processing * 452 Requested action not taken: insufficient system storage * email address was greylisted (or some temporary error occured on the MTA) * i believe that e-mail exists */ return TRUE; case '550': return FALSE; default : return FALSE; } } /** * writes the contents of string to the file stream pointed to by handle * If an error occurs, returns FALSE. * @access protected * @param string $string The string that is to be written * @return string Returns a result code, as an integer. */ protected function _streamQuery($query) { $this->edebug($query); return stream_socket_sendto($this->stream, $query . self::CRLF); } /** * Reads all the line long the answer and analyze it. * If an error occurs, returns FALSE * @access protected * @return string Response */ protected function _streamResponse($timed = 0) { $reply = stream_get_line($this->stream, 1); $status = stream_get_meta_data($this->stream); if (!empty($status['timed_out'])) { $this->edebug("Timed out while waiting for data! (timeout {$this->stream_timeout} seconds)"); } if ($reply === FALSE && $status['timed_out'] && $timed < $this->stream_timeout_wait) { return $this->_streamResponse($timed + $this->stream_timeout); } if ($reply !== FALSE && $status['unread_bytes'] > 0) { $reply .= stream_get_line($this->stream, $status['unread_bytes'], self::CRLF); } $this->edebug($reply); return $reply; } /** * Get Response code from Response * @param string $str * @return string */ protected function _streamCode($str) { preg_match('/^(?<code>[0-9]{3})(\s|-)(.*)$/ims', $str, $matches); $code = isset($matches['code']) ? $matches['code'] : false; return $code; } } /** * verifyEmail exception handler */ class verifyEmailException extends Exception { /** * Prettify error message output * @return string */ public function errorMessage() { $errorMsg = $this->getMessage(); return $errorMsg; } } ?> |
Usage
The VerifyEmail library is easy to use for validating the email address using PHP.
- Initialize the library class using
VerifyEmail()
. - Set the timeout, debug, and sender email address.
- Call
check()
function and pass the email address which you want to validate.- Returns TRUE, if the given email address is valid and real. Also, it indicates that the domain of this email exists and the user is valid.
- Returns FALSE, if the given email address is invalid and not exists.
- If the check() function returns FALSE, you can check the email with validate() function to check if the email format is valid but the user not exists on the domain.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
<?php // Include library file require_once 'VerifyEmail.class.php'; // Initialize library class $mail = new VerifyEmail(); // Set the timeout value on stream $mail->setStreamTimeoutWait(20); // Set debug output mode $mail->Debug= TRUE; $mail->Debugoutput= 'html'; // Set email address for SMTP request // Email to check // Check if email is valid and exist if($mail->check($email)){ echo 'Email <'.$email.'> is exist!'; }elseif(verifyEmail::validate($email)){ echo 'Email <'.$email.'> is valid, but not exist!'; }else{ echo 'Email <'.$email.'> is not valid and not exist!'; } ?> |
Email validation in JavaScript using Regular Expression
Email input field validation is mandatory before submitting the HTML form. Email validation helps to check if a user submitted a valid email address or not. Using regular expression in JavaScript, you can easily validate the email address before submitting the form. We’ll use the regular expression for validate an email address in JavaScript.
1 2 3 4 5 6 7 8 |
function validateEmail(email){ var reg = /^[A-Z0-9._%+-]+@([A-Z0-9-]+\.)+[A-Z]{2,4}$/i; if(reg.test(email)){ return true; } alert('Please enter valid email.'); return false; } |