PHP Form Validation By Regular Expression ()
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)
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;
}
Remove Leading Zeros Using PHP
(1) ltrim()
Example : echo ltrim(”001″,”0″);
Result : 1
(2) intval()
Example : echo intval(”001″);
Result : 1
Conversion of MySQL Timestamp and DateTime to Unix based TimeStamp
* The Prior version of MySQL v4.1 the timestamp was formatted as like YYYYMMDDHHMMSS”
* since after MySQL v4.1 timestamp and datetime data types are formatted “YYYY-MM-DD HH:MM:SS”.
About Unix Based TimeStamp
* It is differ from MySQL. Unix’s timestamp is a integer value of seconds since January 1, 1970.
How To - Convert
(1) Using MySQL
* you can use Unix_Timestamp() function.
* Example:
SELECT Unix_Timestamp(Created) FROM CreatedItem;
(2) Using PHP
* you can use strtotime() function.
* Example:
$unixTimeStamp = strtotime($createdTimestamp);
stdClass in php
you cannot define a class named stdClass in your PHP code. Useful for anonymous objects, dynamic properties,
StdClass object creation. Something like this would be great:
$foo = {”bar”: “baz”, “bam”: “boom”};
so you end up doing something like this:
$foo = new StdClass;
$foo->bar = “baz”;
$foo->bam = “boom”;
but you don’t have to. Using PHP’s casting operator you can create the object in one line:
$foo = (object) array(”bar” => “baz”, “bam” => “boom”);
usage is casting an array to an object which takes each value in the array and adds it as a member variable with the name based on the key
in the array.
Here’s an example below that converts an array to an object below. This method is called Type Casting
'Divyesh',
'lastname' => 'Karelia'
);
$p = (object) $person;
echo $p->firstname; // Will print 'Divyesh'
?>
Here’s an example below that converts a multi-dimensional array to an object. This is accomplished through recursion.
02.function arrayToObject($array) {
03. if(!is_array($array)) {
04. return $array;
05. }
06.
07. $object = new stdClass();
08. if (is_array($array) && count($array) > 0) {
09. foreach ($array as $name=>$value) {
10. $name = strtolower(trim($name));
11. if (!empty($name)) {
12. $object->$name = arrayToObject($value);
13. }
14. }
15. return $object;
16. }
17. else {
18. return FALSE;
19. }
20.}
21.?>
array('name' => 'Divyesh'),
'last' => array('name' => 'Karelia')
'
);
$p = arrayToObject($person);
?>
first->name; // Will print 'Divyesh'
?>
Drupal .module extension treate as php file (syntax color) in Eclipse
Eclipse comes with a nice solution for these kind of situations.
All you need to do in order for Eclipse to treat .module extensions as .php is to go to
Window Menu > Preferences > General > Content Types > (Select) Text > PHP Content TYpe from the Content types area, then below under
File Associations click on Add button and write down any extension you wish. In Drupal CMS case, write down “.module”.
Now you should be able to work with .module files as with all other .php files.
Top 10 Drupal Modules
His list is as shown below, in priority order:
- Content Construction Kit
- Views
- Tagadelic
- Path and Pathauto
- Organic Groups
- Buddylist
- Privatemsg
- Guestbook
- Logintoboggan
- Service Links
You can read Paul Koura's blog post including comments about each module here:
http://webpodge.com/2007/02/22/top-10-drupal-modules/