Home >Backend Development >PHP Tutorial >Compilation of the most commonly used custom functions in PHP project development_PHP tutorial
//alert prompt
function alert($msg){
echo "<script>alert('$msg');</script>";
}
//Convert some predefined characters into HTML entities
function d_htmlspecialchars($string) {
if(is_array($string)) {
foreach($string as $key => $ val) {
$string[$key] = d_htmlspecialchars($val);
}
} else {
$string = str_replace('&', '&', $string);
$string = str_replace('"', '"', $string);
$string = str_replace(''', ''', $string);
$string = str_replace('< ', '<', $string);
$string = str_replace('>', '>', $string);
$string = preg_replace('/&(#d;)/ ', '&1', $string);
}
return $string;
}
//Add a backslash before the predefined characters, including single quotes, double quotes, and backslashes bar, NULL to protect database security
function d_addslashes($string, $force = 0) {
if(!$GLOBALS['magic_quotes_gpc'] || $force) {
if(is_array($ string)) {
foreach($string as $key => $val) $string[$key] = d_addslashes($val, $force);
}
else $string = addslashes($ string);
}
return $string;
}
//Generate a random string, including uppercase, lowercase letters, numbers
function randstr($length) {
$hash = ''; $ CHARS = 'ABCDEFGHIJKLMNOPQRSNOPQRSTUVWXYZ0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'; d (dough) microtime () * 1000000);
for ($ i = 0; $i < $length; $i++) {
$hash .= $chars[mt_rand(0, $max)];
}
return $hash;
}
//Convert timestamp to common date format
function trans_time($timestamp){
if($timestamp < 1) echo 'Invalid Unix timestamp';
else return date("Y-m-d H:i:s",$timestamp);
}
//Get IP
function get_ip() {
if ($_SERVER["HTTP_X_FORWARDED_FOR"])
$ip = $ _SERVER["HTTP_X_FORWARDED_FOR"];
else if ($_SERVER["HTTP_CLIENT_IP"])
$ip = $_SERVER["HTTP_CLIENT_IP"];
else if ($_SERVER["REMOTE_ADDR"])
$ip = $_SERVER["REMOTE_ADDR"];
else if (getenv("HTTP_X_FORWARDED_FOR"))
$ip = getenv("HTTP_X_FORWARDED_FOR");
else if (getenv("HTTP_CLIENT_IP" ))
$ip = getenv("HTTP_CLIENT_IP");
else if (getenv("REMOTE_ADDR"))
$ip = getenv("REMOTE_ADDR");
else
$ip = "Unknown";
return $ip;
}
//Calculate time difference: the default return type is "minutes"
//$old_time can only be a timestamp, $return_type is h which is hour , for s is seconds
function timelag($old_time,$return_type='m'){
if($old_time < 1){
echo 'Invalid Unix timestamp';
} else{
switch($return_type){
case 'h':
$type = 3600; break;
case 'm':
$type = 60; break;
case 's':
$type = 1; break;
case '':
$type = 60; break;
}
$dif = round( (time()-$ old_time)/$type ) ;
return $dif;
}
}
//Get the URL address of the current page
function url_this(){
$url = "http: //".$_SERVER ["HTTP_HOST"].$_SERVER["REQUEST_URI"];
$return_url = "$url";
return $return_url;
}
//Jump function
function url_redirect($url,$delay=''){
if($delay == ''){
echo "< ;script>window.location.href='$url'";
}else{
echo "";
}
}
} //end func
?>