PHP Code Snippets

Validating an email address
PHP allows the use of several regex engines. The Perl Regular Expression engine can be used to match pre-defined patterns and is extremely useful for form validation. The following is a function that will allow you to validate an email address:

User:Ironikart


 * Validate email address
 * @param  string    $email     Email address
 * @return boolean

function by: User:Ironikart

Validating a URL
Here's a URL validation function that accepts (I think) most known types of URL's. Useful for validating a homepage link, or submission of links from the public.

User:Ironikart

/** function validateURL($url) { $pattern = "/^((https?|ftp|gopher|telnet|file|wais):\/\/)" . "(([A-z0-9_]+):([A-z0-9-_]*)@)?" . "(([A-z0-9_-]+\.)*)" . "(([A-z0-9-]{2,})\.)" . "([A-z]{2,})" . "(:(\d+))?" . "((/[a-z0-9-_.%~]*)*)?" . "(\?[^? ]*)?$/"; return preg_match($pattern, $url); }
 * Validate URL
 * Allows for port, path and query string validations
 * @param   string      $url	   string containing url user input
 * @return  boolean     Returns TRUE/FALSE

function by: User:Ironikart

Random Password Generation
A random password generator is a fairly common function used by PHP programmers, here's my take on it:


 * Random Password Generator
 * @public
 * @param int $length Length of password to generate
 * @return string Returns randomised password

function by: User:Ironikart