emailvalidate
[ class tree: emailvalidate ] [ index: emailvalidate ] [ all elements ]

Source for file email_validator.php

Documentation is available at email_validator.php

  1. <?php
  2. /**
  3. * Email Validation Class
  4. *
  5. * Validates and verifies email addresses.
  6. *
  7. * @author Adam Delves <adam@sccode.com>
  8. */
  9. class EmailValidator
  10. {
  11. /**
  12. * Set to true if this email has not yet been saved to the database
  13. * @var boolean $newEntry
  14. */
  15. private $newEntry = false;
  16.  
  17. /**
  18. * ID for this email address. Generated when saved to the database.
  19. * @var integer $id
  20. */
  21. private $id = null;
  22.  
  23. /**
  24. * The Email address
  25. * @var string $email
  26. */
  27. private $email = null;
  28.  
  29. /**
  30. * Verification code generated for this email address.
  31. * @var string $v_code
  32. */
  33. private $v_code = null;
  34.  
  35. /**
  36. * True is the email has been verified.
  37. * @var boolean $verified
  38. */
  39. private $verified = false;
  40.  
  41. /**
  42. * True is the email is valid.
  43. * @var boolean $valid
  44. */
  45. private $valid = false;
  46. /**
  47. * The location of the email database.
  48. * @var string $EMAIL_FILE
  49. */
  50. public static $EMAIL_FILE='emails.dat';
  51.  
  52. /**
  53. * Holds a reference to the Sqllite database
  54. * @var SQLiteDatabase $db
  55. */
  56. private static $db = false;
  57. /**
  58. * Loads the database containing email addresses.
  59. * @return void
  60. */
  61. private static function loadEmailDB()
  62. {
  63. $exists = file_exists(self::$EMAIL_FILE);
  64. $error = false;
  65. self::$db = new SQLiteDatabase(self::$EMAIL_FILE, 0660, $error);
  66.  
  67. if ($error) {
  68. throw new Exception('Failed to open email database: ' . $error);
  69. }
  70. @self::$db->queryExec('CREATE TABLE emails (
  71. id INTEGER PRIMARY KEY,
  72. email TEXT NOT NULL,
  73. v_code TEXT NOT NULL,
  74. verified BOOLEAN DEFAULT 0,
  75. valid BOOLEAN DEFAULT 0)');
  76. }
  77.  
  78. /**
  79. * Class constructor
  80. *
  81. * Creates and instance of the EmailValidator using an ID or an email address. If an invalid ID is passed
  82. * an {link EmailValidatorException} is thrown.
  83. *
  84. * @param string $emailOrId The email address to validate or an ID of a previously saved email address.
  85. */
  86. public function __construct($emailOrId)
  87. {
  88. if (! self::$db) {
  89. self::loadEmailDB();
  90. }
  91. if (is_integer($emailOrId)) { // an ID has been passed for a previously saved email
  92. // search for email in database
  93. $result = self::$db->query("SELECT id,email,v_code,verified,valid FROM emails
  94. WHERE id=$emailOrId LIMIT 1", SQLITE_ASSOC);
  95.  
  96. if ($result->numRows() == 0) {
  97. throw new EmailValidatorException('Email ID Not Found: ' . $emailOrId);
  98. } else {
  99. $emailInfo = $result->current();
  100.  
  101. foreach($emailInfo as $name => $value) {
  102. $this->$name = $value;
  103. }
  104. }
  105. } else {
  106. $this->newEntry = true;
  107. $this->email = $emailOrId;
  108. }
  109. }
  110.  
  111. /**
  112. * Class destructor.
  113. * If this is not a new entry, changes may have been made, to auto save to the database.
  114. *
  115. * @return void
  116. */
  117. public function __destruct()
  118. {
  119. if (! $this->newEntry) {
  120. $this->save();
  121. }
  122. }
  123. /**
  124. * Saves email and verification code to DB
  125. * @return integer ID
  126. */
  127. public function save()
  128. {
  129. $email = addslashes($this->email);
  130. $v_code = (string) $this->v_code;
  131. $verified = (int) $this->verified;
  132. $valid = (int) $this->valid;
  133. // if this is a new entry use an insert query
  134. if ($this->newEntry) {
  135. $query = "INSERT INTO emails (email,v_code,verified,valid) VALUES
  136. ('$email', '$v_code', $verified, $valid)";
  137. self::$db->queryExec($query);
  138. $this->newEntry = false;
  139. return ($this->id = self::$db->lastInsertRowid());
  140. } else {
  141. $query = "UPDATE emails SET email='$email',v_code='$v_code',
  142. verified=$verified,valid=$valid WHERE id={$this->id}";
  143. self::$db->queryExec($query);
  144. return $this->id;
  145. }
  146. }
  147.  
  148. /**
  149. * Removes the email from the database.
  150. * @return void
  151. */
  152. public function remove()
  153. {
  154. if(! $this->id) {
  155. return;
  156. }
  157.  
  158. $query = "DELETE FROM email WHERE email_id={$this->id}";
  159. self::$db->queryExec($query);
  160.  
  161. $this->id = null;
  162. }
  163. /**
  164. * Pattern matches the email and checks the host name.
  165. * @return boolean
  166. */
  167. public function validate()
  168. {
  169. /* syntax check should not be too strict */
  170. $validatePattern = "/^[a-z0-9\-_~\.]+@(([a-z0-9\-]+\.)+[a-z]+)$/ix";
  171.  
  172. if (preg_match($validatePattern, $this->email, $matches)) {
  173. // check the domain part is a valid host name
  174. if (gethostbynamel($matches[1] . '.') === false) {
  175. return false;
  176. } else {
  177. $this->generateVerificationCode();
  178. return ($this->valid=true);
  179. }
  180. } else {
  181. return false;
  182. }
  183. }
  184.  
  185. /**
  186. * Checks a verification code.
  187. * Verification code check is case insensitive. Throws an {@link EmailValidatorException} if the email
  188. * address has not been validated.
  189. *
  190. * @param string $verifyCode 5 character verification code to check
  191. * @return boolean
  192. */
  193. public function verify($verifyCode)
  194. {
  195. if (! $this->valid) {
  196. throw new <a href="../emailvalidate/EmailValidatorException.html">EmailValidatorException</a>('Email must be vlaidated with validate() first.');
  197. }
  198. return ($this->verified = ($this->v_code == strtoupper($verifyCode)));
  199. }
  200.  
  201. /**
  202. * Sends a verification email containing a verification code.
  203. * Throws an {@link EmailValidatorException} if the email address has not been validated or has not been
  204. * saved to the database.
  205. *
  206. * @return boolean True if the email was successfully sent, false if not
  207. */
  208. public function sendVerificationEmail()
  209. {
  210. if (! $this->valid) {
  211. throw new <a href="../emailvalidate/EmailValidatorException.html">EmailValidatorException</a>('Email must be vlaidated with validate() first.');
  212. } else if (! $this->id) {
  213. throw new <a href="../emailvalidate/EmailValidatorException.html">EmailValidatorException</a>('Email must first be saved with save().');
  214. }
  215.  
  216. $subject = 'Validation Required';
  217. $headers = "Content-Type: text/html\r\nSubject: $subject";
  218. $body =
  219. <<<BODY
  220. <html>
  221. <head>
  222. </head>
  223. <body>
  224. <p>Thank you for registering. Before continuing, we must verify that you have entered the correct email address. Enter the
  225. verification code below to complete verify your email address.</p>
  226.  
  227. <p><b>Verification code:</b> {$this->v_code}</p>
  228. </body>
  229. </html>
  230. BODY;
  231. return @mail($this->email, $subject, $body, $headers);
  232. }
  233.  
  234. /**
  235. * Generates a random verification code.
  236. * @return string 5 character verification code containing A-Z and 0-9
  237. */
  238. private function generateVerificationCode()
  239. {
  240. // creates a 5 character random string containing capital letters or numbers
  241. $string = '';
  242. for ($x = 0; $x < 5; $x++) {
  243. $opt = rand(0,1);
  244. if ($opt) {
  245. // create a random number
  246. $chr = rand(48,57);
  247. } else {
  248. // create a random capital letter
  249. $chr = rand(65,90);
  250. }
  251. $string .= chr($chr);
  252. }
  253.  
  254. $this->v_code = $string;
  255. }
  256.  
  257. /**
  258. * Sets the value of the email property.
  259. * Once set, the email must be revalidated.
  260. *
  261. * @param $email
  262. * @return void
  263. */
  264. public function setEmail($email)
  265. {
  266. $this->valid = false;
  267. $this->verified = false;
  268. $this->email = $email;
  269. }
  270. /**
  271. * Gets the vlaue of the email {@link EmailValidator::ID ID} property
  272. * @return integer
  273. */
  274. public function getId()
  275. {
  276. return $this->id;
  277. }
  278.  
  279. /**
  280. * Gets the value of the {@link EmailValidator::valid valid} property
  281. * @return boolean
  282. */
  283. public function getValid()
  284. {
  285. return $this->valid;
  286. }
  287.  
  288. /**
  289. * Gets the value of the {@link EmailValidator::verified verified} property
  290. * @return boolean
  291. */
  292. public function getVerified()
  293. {
  294. return $this->verified;
  295. }
  296. }
  297.  
  298. /**
  299. * Email Exception Class
  300. *
  301. * @author Adam Delves <adam@sccode.com>
  302. */
  303. class EmailValidatorException extends Exception
  304. {
  305. /**
  306. * @ignore
  307. */
  308. public function __construct($message, $code=0)
  309. {
  310. parent::__construct($message, (int)$code);
  311. }
  312. }

Documentation generated on Wed, 22 Feb 2006 15:18:39 +0000 by phpDocumentor 1.3.0RC3