Today I thought I would share with you some useful PHP functions which help speed up my programming life. Some of these functions I have built myself, some have been collecting from the Internet during my searches. Please feel free to add any more you many have in the comments section:
1. Randomized String
This function is great for generating randomized passwords and ‘guids’ which I use for identifying logged in users.
function guid($length=50) {
$characters = ‘0123456789abcdefghijklmnopqrstuvwxyz’;
$string = ”;
for ($p = 0; $p < $length; $p++) {
$string .= $characters[mt_rand(0, strlen($characters))];
}
return $string;
}
2. MySQL Date
This function quickly converts dd/mm/yyyy to yyyy-mm-dd (which is how MySQL likes it input):
function mysqlDate($thedate) {
$date_array = explode(‘/’,$thedate);
return $date_array[2].’-‘.$date_array[1].’-‘.$date_array[0];
}
3. Display MySQL Date
Reverses the previous function, takes a MySQL date (yyyy-mm-dd) and returns as dd/mm/yyyy:
function displayMysqlDate($thedate) {
$date_array = explode(‘-‘,$thedate);
return $date_array[2].’/’.$date_array[1].’/’.$date_array[0];
}
4. Convert Date and Time to mktime()
These functions take a MySQL Date (and time if present) and convert it into a mktime() format which can then be used in the PHP Date() function to display however you want:
function showTime($time) {
if ($time==”) return 0;
else return $time;
}
function mkTimeMysqlDate($timedate) {
$full_array = explode(‘ ‘,$timedate);
$date_array = explode(‘-‘,$full_array[0]);
$time_array = explode(‘:’,$full_array[1]);
return mktime(showTime($time_array[0]),showTime($time_array[1]),showTime($time_array[2]),$date_array[1],$date_array[2],$date_array[0]);
}
5. Filename friendly string
This function returns the enter string ‘filename-friendly’, whereby removing all none letters and numbers and replacing with a hyphen “-”.
I usually call this function using the following command (which could simply be incorporated into the function below): $url = checkCharacters(strtolower(trim(stripslashes($title))));
function checkCharacters($title) {
$final_text = ”;
for ($i=0;$i $letter = substr($title,$i,1);
$ascii = ord($letter);
if (($ascii>=97 && $ascii=48 && $ascii
else $final_text .= “-“;
}
return $final_text;
}