php一些基本函数

<?php // 函数加密解密 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; } } //以下是将字符串“Helloweba欢迎您”分别加密和解密 //加密: echo encryptDecrypt('password', 'Helloweba欢迎您',0); //解密: echo "<br/>"; echo encryptDecrypt('password', 'z0JAx4qMwcF+db5TNbp/xwdUM84snRsXvvpXuaCa4Bk=',1); echo "<br/>"; // 指定长度随机数 function generateRandomString($length = 10) { $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; $randomString = ''; for ($i = 0; $i < $length; $i++) { $randomString .= $characters[rand(0, strlen($characters) - 1)]; } return $randomString; } echo generateRandomString(5); echo "<br/>"; // 获取文件扩展名 function getExtension($filename){ $myext = substr($filename, strrpos($filename, '.')); return str_replace('.','',$myext); } $filename = '我的文档.doc'; echo getExtension($filename); echo "<br/>"; // 获取文件大小 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]); } } echo formatSize(12350006); echo "<br/>"; // 替换标签 function stringParser($string,$replacer){ $result = str_replace(array_keys($replacer), array_values($replacer),$string); return $result; } $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); echo "<br/>"; // 目录下文件 function listDirFiles($DirPath){ if($dir = opendir($DirPath)){ while(($file = readdir($dir))!== false){ if(!is_dir($DirPath.$file)) { echo "filename: $file<br />"; } } } } listDirFiles('D:/'); echo "<br/>"; // PHP获取当前页面URL 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; } echo curPageURL(); // 强制下载 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!"; } } // download("D:/key.txt"); //获取用户真实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); } echo "<br/>"; echo getIp(); echo "<br/>"; function message($msgTitle,$message,$jumpUrl){ $str = '<!DOCTYPE HTML>'; $str .= '<html>'; $str .= '<head>'; $str .= '<meta charset="utf-8">'; $str .= '<title>页面提示</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>系统将在 <span style="color:blue;font-weight:bold">3</span> 秒后自动跳转,如果不想等待,直接点击 <a href="{$jumpUrl}">这里</a> 跳转</p>'; $str .= "<script>setTimeout('location.replace('".$jumpUrl."')',2000)</script>"; $str .= '</div>'; $str .= '</div>'; $str .= '</body>'; $str .= '</html>'; echo $str; } // message('操作提示','操作成功!','http://www.baidu.com'); function getClientIp() { $ip = NULL; if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) { $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']); $pos = array_search('unknown',$arr); if(false !== $pos) unset($arr[$pos]); $ip = trim($arr[0]); }elseif (isset($_SERVER['HTTP_CLIENT_IP'])) { $ip = $_SERVER['HTTP_CLIENT_IP']; }elseif (isset($_SERVER['REMOTE_ADDR'])) { $ip = $_SERVER['REMOTE_ADDR']; } // IP地址合法验证 $ip = (false !== ip2long($ip)) &#63; $ip : '0.0.0.0'; return $ip; } /** * 获取在线IP * @return String */ function getOnlineIp($format=0) { global $S_GLOBAL; if(empty($S_GLOBAL['onlineip'])) { if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) { $onlineip = getenv('HTTP_CLIENT_IP'); } elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) { $onlineip = getenv('HTTP_X_FORWARDED_FOR'); } elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) { $onlineip = getenv('REMOTE_ADDR'); } elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) { $onlineip = $_SERVER['REMOTE_ADDR']; } preg_match("/[\d\.]{7,15}/", $onlineip, $onlineipmatches); $S_GLOBAL['onlineip'] = $onlineipmatches[0] &#63; $onlineipmatches[0] : 'unknown'; } if($format) { $ips = explode('.', $S_GLOBAL['onlineip']); for($i=0;$i&lt;3;$i++) { $ips[$i] = intval($ips[$i]); } return sprintf('%03d%03d%03d', $ips[0], $ips[1], $ips[2]); } else { return $S_GLOBAL['onlineip']; } } /** * 获取url * @return [type] [description] */ function getUrl(){ $pageURL = 'http'; if (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on") { $pageURL .= "s"; } $pageURL .= "://"; if ($_SERVER["SERVER_PORT"] != "80") { $pageURL .= $_SERVER["HTTP_HOST"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"]; } else { $pageURL .= $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]; } return $pageURL; } /** * 获取当前站点的访问路径根目录 * @return [type] [description] */ function getSiteUrl() { $uri = $_SERVER['REQUEST_URI']&#63;$_SERVER['REQUEST_URI']:($_SERVER['PHP_SELF']&#63;$_SERVER['PHP_SELF']:$_SERVER['SCRIPT_NAME']); return 'http://'.$_SERVER['HTTP_HOST'].substr($uri, 0, strrpos($uri, '/')+1); } /** * 字符串截取,支持中文和其他编码 * @param [string] $str [字符串] * @param integer $start [起始位置] * @param integer $length [截取长度] * @param string $charset [字符串编码] * @param boolean $suffix [是否有省略号] * @return [type] [description] */ function msubstr($str, $start=0, $length=15, $charset="utf-8", $suffix=true) { if(function_exists("mb_substr")) { return mb_substr($str, $start, $length, $charset); } elseif(function_exists('iconv_substr')) { return iconv_substr($str,$start,$length,$charset); } $re['utf-8'] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/"; $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/"; $re['gbk'] = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/"; $re['big5'] = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/"; preg_match_all($re[$charset], $str, $match); $slice = join("",array_slice($match[0], $start, $length)); if($suffix) { return $slice."…"; } return $slice; } /** * php 实现js escape 函数 * @param [type] $string [description] * @param string $encoding [description] * @return [type] [description] */ function escape($string, $encoding = 'UTF-8'){ $return = null; for ($x = 0; $x &lt; mb_strlen($string, $encoding);$x ++) { $str = mb_substr($string, $x, 1, $encoding); if (strlen($str) &gt; 1) { // 多字节字符 $return .= "%u" . strtoupper(bin2hex(mb_convert_encoding($str, 'UCS-2', $encoding))); } else { $return .= "%" . strtoupper(bin2hex($str)); } } return $return; } /** * php 实现 js unescape函数 * @param [type] $str [description] * @return [type] [description] */ function unescape($str) { $str = rawurldecode($str); preg_match_all("/(&#63;:%u.{4})|.{4};|&#\d+;|.+/U",$str,$r); $ar = $r[0]; foreach($ar as $k=&gt;$v) { if(substr($v,0,2) == "%u"){ $ar[$k] = iconv("UCS-2","utf-8//IGNORE",pack("H4",substr($v,-4))); } elseif(substr($v,0,3) == "") { $ar[$k] = iconv("UCS-2","utf-8",pack("H4",substr($v,3,-1))); } elseif(substr($v,0,2) == "&#") { echo substr($v,2,-1).""; $ar[$k] = iconv("UCS-2","utf-8",pack("n",substr($v,2,-1))); } } return join("",$ar); } /** * 数字转人名币 * @param [type] $num [description] * @return [type] [description] */ function num2rmb ($num) { $c1 = "零壹贰叁肆伍陆柒捌玖"; $c2 = "分角元拾佰仟万拾佰仟亿"; $num = round($num, 2); $num = $num * 100; if (strlen($num) &gt; 10) { return "oh,sorry,the number is too long!"; } $i = 0; $c = ""; while (1) { if ($i == 0) { $n = substr($num, strlen($num)-1, 1); } else { $n = $num % 10; } $p1 = substr($c1, 3 * $n, 3); $p2 = substr($c2, 3 * $i, 3); if ($n != '0' || ($n == '0' && ($p2 == '亿' || $p2 == '万' || $p2 == '元'))) { $c = $p1 . $p2 . $c; } else { $c = $p1 . $c; } $i = $i + 1; $num = $num / 10; $num = (int)$num; if ($num == 0) { break; } } $j = 0; $slen = strlen($c); while ($j &lt; $slen) { $m = substr($c, $j, 6); if ($m == '零元' || $m == '零万' || $m == '零亿' || $m == '零零') { $left = substr($c, 0, $j); $right = substr($c, $j + 3); $c = $left . $right; $j = $j-3; $slen = $slen-3; } $j = $j + 3; } if (substr($c, strlen($c)-3, 3) == '零') { $c = substr($c, 0, strlen($c)-3); } // if there is a '0' on the end , chop it out return $c . "整"; } /** * 特殊的字符 * @param [type] $str [description] * @return [type] [description] */ function makeSemiangle($str) { $arr = array( '0' =&gt; '0', '1' =&gt; '1', '2' =&gt; '2', '3' =&gt; '3', '4' =&gt; '4', '5' =&gt; '5', '6' =&gt; '6', '7' =&gt; '7', '8' =&gt; '8', '9' =&gt; '9', 'A' =&gt; 'A', 'B' =&gt; 'B', 'C' =&gt; 'C', 'D' =&gt; 'D', 'E' =&gt; 'E', 'F' =&gt; 'F', 'G' =&gt; 'G', 'H' =&gt; 'H', 'I' =&gt; 'I', 'J' =&gt; 'J', 'K' =&gt; 'K', 'L' =&gt; 'L', 'M' =&gt; 'M', 'N' =&gt; 'N', 'O' =&gt; 'O', 'P' =&gt; 'P', 'Q' =&gt; 'Q', 'R' =&gt; 'R', 'S' =&gt; 'S', 'T' =&gt; 'T', 'U' =&gt; 'U', 'V' =&gt; 'V', 'W' =&gt; 'W', 'X' =&gt; 'X', 'Y' =&gt; 'Y', 'Z' =&gt; 'Z', 'a' =&gt; 'a', 'b' =&gt; 'b', 'c' =&gt; 'c', 'd' =&gt; 'd', 'e' =&gt; 'e', 'f' =&gt; 'f', 'g' =&gt; 'g', 'h' =&gt; 'h', 'i' =&gt; 'i', 'j' =&gt; 'j', 'k' =&gt; 'k', 'l' =&gt; 'l', 'm' =&gt; 'm', 'n' =&gt; 'n', 'o' =&gt; 'o', 'p' =&gt; 'p', 'q' =&gt; 'q', 'r' =&gt; 'r', 's' =&gt; 's', 't' =&gt; 't', 'u' =&gt; 'u', 'v' =&gt; 'v', 'w' =&gt; 'w', 'x' =&gt; 'x', 'y' =&gt; 'y', 'z' =&gt; 'z', '(' =&gt; '(', ')' =&gt; ')', '〔' =&gt; '[', '〕' =&gt; ']', '【' =&gt; '[', '】' =&gt; ']', '〖' =&gt; '[', '〗' =&gt; ']', '{' =&gt; '{', '}' =&gt; '}', '《' =&gt; '&lt;', '》' =&gt; '&gt;', '%' =&gt; '%', '+' =&gt; '+', '—' =&gt; '-', '-' =&gt; '-', '~' =&gt; '-', ':' =&gt; ':', '。' =&gt; '.', '、' =&gt; ',', ',' =&gt; '.', '、' =&gt; '.', ';' =&gt; ';', '?' =&gt; '&#63;', '!' =&gt; '!', '…' =&gt; '-', '‖' =&gt; '|', '”' =&gt; '"', '“' =&gt; '"', '' =&gt; '`', '‘' =&gt; '`', '|' =&gt; '|', '〃' =&gt; '"', ' ' =&gt; ' ','.' =&gt; '.'); return strtr($str, $arr); } /** * 下载 * @param [type] $filename [description] * @param string $dir [description] * @return [type] [description] */ function downloads($filename,$dir='./'){ $filepath = $dir.$filename; if (!file_exists($filepath)){ header("Content-type: text/html; charset=utf-8"); echo "File not found!"; exit; } else { $file = fopen($filepath,"r"); Header("Content-type: application/octet-stream"); Header("Accept-Ranges: bytes"); Header("Accept-Length: ".filesize($filepath)); Header("Content-Disposition: attachment; filename=".$filename); echo fread($file, filesize($filepath)); fclose($file); } } /** * 创建一个目录树 * @param [type] $dir [description] * @param integer $mode [description] * @return [type] [description] */ function mkdirs($dir, $mode = 0777) { if (!is_dir($dir)) { mkdirs(dirname($dir), $mode); return mkdir($dir, $mode); } return true; } ?>

本文转载至http://www.jb51.net/article/58610.htm

你可能感兴趣的:(PHP)