api 开发常用函数
<?php
/**
* Created by PhpStorm.
* User: 张华
* Date: 2015/10/29
* Time: 16:10
* QQ: 746502560@qq.com
*/
/**
* @param string $url
* @param string $postdata
* @param array $options
* @return mixed
*/
function curl_post_https($url='', $postdata='', $options=array()){
$curl = curl_init(); // 启动一个CURL会话
curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
//curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 1); // 从证书中检查SSL加密算法是否存在
curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
curl_setopt($curl, CURLOPT_POSTFIELDS, $postdata); // Post提交的数据包
//curl_setopt($curl, CURLOPT_COOKIEFILE, ‘cookie.txt’); // 读取上面所储存的Cookie信息
curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
$tmpInfo = curl_exec($curl); // 执行操作
if (curl_errno($curl)) {
echo 'Errno'.curl_error($curl);
}
curl_close($curl); // 关键CURL会话
return $tmpInfo; // 返回数据
}
/**
* @param string $url
* @param string $postdata
* @param array $options
* @return mixed
*/
function curl_post($url='', $postdata='', $options=array()){
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
if (!empty($options)){
curl_setopt_array($ch, $options);
}
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
/**
* @param string $url
* @param array $options
* @return mixed
*/
function curl_get($url='', $options=array()){
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
if (!empty($options)){
curl_setopt_array($ch, $options);
}
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
/**
* post方式发送
* @param $url
* @param $data_string
* @return array
*/
function curl_post_json($url,$data,$method='POST')
{
if (isset($data)) {
$data_string = json_encode($data);
}
//echo $data_string;
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
if (strtoupper($method) != 'GET') {
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
}
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // 对认证证书来源的检查
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); // 从证书中检查SSL加密算法是否存在
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0)'); // 模拟用户使用的浏览器
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json'
//'Accept: application/json',
//'Authorization: Bearer ' . $this->getToken()
// 'Content-Length: ' . strlen($data_string)
));
$result = curl_exec($ch);
$result = json_decode($result, true);
curl_close($ch);
return $result;
}
/**
* 云吧推送消息发送
* @param $msg
* @param $user
* @param $apn
*/
function yunBarSendMsg($user,$msg,$apn=array(),$isTopic=false,$isTime=false)
{
//是否显示执行时间
if($isTime)
{
$time = microtime();
$time = explode(' ',$time);
}
$url = 'http://rest.yunba.io:8080';
$data = array();
$data['appkey'] = '56259fe8be17bc415cfbf2be';
$data['seckey'] = 'sec-qQFc5vOFsHcsrq8fLrDBt2MTFFrNxOmF0fPaxliURiDcL8ku';
//频道发送
if($isTopic)
{
$data['method'] = 'publish';
$user = str_replace('.','_',$user);
$data['topic'] = $user;
}
//用户发送
else
{
$userType = is_array($user);
if($userType){
$data['method'] = 'publish_to_alias_batch';
foreach($user as $k=>$u){
$user[$k] = str_replace('.','_',$u);
}
$data['aliases']= $user;
}else{
$data['method'] = 'publish_to_alias';
$user = str_replace('.','_',$user);
$data['alias'] = $user;
}
}
$data['msg'] = $msg;
$opts = array();
$opts['time_to_live'] = 10*24*3600;
if($apn && is_array($apn) && !empty($apn)){
$opts['apn_json']['aps'] = $apn;
}
if(!empty($opts)) $data['opts'] = $opts;
//dump($data);
$return = curl_post_json($url,$data);
if($isTime)
{
$timeEnd = microtime();
$timeEnd = explode(' ',$timeEnd);
echo ($timeEnd[1]-$time[1]) + ($timeEnd[0]-$time[0]);
}
//dump($return);
return $return;
}
/**
* 用于api数据返回的格式实现
* @param $data
*/
function apiInfo($data)
{
$arr['status'] = '1';
$arr['msg'] = 'ok';
$arr['data'] = $data;
return $arr;
}
/**
* 用于api错误的数据格式实现
* @param $error
*/
function apiError($error)
{
$arr['status'] = '0';
$arr['msg'] = $error;
$arr['data'] = array();
return $arr;
}
应用程序函数,框架整体函数<pre name="code" class="php"><?php
/**
* Created by JetBrains PhpStorm.
* User: 张华
* Date: 14-3-8
* Time: 下午12:21
* QQ: 746502560@qq.com
* To change this template use File | Settings | File Templates.
*/
include_once ('api.function.php');
/**
* 获取客户端的ip
* @return bool
*/
function get_ip(){
$ip=false;
if(!empty($_SERVER["HTTP_CLIENT_IP"])){
$ip = $_SERVER["HTTP_CLIENT_IP"];
}
if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){
$ips = explode (", ", $_SERVER['HTTP_X_FORWARDED_FOR']);
if ($ip) { array_unshift($ips, $ip); $ip = FALSE; }
for ($i = 0; $i < count($ips); $i++) {
if (!preg_match("^(10|172\.16|192\.168)\.", $ips[$i])) {
$ip = $ips[$i];
break;
}
}
}
return ($ip ? $ip : $_SERVER['REMOTE_ADDR']);
}
/**
* get方式url 参数过滤
* $android_Id = 'http://www.test.com/doc?android=1&imcp_topic=json&aid=46571338&aab=bb&gv=4.0.2&df=androidphone';
* $paramArg = array('android'=>true,'imcp_topic'=>true,'aid'=>true);
* $filterUrl = common::filterParam($android_Id,$paramArg);
* 应用后返回结果:http://www.test.com/doc?android=1&imcp_topic=json&aid=46571338
* 后面的就自动过滤掉&aab=bb&gv=4.0.2&df=androidphone';
* @param type $url
* @param type $paramArgs
* @return string|boolean
*/
function filterParam($url,$paramArgs){
$parts = parse_url($url);
if(!isset($parts['query'])){ return false; }
parse_str($parts['query'], $output);
$path = array_intersect_key($output,$paramArgs);
$pathStr = http_build_query($path);
$parts['query'] = $pathStr;
$filterUrl = $parts['scheme'].'://'.$parts['host'].$parts['path'].'?'.$parts['query'];
unset($parts,$path,$pathStr);
return $filterUrl;
}
/**
* 检测非法字符,存在返回falase 否则返回true
* @param string $data
* @param array $words
* @return bool
*/
function filterKword($data='',$words=array()){
#如果words为空就读取项目所配置的需要验证的关键词
$words=empty($words)?config::readConfig('filterWords'):$words;
#判断data是否为空,如果为空就是全局验证,否则就是验证某个数据是否是否则字符
if($data != ''){
if(in_array($data,$words)){
return false;
}else{
return $data;
}
}
$request=rebuild_array(array_values(array_merge($GLOBALS['_POST'],$GLOBALS['_GET'],$GLOBALS['_COOKIE']))); //得到需要验证的数组
$keywords=array_merge($words,$request);
#只需要判断统计数组中所有的值出现的次数,如果存在就会有重复值,否则用户就是合法数据
$countkeywords=array_count_values($keywords);
foreach($countkeywords as $key=>$value){
if($value > 1){
unset($words,$request,$countkeywords);
return false;
}
}
unset($words,$request,$countkeywords);
return true;
}
/**
* 反转义
* @param type $data
* @return type
*/
function clean($data){
if (is_array($data)){
foreach ($data as $key => $value){
$data[clean($key)] =clean($value);
}
}else{
$data = stripslashes($data);
}
return $data;
}
/**
*获取数据对字符串转义
* @param type $data
* @return type
*/
function addslashes_deep($data){
if(empty($data)){
return $data;
}else{
if(is_array($data)){
foreach($data as $value ){
addslashes_deep($value);
}
}else{
return addslashes($data);
}
}
}
/**
* @param $error_no
* @param $error_msg
* @param $error_file
* @param $error_line
*/
function error($error_no, $error_msg, $error_file, $error_line){
$error = null;
$error_level = array('E_WARNING' => '警告:非致命错误', 'E_NOTICE' => '注意:程序发现了不严谨的地方',
'E_ALL' => '程序报告:所有的错误、警告和建议', 'E_ERROR' => '严重错误:致命的运行错误', 'E_PARSE' =>
'严重错误:程序编译解析错误', 'E_USER_NOTICE' => '注意:程序善意的提醒', 'E_CORE_ERROR' =>
'启动时初始化过程中的致命错误', 'E_CORE_WARNING' => '启动时初始化过程中的警告(非致命性错)', 'E_COMPILE_ERROR' =>
'编译时致命性错', 'E_COMPILE_WARNING' => '编译时警告(非致命性错)', 'E_USER_ERROR' => '自定义的错误消息',
'E_USER_WARNING' => '自定义的警告消息', 'E_STRICT' => '兼容性和互操作性的建议', '1' =>
'严重错误:致命的运行错误', '2' => '注意:程序发现了非致命错误', '4' => '严重错误:程序编译解析错误', '8' =>
'注意:程序发现了不严谨的地方', '256' => '自定义的错误消息', '512' => '自定义的警告消息', '1024' =>
'注意:程序善意的提醒', '2048' => '兼容性和互操作性的建议', '8191' => '程序报告:所有的错误、警告和建议');
if (array_key_exists($error_no, $error_level)){
$error .= '<b><font color="red">错误级别:' . $error_level[$error_no] .
'</font></b><br />';
}
$error .= '<b>错误说明:</b>' . $error_msg . '<br />';
$error .= '<b>发生错误文件名:</b>' . basename($error_file) . '<br />';
$error .= '<b>发生错误行:</b>' . $error_line . '<br />';
echo $error;
}
/**
* @param $string
* @param $key
* @return mixed
* 加密
*/
function encrypt($string, $key)
{
$str_len = strlen($string);
$key_len = strlen($key);
for ($i = 0; $i < $str_len; $i++) {
for ($j = 0; $j < $key_len; $j++) {
$string[$i] = $string[$i] ^ $key[$j];
}
}
return $string;
}
/**
* @param $string
* @param $key
* @return mixed
* 解密
*/
function decrypt($string, $key)
{
$str_len = strlen($string);
$key_len = strlen($key);
for ($i = 0; $i < $str_len; $i++) {
for ($j = 0; $j < $key_len; $j++) {
$string[$i] = $key[$j] ^ $string[$i];
}
}
return $string;
}
/**更换白符
*把所有的空白字符替换为$var;
*/
function html_space($str = '',$var = '')
{
$add_str = array('%01','%02','%03','%04','%05','%06','%07','%08','%09','%0b','%0c','%0e','%0f','%20','%19','%18','%17','%16','%15','%14','%13','%12','%11','%10',' ','%1a','%1b','%1c','%1d','%1f');
return str_replace($add_str,$var,$str);
}
/**
*更安全的空白符去除
*/
function remove_all_space($str, $url_encoded = TRUE)
{
$non_displayables = array();
// every control character except newline (dec 10)
// carriage return (dec 13), and horizontal tab (dec 09)
if ($url_encoded)
{
$non_displayables[] = '/%0[0-8bcef]/'; // url encoded 00-08, 11, 12, 14, 15
$non_displayables[] = '/%1[0-9a-f]/'; // url encoded 16-31
}
$non_displayables[] = '/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]+/S'; // 00-08, 11, 12, 14-31, 127
do
{
$str = preg_replace($non_displayables, '', $str, -1, $count);
}
while ($count);
return $str;
}
/**
* 转义html实体
*对于一些HTML特别字符进行转义以免跨站脚本的攻击
*/
function html_entity($str = '')
{
$add_str = array('<','>','.','/','\'',':',';','(',')','=','"','*','[',']','{','}','%3c','%3e','%2e','%2f','%27','%3a','%3b','%28','%29','%3d','%09','%22','%2a','%5b','%5d','%7b','%7d','$','%24','?','%3f');
$html_str = array('<','>','.','/',''',':',';','(',')','=','"','*','[',']','{','}','<','>','.','/',''',':',';','(',')','=','<br/>','"','*','[',']','{','}','$','$','?','?');
return str_replace($add_str,$html_str,$str);
}
/**
*文件名安全
*/
function save_filename($str, $relative_path = FALSE)
{
$bad = array(
"../",
"<!--",
"-->",
"<",
">",
"'",
'"',
'&',
'$',
'#',
'{',
'}',
'[',
']',
'=',
';',
'?',
"%20",
"%22",
"%3c", // <
"%253c", // <
"%3e", // >
"%0e", // >
"%28", // (
"%29", // )
"%2528", // (
"%26", // &
"%24", // $
"%3f", // ?
"%3b", // ;
"%3d" // =
);
if ( ! $relative_path)
{
$bad[] = './';
$bad[] = '/';
}
$str = html_space($str,'');
return str_replace($bad,'',$str);
}
/**
* 显示错误页面对话框
* @param string $error
* @param string $url
* @param string $go
* @return bool
*/
function show_msg($error ='',$url='',$go='-1')
{
$gourl = '';
$errors = '<div style="margin:40px auto;padding:0px;border:1px solid #ccc;text-align:center;width:280px"><div style="border-bottom:1px solid #ccc; background: blue; width:auto; height:40px; text-align:center; padding-top:5px; color:#ffffff"><font>网站温馨提示</font></div><p>';
if($url != ''){
$url = $errors.$error.'</p><a href="http://'.$url.'">如果你的浏览器没反应,请点击这里</a></div><script>setTimeout("window.location.replace(\'http://'.$url.'\')","3000");</script>';
exit($url);
return true;
}
if($_SERVER['HTTP_REFERER'] != ''){
$gourl = $errors.$error.'</p><a href="'.$_SERVER['HTTP_REFERER'].'">如果你的浏览器没反应,请点击这里</a></div><script>setTimeout("window.history.go(-1)","3000");</script>';
}else{
$host = $_SERVER['HTTP_HOST'] || $_SERVER['SERVER_NAME'];
$gourl = $errors.$error.'</p><a href="http://'.$host.'">如果你的浏览器没反应,请点击这里</a></div><script>setTimeout("window.history.go(-1)","3000");</script>';
}
exit($gourl);
return true;
}
/**
* 遍历文件夹
*/
function read_folder_directory($dir)
{
$listDir = array();
if($handler = opendir($dir)) {
while (($sub = readdir($handler)) !== FALSE) {
if ($sub != "." && $sub != ".." && $sub != "Thumb.db" && $sub != "Thumbs.db") {
if(is_file($dir."/".$sub)) {
$listDir[] = $sub;
}elseif(is_dir($dir."/".$sub)){
$listDir[$sub] = read_folder_directory($dir."/".$sub);
}
}
}
closedir($handler);
}
return $listDir;
}
/**
* 删除文件夹
*/
function delete_floder($dir)
{
$listDir = array();
$filepath = '';
if($handler = opendir($dir)) {
while (($sub = readdir($handler)) !== FALSE) {
$filepath = $dir."/".ltrim($sub,'/');
if ($sub != "." && $sub != ".." && $sub != "Thumb.db" && $sub != "Thumbs.db") {
if(is_file($filepath)) {
unlink($filepath);
}elseif(is_dir($dir."/".$sub)){
$listDir[] = $filepath;//记录文件
delete_floder($filepath); //遍历文件夹
}
}
}
closedir($handler);
}
foreach($listDir as $k)
{
rmdir($k);
}
}
/**
* 二维数组转一维数组
*/
function rebuild_array($arr,$type=false){
static $tmp=array();
//保留键
if($type){
foreach($arr as $key=>$value){
if(is_array($value)){
rebuild_array($value);
}else{
$tmp[$key]=$value;
}
}
}else{
foreach($arr as $value){
if(is_array($value)){
rebuild_array($value);
}else{
$tmp[]=$value;
}
}
}
return $tmp;
}
/**
* @param $array
* @param bool $steep
* 三维数组转二维数组
*/
function array3DToArray2D(&$array,$steep=true){
$array2D=array();
if($steep){
foreach($array as $key=>$value){
if(is_array($value)){
foreach($value as $kk=>$val){
if(is_array($val)){
foreach($val as $k=>$v){
if(is_string($k)){
$array2D[$kk][$k]=$v;
}else{
$array2D[$kk]=$val;
}
}
}
}
}
}
}
return $array2D;
}
/**
* @param $array2D
* @param bool $stkeep
* @param bool $ndformat
* @return mixed
* 去除二维数组中的重复单元
*/
function unique_array($array,$stkeep=true,$ndformat=true){
// 判断是否保留一级数组键 (一级数组键可以为非数字)
if($stkeep) $stArr = array_keys($array);
// 判断是否保留二级数组键 (所有二级数组键必须相同)
if($ndformat) $ndArr = array_keys(end($array));
//降维,也可以用implode,将一维数组转换为用逗号连接的字符串
foreach ($array as $k=>$v){
if(is_int($k)){
unique_array($v);
}
echo '<pre>';
print_r($v);
echo '</pre>';
$temp[] =join(",",$v);
echo '<hr />';
}
//去掉重复的字符串,也就是重复的一维数组
$temp = array_unique($temp);
//再将拆开的数组重新组装
foreach ($temp as $k => $v)
{
if($stkeep) $k = $stArr[$k];
if($ndformat)
{
$tempArr = explode(",",$v);
foreach($tempArr as $ndkey => $ndval) $output[$k][$ndArr[$ndkey]] = $ndval;
}
else $output[$k] = explode(",",$v);
}
return $output;
}
/**
* @param $arr
* @param $keys
* @param string $type
* @return array
* @二维数组排序
*/
function array_sort($arr,$keys,$type='asc'){
$keysvalue = $new_array = array();
foreach ($arr as $k=>$v){
$keysvalue[$k] = $v[$keys];
}
if($type == 'asc'){
asort($keysvalue);
}else{
arsort($keysvalue);
}
reset($keysvalue);
$index = 0;
foreach ($keysvalue as $k=>$v){
$new_array[$index] = $arr[$k];
$index++;
}
return $new_array;
}
/**
* 采用递归算法的快速排序。
*
* @param array $arr 要排序的数组
* @param int $low 最低的排序子段
* @param int $high 最高的排序字段
*/
function array_quick_sort(&$arr, $low, $high)
{
$low_data = $arr[$low];
$prev_low = $low;
$prev_high = $high;
while ($low < $high)
{
while ($arr[$high] >= $low_data && $low < $high) {
$high--;
}
if ($low < $high) {
$arr[$low] = $arr[$high];
$low++;
}
while ($arr[$low] <= $low_data && $low < $high) {
$low++;
}
if ($low < $high) {
$arr[$high] = $arr[$low];
$high--;
}
}
$arr[$low] = $low_data;
if ($prev_low < $low) {
_quick_sort($arr, $prev_low, $low);
}
if ($low + 1 < $prev_high) {
_quick_sort($arr, $low + 1, $prev_high);
}
}
/**
* 创建目录
*/
function mk_dir($dirs,$mode=0755){
set_time_limit(0);
if(is_array($dirs)){
foreach($dirs as $dir){
self::mk_dir($dir,$mode);
}
}else if(is_string($dirs)){
if (is_dir($dirs) || @mkdir($dirs,$mode,true));
}
unset($dirs,$mode);
return true;
}
/**
* php 获取ie的版本
* @return string
*/
function getMSIE() {
$userAgent = strtolower($_SERVER["HTTP_USER_AGENT"]);
if (preg_match("msie 6", $userAgent)) {
return '6';
}else if(preg_match("msie 7", $userAgent)){
return '7';
}else if(preg_match("msie 8", $userAgent)){
return '8';
}else if(preg_match("msie 9", $userAgent)){
return '9';
}else if(preg_match("msie 10", $userAgent)){
return '10';
}
}
/**
* php实现冒泡排序
* @param $array
* @return mixed
*/
function bubble_sort ($array)
{
do {
$again = false;
for($ii=0; $ii<(count($array)-1); $ii++) {
if($array[$ii] > $array[$ii+1]) {
$temp = $array[$ii];
$array[$ii] = $array[$ii+1];
$array[$ii+1] = $temp;
$again = true;
}
}
} while ($again==true);
return $array;
}
/**
* xml转array
* @param $obj
* @return array|string
*/
function simplexml_obj2array($obj) {
if( count($obj) >= 1 )
{
$result = $keys = array();
foreach( $obj as $key=>$value)
{
isset($keys[$key]) ? ($keys[$key] += 1) : ($keys[$key] = 1);
if( $keys[$key] == 1 )
{
$result[$key] = simplexml_obj2array($value);
}
elseif( $keys[$key] == 2 )
{
$result[$key] = array($result[$key], simplexml_obj2array($value));
}
else if( $keys[$key] > 2 )
{
$result[$key][] = simplexml_obj2array($value);
}
}
return $result;
}
else if( count($obj) == 0 )
{
return (string)$obj;
}
}
/**
* 依据ip地址得到位置
* @param $ip
* @return string
*/
function lazdf($ip){
$curl= curl_init();
curl_setopt($curl,CURLOPT_URL,"http://www.ip138.com/ips138.asp?ip=".$ip);
curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);
$ipdz=curl_exec($curl);
curl_close($curl);
preg_match("/<ul class=\"ul1\"><li>(.*?)<\/li>/i",$ipdz,$jgarray);
preg_match("/本站主数据:(.*)/i", $jgarray[1],$ipp);
return "<div class=\"global_widht global_zj zj\" style=\"background: none repeat scroll 0% 0% rgb(226, 255, 191); font-size: 12px; color: rgb(85, 85, 85); height: 30px; line-height: 30px; border-bottom: 1px solid rgb(204, 204, 204); text-align: left;\"> 欢迎来自 <b>".$ipp[1]."</b> 的朋友!</div>";
}
/**
* @param $moduledir
* @param $controller
* @param $action
* @param $params
* @return bool
*/
function readhtml($moduledir,$controller,$action,$params){
#目录组装
$controller=ucfirst($controller);
$htmlFile=$moduledir.$controller.'/'.$action;
#参数链接
$countParams= count($params);
if($countParams){
foreach ($params as $value){
$htmlFile.='/'.$value;
}
}
$htmlFile.='.html';
$fileName=HTML_STATIC_PATH.$htmlFile;
if(file_exists($fileName)){
$url=HTTP_URL.$htmlFile;
header("HTTP/1.1 301 Moved Permanently");
header("Location: ".$url);
die();
}else{
return false;
}
}
/**
* @param $moduledir
* @param $controller
* @param $action
* @param $params
*/
function writeHtml($moduledir,$controller,$action,$params){
#目录组装
$controller=ucfirst($controller);
$htmlFile=HTML_STATIC_PATH.$moduledir.$controller.'/'.$action;
#参数链接
$countParams= count($params);
if($countParams){
foreach ($params as $value){
$htmlFile.='/'.$value;
}
}
$htmlFile.='.html';
$dir=dirname($htmlFile);
mk_dir($dir);
chmod($dir,0775);
$content=ob_get_contents();
file_put_contents($htmlFile, $content);
chmod($htmlFile,0775);
}
/**
* @param undefined $data
* @param undefined $tag
*
* @return
*/
function vardump($data,$tag=false){
echo '<pre>';
if($tag === false){
print_r($data);
}else{
var_dump($data);
}
echo '</pre>';
}
/**
* @return mixed
*/
function scriptFile(){
return isset($_SERVER['REQUEST_URI'])?$_SERVER['REQUEST_URI']:$_SERVER['PHP_SELF'];
}
/**
*
* 系统函数,无需关注,不能修改
* @param undefined $router
* @创建模块、控制器、方法
* @return
*/
function createModule_Control_Action($router){
$router=unserialize($router);
$module=$router->getModule();#得到模块
$moduledir=empty($module)?null:'modules/'.$module.'/';#构建模块
$control=$router->getControl();#得到控制器名
$controller=ucfirst($control).'Controller';#获取控制器
$actionName=$router->getAction();#得到用户的action
$action=$actionName.'Action';#组装真实的action
$params=is_array($router->getParams())?$router->getParams():array();#获取参数
$routerInfo=array(
'moduleName'=>$module,
'moduleDir'=>$moduledir,
'controlName'=>$control,
'trueControllerFileName'=>$controller,
'actionName'=>$actionName,
'trueActionName'=>$action,
'params'=>$params
);
unset($router,$module,$moduledir,$control,$controller,$actionName,$action,$params);
return $routerInfo;
}
/**
* @param $params
* @return string
* @创建静态页面名称
*/
function createStaticHtmlFileName($params){
$suffixName='_';
if( ! empty($params)){
foreach($params as $key=>$value){
$suffixName.=$key.'_'.$value.'_';
}
}
$_tag=substr($suffixName,-1);
unset($params);
if($_tag == '_'){
return substr($suffixName,0,-1);
}
return $suffixName;
}
/**
*预防sql 注入函数
*
*/
function checkSafeInput()
{
$ar1 = $_COOKIE;
$ar2 = $_REQUEST;
if(is_array($ar1) && !empty($ar1))
{
foreach($ar1 as $k=>$v){
$value = strval( isset($v) ? $v : '');
if($value){
if(strstr($value,'8281')) exit('fuck destroy!');
if(strstr($value,'761-')) exit('fuck destroy!');
if(strstr($value,'win.ini')) exit('fuck destroy!');
if(strstr($value,'app.conf')) exit('fuck destroy!');
if(strstr($value,'8281')) exit('fuck destroy!');
if(strstr($value,'761-(')) exit('fuck destroy!');
}
}
}
if(is_array($ar2) && !empty($ar2))
{
foreach($ar2 as $k=>$v){
$value =strval( isset($v) ? $v : '');
if($value){
if(@strstr($value,'8281')) exit('fuck destroy!');
if(@strstr($value,'1=1 or')) exit('fuck destroy!');
if(@strstr($value,'win.ini')) exit('fuck destroy!');
if(@strstr($value,'app.conf')) exit('fuck destroy!');
if(@strstr($value,'8281')) exit('fuck destroy!');
if(@strstr($value,'761-(')) exit('fuck destroy!');
}
}
}
}
/**
*
*浏览器debug 调试
*/
function browserDebug(){
//判断用户当前使用的浏览器 加载不同的调试工具
$browserName=import('Browser.php','extends/tools',true,'','getBrowser');
if( $browserName == 'Firefox' ){
import('FirePHP.class.php','_browserdebug/FirePHPCore');
import('fb.php','_browserdebug/FirePHPCore');
}elseif( $browserName == 'Chrome' ){
import('ChromePhp.php','_browserdebug/chromephp');
}
}
/**
* @param $fileName 文件名称 @代表当前项目 否则就是系统文件 注意要包含后缀名
* @param string $dirName 目录名称
* @param bool $isnew 是否实例化
* @param null $className 如果文件名不是类名 那么就需要填写该变量
* @param null $actionName 方法名
* @param null $args 参数
* @return mixed
*/
function import($fileName,$dirName='library',$isnew=false,$className=null,$actionName=null,$args=null){
$filePath='';
if( substr_count($fileName, '@') > 0 ){
$fileName=str_replace('@.', '', $fileName);
$filePath=APP_PATH.$dirName.DS.$fileName;
}else{
$filePath=ROOT_PATH.$dirName.DS.$fileName;
}
if(file_exists($filePath)){
$callback=include_once($filePath);
}else{
if(APP_DEBUG)
{
echo 'Error:file['.$filePath.'] is not exist!';
exit;
}
}
if($isnew){
//小数点分割
$arr=explode('.',$fileName);
if(is_null($className) || empty($className)){
$className=$arr[0];
}
if(class_exists($className)){
$callback=new $className();
}
if(is_null($actionName) == false){
if(is_null($args)){
$callback=$callback->$actionName();
}else{
$callback=$callback->$actionName($args);
}
}
}
return $callback;
}
/**
* @return string
* @获取当前操作系统
*/
function getOS()
{
$agent = strtolower($_SERVER['HTTP_USER_AGENT']);
$agent = strtolower($agent);
if(strpos($agent, 'windows')) {
$platform = 'windows';
} elseif(strpos($agent, 'macintosh')) {
$platform = 'mac';
} elseif(strpos($agent, 'ipod')) {
$platform = 'ipod';
} elseif(strpos($agent, 'ipad')) {
$platform = 'ipad';
} elseif(strpos($agent, 'iphone')) {
$platform = 'iphone';
} elseif (strpos($agent, 'android')) {
$platform = 'android';
} elseif(strpos($agent, 'unix')) {
$platform = 'unix';
} elseif(strpos($agent, 'linux')) {
$platform = 'linux';
} else {
$platform = 'other';
}
return $platform;
}
/**
* @return bool
* @php 判定是否是移动端浏览器 返回 true 或者 false
*/
function is_mobile_request()
{
$_SERVER['ALL_HTTP'] = isset($_SERVER['ALL_HTTP']) ? $_SERVER['ALL_HTTP'] : '';
$mobile_browser = '0';
$client = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
if(preg_match('/(up.browser|up.link|mmp|symbian|smartphone|midp|wap|phone|iphone|ipad|ipod|android|xoom)/i', strtolower($client)))
$mobile_browser++;
if((isset($_SERVER['HTTP_ACCEPT'])) and (strpos(strtolower($_SERVER['HTTP_ACCEPT']),'application/vnd.wap.xhtml+xml') !== false))
$mobile_browser++;
if(isset($_SERVER['HTTP_X_WAP_PROFILE']))
$mobile_browser++;
if(isset($_SERVER['HTTP_PROFILE']))
$mobile_browser++;
$mobile_ua = strtolower(substr($client,0,4));
$mobile_agents = array(
'w3c ','acs-','alav','alca','amoi','audi','avan','benq','bird','blac',
'blaz','brew','cell','cldc','cmd-','dang','doco','eric','hipt','inno',
'ipaq','java','jigs','kddi','keji','leno','lg-c','lg-d','lg-g','lge-',
'maui','maxo','midp','mits','mmef','mobi','mot-','moto','mwbp','nec-',
'newt','noki','oper','palm','pana','pant','phil','play','port','prox',
'qwap','sage','sams','sany','sch-','sec-','send','seri','sgh-','shar',
'sie-','siem','smal','smar','sony','sph-','symb','t-mo','teli','tim-',
'tosh','tsm-','upg1','upsi','vk-v','voda','wap-','wapa','wapi','wapp',
'wapr','webc','winw','winw','xda','xda-'
);
if(in_array($mobile_ua, $mobile_agents))
$mobile_browser++;
if(strpos(strtolower($_SERVER['ALL_HTTP']), 'operamini') !== false)
$mobile_browser++;
// Pre-final check to reset everything if the user is on Windows
if(strpos(strtolower($client), 'windows') !== false)
$mobile_browser=0;
// But WP7 is also Windows, with a slightly different characteristic
if(strpos(strtolower($client), 'windows phone') !== false)
$mobile_browser++;
if($mobile_browser>0)
return true;
else
return false;
}
/**
* @param $array
* @return array
* @新增对象转数组函数
*/
function object2array($array){
if(is_object($array)){
$array = (array)$array;
}
if(is_array($array)){
foreach($array as $key=>$value){
$array[$key] = object2array($value);
}
}
return $array;
}
/**
* @param $file
* @param string $code
* @return mixed
* @ 程序新增 amr 转mp3
* $mp3 = amrTomp3('\data\upload\vi\20141111101117_46172cece8ae8-7ae2-4831-b8be-509aa2678767.amr');
* echo $mp3;
*/
function amr2mp3($file,$code='64')
{
if($file){
$httpFile = str_replace('.amr','.mp3',$file);
$httpFileMp3 = APPROOT.$httpFile;
if(file_exists($httpFileMp3)){
return $httpFile;
}
$file = APPROOT.$file;
}
if(file_exists($file))
{
//echo $file;
$newfileName = str_replace('.amr','.mp3',$file);
//echo $newfileName;
$execFile = APPROOT.'/ffmpeg/'.$code.'/ffmpeg.exe';
$execCmd = $execFile." -i ".$file." ".$newfileName;
//echo $execCmd;
exec($execCmd);
return $httpFile;
}
}
/**
* @param string $operator
* @return string
* @支持运营商 $operator
* @移动 10086
* @联通 10010
* @电信 10000
*/
function randTel($operator='10086')
{
$secondArr = array(3,4,5,8);
switch($operator)
{
case '10086':
$tel3 = array(4,5,6,7,8,9);
$tel4 = array(7);
$tel5 = array(0,1,2,7,8,9);
$tel8 = array(2,3,7,8);
break;
case '10010':
$tel3 = array(0,1,2);
$tel4 = array(5);
$tel5 = array(5,6);
$tel8 = array(5,6);
break;
case '10000':
$secondArr = array(3,5,8);
$tel3 = array(3,49);
$tel4 = array();
$tel5 = array(3);
$tel8 = array(0,9);
break;
default:
$tel3 = array();
$tel4 = array();
$tel5 = array();
$tel8 = array();
break;
}
$second = $secondArr[array_rand($secondArr,1)];
$thirdArr = ($second == 3) ? $tel3 : (($second == 5)
? $tel5 : (($second == 8) ? $tel8 : (($second == 4) ? $tel4 : array())));
$third = $thirdArr[array_rand($thirdArr,1)];
return str_pad(("1".$second."".$third),11,mt_rand(10000000,99999999));
}