What are those little useful ,customize/enhanced php functions that you wish you knew about 2 years
- by I Like PHP
Hello All,
i like to work in php bcoz it's just amazing language.
please share basic, useful, enhanced and customize function that make things better and easy in php and must be used in our all PHP project, i m sharing some of them please share your customize function that may be useful for everyone
alternative/ enhanced print_r() and var_dump()
function watch( $what ) {
echo '<pre>';
if ( is_array( $what ) ) {
print_r ( $what );
} else {
var_dump ( $what );
}
echo '</pre>';
}
usage:
1. watch($_POST); // to see all post variable
2. watch($array); // to see any variable may b array, string or a variable
enhanced mysql_escape_string() for multidimensional array to prevent sql injection
function recursive_escape(&$value) {
if (is_array($value))
array_map('recursive_escape', $value);
else
$value = mysql_escape_string($value);
}
usage
array_map('recursive_escape', $_POST);
---------------------For encoding Get variables--------------------------------------
function nkode($k)
{
if ( is_array( $k ) ) return array_map("base64_encode",$k);
else return base64_encode($k);
}
---------------------for decoding varaibles from GET---------------------------------
function dkode($k)
{
if ( is_array( $k ) ) return array_map("base64_decode",$k);
else return base64_decode($k);
}
Usage
<a href="somelink.php?pid=<?php echo nkode($someid)?>">
and on next page(somelink.php)
$findID=dkode($_GET[pid]);
date convert to mm/dd/yyyy to yyyy-mm-dd( if we use date datatype in mysql) and also change into mm/dd/yyyy to disply on page
function dateconvert($date,$func)
{
if ($func == 1){ //insert conversion
list($month, $day, $year) = split('[/.-]', $date);
$date = "$year-$month-$day";
return $date;
}
if ($func == 2){ //output conversion
list($year, $month, $day) = split('[-.]', $date);
$date = "$month/$day/$year";
return $date;
}
}
usage
$firstDate=dateconvert($_POST['firstdate'],1); // for insertion in database
$showDate=dateconvert($fetch->date_field,2) // to display on browser
to clean data before doing some action with that variable
function cleanID($data)
{
$success=0;
$data=trim($data);
$data=strtolower($data);
$data=strip_tags($data);
return $data;
}
usage
cleanID($_POST[username]);
cleanID($_GET[pid]);
please share any basic function that must be used , and please give me some suggestion to make above function more better
Thanks