主要方法包含 取文件的后缀名 取随机字符串 使用加密和解密字符串函数 获取文件的大小 对字符串使用替换字符 获取web服务器的文件路径 获取当前页面的URL 检测浏览器语言 创建一个目录树 下载本目录下的某个文件 页面提示与跳转 获取各种编码的固定长度 取得用户的真实ip地址 数组值转换 js的unescape函数 unescape函数 防止SQL注入
/*
* 取文件的后缀名
*/
function getExtension($filename){
$myext = substr($filename, strrpos($filename, '.')); //取得的字符串为 .doc
return str_replace('.','',$myext); //参数分别为 。。。
}
$filename = '我的文档.doc';
echo getExtension($filename);
/*
* 取随机字符串
* length 长度 默认10
*/
function omString($length = 10) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, strlen($characters) - 1)];
}
return $randomString;
}
echo omString(20);
/*
* 使用加密和解密字符串函数
* key 加密密码
* string 加密字段
* decrypt 加密(0)或解密(1)
*/
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;
}
}
echo encryptDecrypt('eily', '玉娟',0); echo "<br />";
echo encryptDecrypt('eily', '6anhA2GKZLV/sn91lnZ/KSgnrfD05Mihj8ARQ8SAE7A=',1);
/*
* 获取文件的大小
*/
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]);
}
}
$thefile = filesize('jquery-2.0.0.min.js');
echo formatSize($thefile);
/*
* 对字符串使用替换字符
*/
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 />');
/*
* 获取web服务器的文件路径
*/
function listDirFiles($DirPath){
if($dir = opendir($DirPath)){
while(($file = readdir($dir))!== false){
if(!is_dir($DirPath.$file))
{
echo "filename: $file<br />";
}
}
}
}
listDirFiles('/Users/eily/Documents');
/*
* 获取当前页面的URL,不管是http还是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;
}
echo curPageURL();
--------------------------------------------------------------------------------
/*
* 获取编码字符串的指定长度,效果如下
* jQuery插件实现的加载图片和页面...
*/
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;
}
}
$str = "jQuery插件实现的加载图片和页面效果";
echo cutStr($str,21,0,''); //3的倍数
--------------------------------------------------------------------------------
/*
* 取得用户的真实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 getIp();
--------------------------------------------------------------------------------
/*
* PHP防止SQL注入
*/
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;
}
}
echo injCheck('1 select 1=1');
/*
* PHP页面提示与跳转
*/
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 id="tz1">系统将在 <span style="color:blue;font-weight:bold">3</span> 秒后自动跳转,如果不想等待,直接点击 <a href="'.$jumpUrl.'">这里</a> 跳转</p>';
$str .= "<script>setTimeout('location.href=".'"'.$jumpUrl.'"'."',2000)</script>";
$str .= '</div>';
$str .= '</div>';
$str .= '</body>';
$str .= '</html>';
echo $str;
}
message('操作提示','操作成功!','ajax.html');
/*
*计算时长
*/
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;
}
$seconds = 3712;
echo changeTimeType($seconds);
/*
*获取客户端IP
*/
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)) ? $ip : '0.0.0.0';
return $ip;
}
/*
*获取在线 端IP
*/
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] ? $onlineipmatches[0] : 'unknown';
}
if($format) {
$ips = explode('.', $S_GLOBAL['onlineip']);
for($i=0;$i<3;$i++) {
$ips[$i] = intval($ips[$i]);
}
return sprintf('%03d%03d%03d', $ips[0], $ips[1], $ips[2]);
} else {
return $S_GLOBAL['onlineip'];
}
}
getOnlineIp();
/*
*获取url
*/
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;
}
echo getUrl();
/*
* 获取url的路径
*/
function getSiteUrl() {
$uri = $_SERVER['REQUEST_URI']?$_SERVER['REQUEST_URI']:($_SERVER['PHP_SELF']?$_SERVER['PHP_SELF']:$_SERVER['SCRIPT_NAME']);
return 'http://'.$_SERVER['HTTP_HOST'].substr($uri, 0, strrpos($uri, '/')+1);
}
echo getSiteUrl();
/*
* 获取各种编码的固定长度
*/
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) {
$slice=($slice.'...');
return $slice;
}
return $slice;
}
$ss='按时打算的撒的撒打算的撒的撒的撒的撒的撒的的撒的123';
echo msubstr($ss,0,11,'utf-8')."...";
/*
* js的escape函数
*/
function escape($string, $encoding = 'UTF-8'){
$return = null;
for ($x = 0; $x < mb_strlen($string, $encoding);$x ++)
{
$str = mb_substr($string, $x, 1, $encoding);
if (strlen($str) > 1) { // 多字节字符
$return .= "%u" . strtoupper(bin2hex(mb_convert_encoding($str, 'UCS-2', $encoding)));
} else {
$return .= "%" . strtoupper(bin2hex($str));
}
}
return $return;
}
$ss='aaaaaaaaaa';
echo escape($ss);
/*
* js的unescape函数
*/
function unescape($str) {
$str = rawurldecode($str);
preg_match_all("/(?:%u.{4})|.{4};|&#\d+;|.+/U",$str,$r);
$ar = $r[0];
foreach($ar as $k=>$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);
}
$ss='aaaaaaaaaa';
echo escape($ss);
--------------------------------------------------------------------------------
/*
* 数组值转换
*/
function makeSemiangle($str) {
$arr = array(
'0' => '0', '1' => '1', '2' => '2', '3' => '3', '4' => '4',
'5' => '5', '6' => '6', '7' => '7', '8' => '8', '9' => '9',
'A' => 'A', 'B' => 'B', 'C' => 'C', 'D' => 'D', 'E' => 'E',
'F' => 'F', 'G' => 'G', 'H' => 'H', 'I' => 'I', 'J' => 'J',
'K' => 'K', 'L' => 'L', 'M' => 'M', 'N' => 'N', 'O' => 'O',
'P' => 'P', 'Q' => 'Q', 'R' => 'R', 'S' => 'S', 'T' => 'T',
'U' => 'U', 'V' => 'V', 'W' => 'W', 'X' => 'X', 'Y' => 'Y',
'Z' => 'Z', 'a' => 'a', 'b' => 'b', 'c' => 'c', 'd' => 'd',
'e' => 'e', 'f' => 'f', 'g' => 'g', 'h' => 'h', 'i' => 'i',
'j' => 'j', 'k' => 'k', 'l' => 'l', 'm' => 'm', 'n' => 'n',
'o' => 'o', 'p' => 'p', 'q' => 'q', 'r' => 'r', 's' => 's',
't' => 't', 'u' => 'u', 'v' => 'v', 'w' => 'w', 'x' => 'x',
'y' => 'y', 'z' => 'z',
'(' => '(', ')' => ')', '〔' => '[', '〕' => ']', '【' => '[',
'】' => ']', '〖' => '[', '〗' => ']', '{' => '{', '}' => '}', '《' => '<',
'》' => '>',
'%' => '%', '+' => '+', '—' => '-', '-' => '-', '〜' => '-',
':' => ':', '。' => '.', '、' => ',', ',' => '.', '、' => '.',
';' => ';', '?' => '?', '!' => '!', '⋯' => '-', '‖' => '|',
'”' => '"', '“' => '"', '‘' => '`', '|' => '|', '〃' => '"',
' ' => ' ','.' => '.');
return strtr($str, $arr);
}
echo makeSemiangle('〖');
/*
* 下载本目录下的某个文件
*/
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);
}
}
echo downloads('aj.php');
/*
* 创建一个目录树
*/
function mkdirs($dir, $mode = 0777) {
if (!is_dir($dir)) {
mkdirs(dirname($dir), $mode);
return mkdir($dir, $mode);
}
return true;
}
mkdir ( "/aa/to/my/dir" , 0700 );
/*
* 检测浏览器语言
*/
function get_client_language($availableLanguages, $default='en'){
if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
$langs=explode(',',$_SERVER['HTTP_ACCEPT_LANGUAGE']);
foreach ($langs as $value){
$choice=substr($value,0,2);
if(in_array($choice, $availableLanguages)){
return $choice;
}
}
}
return $default;
}