PHP常用函数总结
来源:互联网 发布:大智慧股票行情软件 编辑:程序博客网 时间:2024/05/16 12:05
函数总结:
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; } }
2、生成随机字符串
//生成随机字符串function generateRandomString($length = 10) { $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; $randomString = ''; for ($i = 0; $i < $length; $i++) { $randomString .= $characters[rand(0, strlen($characters) - 1)]; } return $randomString;}
3、生成随机字符串方法二
//生成随机字符串方法二function generateRandomString($length = 10) { $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; $randomString = ''; $randomString = substr(str_shuffle($str),0,$length); return $randomString;}
4、获取文件扩展名
//获取文件扩展名function getExtension($filename){ $myext = substr($filename, strrpos($filename, '.')); return str_replace('.','',$myext);}
5、获取文件大小并格式化
//获取文件大小并格式化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]); }}
6、PHP替换标签字符
//PHP替换标签字符function stringParser($string,$replacer){ $result = str_replace(array_keys($replacer), array_values($replacer),$string); return $result;}
7、列出目录下的文件
//列出目录下的文件function listDirFiles($DirPath){ if($dir = opendir($DirPath)){ while(($file = readdir($dir))!== false){ if(!is_dir($DirPath.$file)) { echo "filename: $file<br />"; } } }}
8、获取当前页面的url
//获取当前页面的urlfunction 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;}
9、强制下载
//强制下载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!"; }}
10、汉字截取函数
/* Utf-8、gb2312都支持的汉字截取函数 cut_str(字符串, 截取长度, 开始长度, 编码); 编码默认为 utf-8 开始长度默认为 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; }}
11、获取用户真实IP
//获取用户真实IPfunction getIp() {if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))$ip = getenv("HTTP_CLIENT_IP");elseif (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown"))$ip = getenv("HTTP_X_FORWARDED_FOR");elseif (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))$ip = getenv("REMOTE_ADDR");elseif (isset ($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))$ip = $_SERVER['REMOTE_ADDR'];else$ip = "unknown";return ($ip);}
12、防止注入
//防止注入function injCheck($sql_str) { $check = preg_match('/select|insert|update|delete|\'|\/\*|\*|\.\.\/|\.\/|union|into|load_file|outfile/', $sql_str);if ($check) {echo '非法字符!!'.$sql_str;exit;} else {return $sql_str;}}
13、页面提示跳转
//页面提示跳转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;}
14、时间长度转换
//时间长度转换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;}
15、post发送数据
function http_send_data($url,$data='',$do='post'){$ch = curl_init();//初始化curl_setopt($ch, CURLOPT_URL,$url);curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);if($do=='post'){curl_setopt($ch,CURLOPT_POST,true);curl_setopt($ch,CURLOPT_POSTFIELDS,$data);}$output = curl_exec($ch);curl_close($ch);return $output;}
function do_post_request($url, $data, $optional_headers = null) { $params = array('http' => array( 'method' => 'POST', 'content' => $data )); if ($optional_headers !== null) { $params['http']['header'] = $optional_headers; } $ctx = stream_context_create($params); $fp = @fopen($url, 'rb', false, $ctx); if (!$fp) { throw new Exception("Problem with $url, $php_errormsg"); } $response = @stream_get_contents($fp); if ($response === false) { throw new Exception("Problem reading data from $url, $php_errormsg"); } return $response; }
16、CURL获取数据
function curl_file_get_contents($durl){$ch = curl_init();curl_setopt($ch, CURLOPT_URL, $durl);curl_setopt($ch, CURLOPT_TIMEOUT, 5);curl_setopt($ch, CURLOPT_USERAGENT, _USERAGENT_);curl_setopt($ch, CURLOPT_REFERER,_REFERER_);curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);$r = curl_exec($ch);curl_close($ch);return $r;}
17、根据地球两点经纬度计算距离的两个函数
//根据两个经纬度数据判断两点距离function GetDistance($lat_a, $lng_a, $lat_b, $lng_b) { //R是地球半径(米) $R = 6378137; $pk = doubleval(180 / 3.1415926535898); $a1 = doubleval($lat_a / $pk); $a2 = doubleval($lng_a / $pk); $b1 = doubleval($lat_b / $pk); $b2 = doubleval($lng_b / $pk); $t1 = doubleval(cos($a1) * cos($a2) * cos($b1) * cos($b2)); $t2 = doubleval(cos($a1) * sin($a2) * cos($b1) * sin($b2)); $t3 = doubleval(sin($a1) * sin($b1)); $tt = doubleval(acos($t1 + $t2 + $t3)); $s=round($R * $tt); if($s>=3000) $s=(string)($s/1000).'公里'; else $s=$s.'米'; return $s;}
function getDistance($lat1, $lng1, $lat2, $lng2) {$earthRadius = 6367000; $lat1 = ($lat1 * pi() ) / 180; $lng1 = ($lng1 * pi() ) / 180; $lat2 = ($lat2 * pi() ) / 180; $lng2 = ($lng2 * pi() ) / 180; $calcLongitude = $lng2 - $lng1; $calcLatitude = $lat2 - $lat1; $stepOne = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2); $stepTwo = 2 * asin(min(1, sqrt($stepOne))); $calculatedDistance = $earthRadius * $stepTwo; return round($calculatedDistance); }
0 0
- php常用函数总结
- php常用函数总结
- php常用函数总结
- php常用函数(总结)
- PHP常用函数总结
- PHP常用函数总结
- php常用函数总结
- PHP常用函数总结
- PHP常用函数总结
- php常用函数总结
- php 常用函数总结
- php常用函数总结
- php 常用字符串函数总结
- PHP 常用函数总结分享
- PHP常用字符串函数总结
- PHP常用字符串函数总结
- PHP常用字符串函数总结
- PHP常用字符串函数总结
- php面向对象基本概念(魔法方法)__invoke() __toString() __call() __callStatic() __clone()
- Markdonw 小技巧
- [LeetCode] Longest Palindromic Substring
- Java 文件上传 JQ 文件上传
- 创建一个字符设备驱动
- PHP常用函数总结
- Linux VGA驱动移植实验
- 如何编译Apache Hadoop2.2.0源代码
- OpenGL Tutorial: (2) Creating an OpenGL Window
- leecode(1)Two Sum
- 利用python画微分方程(组)的数值曲线
- 马上去行动马上去体验
- 在浏览器中运行applet
- Web开发教程--如何让图片在div中垂直居中