When developing projects, there are always some common work should be accomplished, for example, encrption/decryption, get IP. As a PHP developer, you should have a list of the handy functions in your toolkit so that you can pick up in every project you work on. Here is a summary of some handy PHP functions.
1. PHP encryption/decryption
Encryption/decryption can be used when storing user confidential information such as passwords. Below function uses base64 and MD5 to accomplish encryption/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;
}
}
Usage:
//Encryption
echo encryptDecrypt('password', 'Helloweba',0);
//Decryption
echo encryptDecrypt('password', 'z0JAx4qMwcF+db5TNbp/xwdUM84snRsXvvpXuaCa4Bk=',1);
2. Generate random string
This is useful when a temporary password or random name is needed.
function generateRandomString($length = 10) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, strlen($characters) - 1)];
}
return $randomString;
}
Usage:
echo generateRandomString(20);
3. Get file extension name
Below function can be used to get file extension name.
function getExtension($filename){
$myext = substr($filename, strrpos($filename, '.'));
return str_replace('.','',$myext);
}
Usage:
$filename = 'mydoc.doc'; echo getExtension($filename);
4. Get formatted file size
Below function can be used to get file size in KB, MB format.
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]);
}
}
Usage:
$thefile = filesize('test_file.mp3');
echo formatSize($thefile);
5. Tag replacement
Sometimes template tags should be replaced. This function can help us out. Actually, it can be used to replace any string you want.
function stringParser($string,$replacer){
$result = str_replace(array_keys($replacer), array_values($replacer),$string);
return $result;
}
Usage:
$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. List directory
function listDirFiles($DirPath){
if($dir = opendir($DirPath)){
while(($file = readdir($dir))!== false){
if(!is_dir($DirPath.$file))
{
echo "filename: $file<br />";
}
}
}
}
Usage:
listDirFiles('home/some_folder/');
7. Get current page URL
Below function can be used to get the current page URL no matter it's 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;
}
Usage:
echo curPageURL();
8. Force downloading file
If you don't want the browser to download the file instead of opening the file directly, below function can be used to achieve this. It uses application/octet-stream
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!";
}
}
Usage:
download('/down/test_45f73e852.zip');
9. Get client 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);
}
Usage:
echo getIp();
10. Detect SQL injection
function injCheck($sql_str) {
$check = preg_match('/select|insert|update|delete|\'|\/\*|\*|\.\.\/|\.\/|union|into|load_file|outfile/', $sql_str);
if ($check) {
echo 'éžæ³•å—符ï¼ï¼';
exit;
} else {
return $sql_str;
}
}
Usage:
echo injCheck('1 or 1=1');
You may have your own list of functions in your toolkit, it will help many others if you share them.
No comment for this article.