PHP Code Snippets
From DreamHost
Contents |
Useful 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:
<?php
/**
* Validate email address
* @param string $email Email address
* @return boolean
*/
function checkEmail($email)
{
$pattern = "/^([\w]+[\.-])+@([\w]+)([\.-]?[\w]+)*\.([A-z]{2,})$/i";
return preg_match ($pattern, $email);
}
?>
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.
/**
* Validate URL
* Allows for port, path and query string validations
* @param string $url string containing url user input
* @return boolean Returns TRUE/FALSE
*/
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);
}
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:
<?php
/**
* Random Password Generator
* @public
* @param int $length Length of password to generate
* @return string Returns randomised password
*/
function randomPword($length)
{
$seed = 'ABC123DEF456GHI789JKL0MNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
$seedLength = strlen($seed);
$random = '';
for ($i=1; $i <= $length; $i++)
{
$charPos = mt_rand(0, ($seedLength - 1));
$singleChar = substr($seed, $charPos, 1);
$random .= $singleChar;
}
return $random;
}
?>
function by: User:Ironikart

