PHP Form Validation By Regular Expression ()

(1) PHP check valid url

function valid_url($str)
{
return ( ! preg_match('/^(http|https|ftp):\/\/([A-Z0-9][A-Z0-9_-]*(?:\.[A-Z0-9][A-Z0-9_-]*)+):?(\d+)?\/?/i', $str)) ? FALSE : TRUE;
}

(2) PHP numeric characters validator

function numeric($str)
{
return ( ! ereg("^[0-9\.]+$", $str)) ? FALSE : TRUE;
}

(3) PHP alpha-numeric characters validator

function alpha_numeric($str)
{
return ( ! preg_match("/^([-a-z0-9])+$/i", $str)) ? FALSE : TRUE;
}

(4) PHP alpha characters validator

function alpha($str)
{
return ( ! preg_match("/^([-a-z])+$/i", $str)) ? FALSE : TRUE;
}

(5) PHP validate ip

function valid_ip($ip)
{
return ( ! preg_match( "/^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$/", $ip)) ? FALSE : TRUE;
}

(6) PHP validate email

function valid_email($str)
{
return ( ! preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $str)) ? FALSE : TRUE;
}

(7) PHP Windows Filename Validation
function is_valid_filename($name) {
$parts=preg_split("/(\/|".preg_quote("\\").")/",$name);
if (preg_match("/[a-z]:/i",$parts[0])) {
unset($parts[0]);
}
foreach ($parts as $part) {
if (
preg_match("/[".preg_quote("^|?*<\":>","/")."\a\b\c\e\x\v\s]/",$part)||
preg_match("/^(PRN|CON|AUX|CLOCK$|NUL|COMd|LPTd)$/im",str_replace(".","\n",$part))
) {
return false;
}
}
return true;
}


Reference from : http://www.roscripts.com/snippets/show/61

important scrips for php (Part -1)

(1) Human readable Sizes

function ByteSize ( $file_size )
{
$file_size = $file_size-1;
if ($file_size >= 1099511627776) $show_filesize = number_format(($file_size / 1099511627776),2) . " TB";
elseif ($file_size >= 1073741824) $show_filesize = number_format(($file_size / 1073741824),2) . " GB";
elseif ($file_size >= 1048576) $show_filesize = number_format(($file_size / 1048576),2) . " MB";
elseif ($file_size >= 1024) $show_filesize = number_format(($file_size / 1024),2) . " KB";
elseif ($file_size > 0) $show_filesize = $file_size . " b";
elseif ($file_size == 0 || $file_size == -1) $show_filesize = "0 b";
return $show_filesize;
}

(2) Remove non alpha numeric characters

function rem_non_alpha_numeric ( $string, $replace )
{
return preg_replace ( '/[^a-zA-Z0-9]/u', $replace, $string );
}

(3) PHP escape for SQL

/**
* Correctly quotes a string so that all strings are escaped. We prefix and append
* to the string single-quotes.
* An example is escape ( "Don't bother",magic_quotes_runtime () );
*
* @param str the string to quote
* @param [magic_quotes] if $s is GET/POST var, set to get_magic_quotes_gpc().
*
* @return quoted string to be sent back to database
*/
function escape ( $str, $magic_quotes = false )
{
switch ( gettype ( $str ) )
{
case 'string' :
$replaceQuote = "\\'"; /// string to use to replace quotes
if ( ! $magic_quotes ) {

if ( $replaceQuote [ 0 ] == '\\' ){
// only since php 4.0.5
$str = seo_str_replace ( array ( '\\', "\0" ), array ( '\\\\', "\\\0" ), $str );
//$s = str_replace("\0","\\\0", str_replace('\\','\\\\',$s));
}
return "'" . str_replace ( "'", $replaceQuote, $str ) . "'";
}

// undo magic quotes for "
$str = str_replace ( '\\"','"', $str );

if ( $replaceQuote == "\\'" ) {// ' already quoted, no need to change anything
return "'$str'";
}
else {// change \' to '' for sybase/mssql
$str = str_replace ( '\\\\','\\', $str );
return "'" . str_replace ( "\\'", $treplaceQuote, $str ) . "'";
}
break;
case 'boolean' : $str = ($str === FALSE) ? 0 : 1;
return $str;
break;
case 'integer' : $str = ($str === NULL) ? 'NULL' : $str;
return $str;
break;
default : $str = ($str === NULL) ? 'NULL' : $str;
return $str;
break;
}
}

(4) PHP is keyword in string

function is_keyword_in_string_bol ($keyword, $string)
{
if ( strpos ( $string, $keyword ) === false )
{
return FALSE;
}
else {
return TRUE;
}
}

(5) PHP check url if valid

function is_valid_url ( $url )
{
$url = @parse_url($url);

if ( ! $url) {
return false;
}

$url = array_map('trim', $url);
$url['port'] = (!isset($url['port'])) ? 80 : (int)$url['port'];
$path = (isset($url['path'])) ? $url['path'] : '';

if ($path == '')
{
$path = '/';
}

$path .= ( isset ( $url['query'] ) ) ? "?$url[query]" : '';

if ( isset ( $url['host'] ) AND $url['host'] != gethostbyname ( $url['host'] ) )
{
if ( PHP_VERSION >= 5 )
{
$headers = get_headers("$url[scheme]://$url[host]:$url[port]$path");
}
else
{
$fp = fsockopen($url['host'], $url['port'], $errno, $errstr, 30);

if ( ! $fp )
{
return false;
}
fputs($fp, "HEAD $path HTTP/1.1\r\nHost: $url[host]\r\n\r\n");
$headers = fread ( $fp, 128 );
fclose ( $fp );
}
$headers = ( is_array ( $headers ) ) ? implode ( "\n", $headers ) : $headers;
return ( bool ) preg_match ( '#^HTTP/.*\s+[(200|301|302)]+\s#i', $headers );
}
return false;
}

(6) How to extract google search results using PHP




if(!isset($_POST['q']))
{
echo '

';
}
else
{
// this would be the URL if you want the results on page 2, 3 ... where $_POST['p'] is multiple of 10
// $off_site = 'http://www.google.com/search?q='.urlencode($_POST['q']).'&start='.$_POST['p'];
$off_site = 'http://www.google.com/search?q='.urlencode($_POST['q']).'&ie=UTF-8&oe=UTF-8';
$fp = fopen ($off_site, 'r') or die('Unable to open file '.$off_site.' for reading');
while (!feof ($fp))
{
$buf = trim(fgets($fp, 4096));
$pos = strpos($buf,'

');
if($pos !== false)
{
$parts = explode('

',$buf);
$parts2 = explode('http://',$parts[1]);
$parts3 = explode('>',$parts2[1]);
echo ''.$parts3[0].'
';
}
}
}


?>

(7) PHP word wrap

/** * Example usage: *
* // Your text * $text = "This is a sentence which contains some words.";
* * // Or from a database result * $text = $row['text'];
* * // Then put it into the function * $text = word_wrap($text);
* * // Output the result * echo $text; */ function word_wrap($text)
{ // Define the characters to display per row
$chars = "10"; $text = wordwrap($text, $chars, "
", 1);
return $text;
}?>

8) Page load time calculator

// Insert this block of code at the very top of your page:
$time = microtime();$time = explode(" ", $time);
$time = $time[1] + $time[0];$start = $time;
// Place this part at the very end of your page$time = microtime();
$time = explode(" ", $time);$time = $time[1] + $time[0];
$finish = $time;$totaltime = ($finish - $start);
printf ("This page took %f seconds to load.", $totaltime);
?>


(9) PHP limit words

function word_limiter($str, $n = 100, $end_char = '…')
{
if (strlen($str) < $n)
{
return $str;
}

$words = explode(' ', preg_replace("/\s+/", ' ', preg_replace("/(\r\n|\r|\n)/", " ", $str)));

if (count($words) <= $n)
{
return $str;
}

$str = '';
for ($i = 0; $i < $n; $i++)
{
$str .= $words[$i].' ';
}

return trim($str).$end_char;
}

(10) PHP limit characters

function character_limiter($str, $n = 500, $end_char = '…')
{
if (strlen($str) < $n)
{
return $str;
}

$str = preg_replace("/\s+/", ' ', preg_replace("/(\r\n|\r|\n)/", " ", $str));

if (strlen($str) <= $n)
{
return $str;
}

$out = "";
foreach (explode(' ', trim($str)) as $val)
{
$out .= $val.' ';
if (strlen($out) >= $n)
{
return trim($out).$end_char;
}
}
}

(11) Show page queries

function mysql_query_2($query){
$_SESSION['queries']++;
return mysql_query($query);

// now use mysql_query_2() function in place of mysql_query()
// Each query will execute exactly the same but count up in
// session variable 'queries'

echo "$_SESSION['queries']";

// just output it somewhere like above...

(12) Checks if a path is absolute or relative

function is_absolute($path)
{
return ($path[0] == '/' || (substr(PHP_OS, 0, 3) == 'WIN' && preg_match('#^[a-z]:/#i', $path))) ? true : false;
}