» » Useful PHP functions collected

 

Useful PHP functions collected

Author: bamboo06 on 5-12-2014, 03:10, views: 4289

3
Projects often require some headache functions, as developers should organize its own library, when you need it can be copied. The authors collected dozens of commonly used functions in PHP project, guaranteed to run properly, you just copy and paste into your project.
Useful PHP functions collected

1, PHP encryption and decryption
2, PHP generates a random string
3, PHP to get the file extension (suffix)
4, PHP get the file size and format
5, PHP replace the label characters
6, PHP directory lists the file name
7, PHP to get the current page URL
8, PHP forced to download the file
9, PHP interception string length
10, PHP obtain client's IP
11, PHP prevent SQL injection
12, PHP page Tips & Jump
13, Calculating PHP running time

1, PHP encryption and decryption
PHP encryption and decryption functions can be used to encrypt some useful string is stored in the database, and by reversible decrypt strings, the function uses the base64 and MD5 encryption and decryption.
function encryptDecrypt($key, $string, $decrypt){
    if($decrypt){
        $decrypted = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($key), base64_decode($string), MCRYPT_MODE_CBC, md5(md5($key))), "12");
        return $decrypted;
    }else{
        $encrypted = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($key), $string, MCRYPT_MODE_CBC, md5(md5($key))));
        return $encrypted;
    }
}

Use as follows:
//The following is the string "Welcomes to goocode.net", respectively, the encryption and decryption
//Encryption:
echo encryptDecrypt('password', 'Helloweba欢迎您',0);
//Decryption:
echo encryptDecrypt('password', 'z0JAx4qMwcF+db5TNbp/xwdUM84snRsXvvpXu',1);


2, PHP generates a random string
When we need to generate a random name and a temporary password and other strings can be used the following function:
function generateRandomString($length = 10) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, strlen($characters) - 1)];
    }
    return $randomString;
}

Use as follows:
echo generateRandomString(20);


3, PHP to get the file extension (suffix)
The following functions can quickly get the file extension that suffix.
function getExtension($filename){
  $myext = substr($filename, strrpos($filename, '.'));
  return str_replace('.','',$myext);
}

Use as follows:
$filename = 'mydocuments.doc';
echo getExtension($filename);


4, PHP get the file size and format
The following functions can be used to obtain the file size, and converted into readable KB, MB and other formats.
function formatSize($size) {
    $sizes = array(" Bytes", " KB", " MB", " GB", " TB", " PB", " EB", " ZB", " YB");
    if ($size == 0) { 
		return('n/a'); 
	} else {
      return (round($size/pow(1024, ($i = floor(log($size, 1024)))), 2) . $sizes[$i]); 
	}
}

Use as follows:
$thefile = filesize('sky.mp3');
echo formatSize($thefile);


5, PHP replace the label characters
Sometimes we need to be string, replace the specified template tag content, you can use the following function:
function stringParser($string,$replacer){
    $result = str_replace(array_keys($replacer), array_values($replacer),$string);
    return $result;
}

Use as follows:
$string = 'The {b}anchor text{/b} is the {b}actual word{/b} or words used {br}to describe the link {br}itself';
$replace_array = array('{b}' => '<b>','{/b}' => '</b>','{br}' => '<br />');
echo stringParser($string,$replace_array);


6, PHP directory lists the file name
If you want to list all the files in a directory, use the following code:
function listDirFiles($DirPath){
    if($dir = opendir($DirPath)){
         while(($file = readdir($dir))!== false){
                if(!is_dir($DirPath.$file))
                {
                    echo "filename: $file<br />";
                }
         }
    }
}

Use as follows:
listDirFiles('home/some_folder/');


7, PHP to get the current page URL
The following functions can obtain the URL of the current page, whether it is http or https.
function curPageURL() {
	$pageURL = 'http';
	if (!empty($_SERVER['HTTPS'])) {$pageURL .= "s";}
	$pageURL .= "://";
	if ($_SERVER["SERVER_PORT"] != "80") {
		$pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
	} else {
		$pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
	}
	return $pageURL;
}

Use as follows:
echo curPageURL();


8, PHP forced to download the file
Sometimes we do not want the browser to directly open files, such as PDF files, but to directly download the file, then the following functions can be forced to download the file, the function uses the application / octet-stream header type.
function download($filename){
    if ((isset($filename))&&(file_exists($filename))){
       header("Content-length: ".filesize($filename));
       header('Content-Type: application/octet-stream');
       header('Content-Disposition: attachment; filename="' . $filename . '"');
       readfile("$filename");
    } else {
       echo "Looks like file does not exist!";
    }
}

Use as follows:
download('/down/asb123.zip');


9, PHP interception string length
We often encounter the need to intercept the string (including Chinese characters) case length, such as the title can not exceed the number of characters displayed beyond the length with ... said that the following functions to meet your needs.
/*
Utf-8, gb2312 character interception function supported
cut_str (string interception length, began length coding);
The default is utf-8 encoding
Start length defaults to 0
*/
function cutStr($string, $sublen, $start = 0, $code = 'UTF-8'){
    if($code == 'UTF-8'){
        $pa = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/";
        preg_match_all($pa, $string, $t_string);

        if(count($t_string[0]) - $start > $sublen) return join('', array_slice($t_string[0], $start, $sublen))."...";
        return join('', array_slice($t_string[0], $start, $sublen));
    }else{
        $start = $start*2;
        $sublen = $sublen*2;
        $strlen = strlen($string);
        $tmpstr = '';

        for($i=0; $i<$strlen; $i++){
            if($i>=$start && $i<($start+$sublen)){
                if(ord(substr($string, $i, 1))>129){
                    $tmpstr.= substr($string, $i, 2);
                }else{
                    $tmpstr.= substr($string, $i, 1);
                }
            }
            if(ord(substr($string, $i, 1))>129) $i++;
        }
        if(strlen($tmpstr)<$strlen ) $tmpstr.= "...";
        return $tmpstr;
    }
}

Use as follows:
$str = "jQuery to realize page effects";
echo cutStr($str,16);


10, PHP obtain client's IP
We often use the database to record the user's IP, the following code to get the client's IP:
//get users' real IP
function getIp() {
	if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))
		$ip = getenv("HTTP_CLIENT_IP");
	else
		if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown"))
			$ip = getenv("HTTP_X_FORWARDED_FOR");
		else
			if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
				$ip = getenv("REMOTE_ADDR");
			else
				if (isset ($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
					$ip = $_SERVER['REMOTE_ADDR'];
				else
					$ip = "unknown";
	return ($ip);
}

Use as follows:
echo getIp();


11, PHP prevent SQL injection
We query the database, for security reasons, to prevent the need to filter some illegal characters malicious SQL injection, take a look at the function:
function injCheck($sql_str) { 
	$check = preg_match('/select|insert|update|delete|\'|\/\*|\*|\.\.\/|\.\/|union|into|load_file|outfile/', $sql_str);
	if ($check) {
		echo 'hack error!!';
		exit;
	} else {
		return $sql_str;
	}
}

Use as follows:
echo injCheck('1 or 1=1');


12, PHP page Tips & Jump
We form during the operation, and sometimes need to prompt the user-friendly operating results and jump to the relevant page, consider the following function:
function message($msgTitle,$message,$jumpUrl){
	$str = '<!DOCTYPE HTML>';
	$str .= '<html>';
	$str .= '<head>';
	$str .= '<meta charset="utf-8">';
	$str .= '<title>Tips</title>';
	$str .= '<style type="text/css">';
	$str .= '*{margin:0; padding:0}a{color:#369; text-decoration:none;}a:hover{text-decoration:underline}body{height:100%; font:12px/18px Tahoma, Arial,  sans-serif; color:#424242; background:#fff}.message{width:450px; height:120px; margin:16% auto; border:1px solid #99b1c4; background:#ecf7fb}.message h3{height:28px; line-height:28px; background:#2c91c6; text-align:center; color:#fff; font-size:14px}.msg_txt{padding:10px; margin-top:8px}.msg_txt h4{line-height:26px; font-size:14px}.msg_txt h4.red{color:#f30}.msg_txt p{line-height:22px}';
	$str .= '</style>';
	$str .= '</head>';
	$str .= '<body>';
	$str .= '<div class="message">';
	$str .= '<h3>'.$msgTitle.'</h3>';
	$str .= '<div class="msg_txt">';
	$str .= '<h4 class="red">'.$message.'</h4>';
	$str .= '<p>The page will be redirected in  <span style="color:blue;font-weight:bold">3</span> s. You can also click <a href="{$jumpUrl}">HERE</a>  to redirect immediately.</p>';
	$str .= "<script>setTimeout('location.replace(\'".$jumpUrl."\')',2000)</script>";
	$str .= '</div>';
	$str .= '</div>';
	$str .= '</body>';
	$str .= '</html>';
	echo $str;
}

Use as follows:
message('Prompt','Success!','http://www.goocode.net/');


13, Calculating PHP running time
Processing time when we need to calculate the distance between the current time point in time duration, such as computing client runtime long, usually with hh: mm: ss, said.
function changeTimeType($seconds) {
	if ($seconds > 3600) {
		$hours = intval($seconds / 3600);
		$minutes = $seconds % 3600;
		$time = $hours . ":" . gmstrftime('%M:%S', $minutes);
	} else {
		$time = gmstrftime('%H:%M:%S', $seconds);
	}
	return $time;
}

Use as follows:
$seconds = 3712;
echo changeTimeType($seconds);

Tags: PHP, function

Category: PHP Scripts

Dear visitor, you are browsing our website as Guest.
We strongly recommend you to register and login to view hidden contents.
<
  • 0 Comments
  • 0 Articles
8 July 2017 19:09

Thomas Fischer

Reply
  • Group: Guests
  • РRegistered date: --
  • Status:
 
All these PHP functions really are impressive. More than anything else, they're those which one would regularly keep on using, which is the thing that actually matters above anything else. I was wondering is myassignmentservice good, if it is, I'd like purchasing assignments.

<
  • 0 Comments
  • 0 Articles
19 July 2017 19:07

Yael Chaney

Reply
  • Group: Guests
  • РRegistered date: --
  • Status:
 
This is great, good to know that Useful PHP functions have been collected including the information about vinyl flooring denver. It's feature like PHP encryption and decryption is the most helpful of all.

<
  • 0 Comments
  • 0 Articles
10 February 2018 02:57

MytishiFub

Reply
  • Group: Guests
  • РRegistered date: --
  • Status:
 
Продаётся 1 комнатная квартира срочно. продажа квартир мытищи трехкомнатные никитина 4, фото 1970-х гг. жилой комплекс отрадное мытищи

Information
Comment on the news site is possible only within (days) days from the date of publication.