PHP SNIPPETS

获取当前Server的IP

$serverHostIp = gethostbyname(php_uname('n'));

 

报错设置

ini_set("display_errors", TRUE);
	error_reporting(E_ALL ^ E_NOTICE);

 

把字符串或者数组转化成UTF8

/**
 * @desc 把字符串或者数组转化成UTF8
 * @param unknown $var
 * @throws Exception
 * @return multitype:string |string
 */
function utf8($var)
{
	if (is_array($var))
	{
		$data = array();
		foreach ($var as $k => $v)
		{
			$data[utf8($k)] = utf8($v);
		}
		return $data;
	}
	else
	{
		if (function_exists('mb_convert_encoding'))
		{
			return mb_convert_encoding($var, 'UTF-8', 'GBK');
		}
		else if (function_exists('iconv'))
		{
			return iconv('GBK', 'UTF-8', $var);
		}
		else
		{
			throw new Exception('don\'t support charset convert!');
		}
	}
}

把php 数据写入到php文件

/**
 * @desc 把php 数据写入到php文件 
 * @param  array $data 
 * @param string $file php文件名 
 */
function writeToPHP($data,$file){
	if(strpos($file, '.php') === false)
		$file = $file.'.php';
	file_exists($file) or touch($file);
	$str = var_export($data,TRUE);
	$str = "<?php\r\n return ".$str.";\r\n";
	file_put_contents($file, $str);
}

获取csv 文件的内容

/**
 * @desc 获取csv 文件的内容
 * @param string $file_name 要写入的文件名
 * @param number $priKey 主键  已什么为主键
 * @param string $recursion 是否 递归(王朝球员的等级和突破都 有多条数据)
 * @return array $data 数组
 */
function getData($file_name,$priKey=0,$recursion = false){
	$baseDataHandle = fopen($file_name, "r");
	$data = array();
	$keys = fgetcsv($baseDataHandle);
	$keys = fgetcsv($baseDataHandle);//第二次是对应的键值
	while (!feof($baseDataHandle))
	{
		$tmp_value = fgetcsv($baseDataHandle);
		$tmp_data = array_combine($keys, $tmp_value);
		if($recursion){
			$data[$tmp_value[$priKey]][] = $tmp_data;
		} else {
			$data[$tmp_value[$priKey]] = $tmp_data;
		}
	}
	fclose($baseDataHandle);
	return $data;
}

获取CSV文件指定字段

/**
 * @desc 获取CSV文件
 * @param unknown $file_name
 * @param unknown $need_keys
 * @return multitype:number multitype: string |multitype:number string multitype:multitype:unknown
 */
function getCsvData($file_name,$need_keys){
	setlocale(LC_ALL,array('zh_CN.gbk','zh_CN.gb2312','zh_CN.gb18030')); //linux中文乱码
	$baseDataHandle = fopen($file_name, "r");
	$data = array();
	//第一步 :获取首行title 里面所有的key
	$first_line_keys = fgetcsv($baseDataHandle);
	//第二步 :检查所需要的need_keys 是否都存在当前csv中
	foreach ($need_keys as $need_key=>$need_value){
		if(!in_array($need_key, $first_line_keys)){
			$msg = "必填字段【".$need_key."】不在上传CSV文件中,请确认首行标题!";
			return array(
					'ret' =>-1,
					'msg' =>$msg,
					'data'=>array(),
			);
		}
	}
	//第三步 获取所有的数据
	while (!feof($baseDataHandle))
	{
		$tmp_value = fgetcsv($baseDataHandle);
		if($tmp_value){
			$tmp_data = array_combine($first_line_keys, $tmp_value); //把第一行的键作为键跟 以后的record合并
			$data[] = $tmp_data;
		}
	}
	fclose($baseDataHandle);
	//第四步 重新格式化 need_keys 中的数据
	$backData = array();
	foreach ($data as $key=>$value){
		$tmp_record = array();
		foreach ($value as $s_key=>$s_value){
			// 4.1 获取当前字段的对应key
			if(isset($need_keys[$s_key])){//如果需求字段在其中
				$tmp_record[$need_keys[$s_key]] = $s_value;
			}
		}
		$backData[] = $tmp_record;
	}
	return array(
			'ret'=>0,
			'msg'=>'ok',
			'data'=>$backData
	);
}

 

php分类数组或者树状数组结构

$baseArray = array(
	array('id'=>1,'parent'=>0,'name'=>'我是爷爷'),
	array('id'=>2,'parent'=>1,'name'=>'我是爹'),
	array('id'=>3,'parent'=>2,'name'=>'我是我'),
	array('id'=>4,'parent'=>3,'name'=>'我是儿子'),
	array('id'=>5,'parent'=>4,'name'=>'我是孙子'),
	array('id'=>6,'parent'=>2,'name'=>'我是兄弟'),
);
$treeData = array();
foreach ($baseArray as $key=>$value){
	if($value['parent'] == '0'){
		$value['sons'] = getSons($value['id'],$baseArray);
		$treeData[] = $value;
	}
}


function getSons($parent_id,$baseArray){
	$sons = array();
	foreach ($baseArray as $key=>$value){
		if($value['parent'] == $parent_id){
			//$sons[] = getSons($value['id'], $baseArray);
			$sons[] = $value;
		}
	}
	if(!empty($sons)){
		foreach ($sons as $key=>&$value){
			$value['sons'] = getSons($value['id'], $baseArray);;
		}
	}
	return $sons;
}
echo '<pre>';
print_r($treeData);

获取参数过滤防止注入

function I($name,$filter=true) {
    if($name == 'callback'){
        header('Content-Type: json');
        if(!preg_match('/^[a-z0-9A-Z_\.\%]*$/', $_REQUEST[$name])){
            return 'callback';
        }
    }
	if(isset($_REQUEST[$name])){
		if(is_array($_REQUEST[$name])){
			return filterArray($_REQUEST[$name],$filter);
		} else {
			if($filter == true){
				return addslashes(htmlentities($_REQUEST[$name]));
			} else {
				return $_REQUEST[$name];
				
			}
		}
	} else {
		return null;
	}

}


function amsOutPut($iRet,$sMsg,$jData = array()){
    $array = array();
    $array['iRet'] = $iRet;
    $array['sMsg'] = $sMsg;
    $array['jData'] = array_merge($array,$jData);
    $array = utf8($array);
    if(I('callback')){
        echo I('callback')."(".json_encode($array).")";
    }else{
        echo json_encode($array);
    }
    die;
}

 

curl_post curl_get

<?php 

/** 
* Send a POST requst using cURL 
* @param string $url to request 
* @param array $post values to send 
* @param array $options for cURL 
* @return string 
*/ 
function curl_post($url, array $post = NULL, array $options = array()) 
{ 
    $defaults = array( 
        CURLOPT_POST => 1, 
        CURLOPT_HEADER => 0, 
        CURLOPT_URL => $url, 
        CURLOPT_FRESH_CONNECT => 1, 
        CURLOPT_RETURNTRANSFER => 1, 
        CURLOPT_FORBID_REUSE => 1, 
        CURLOPT_TIMEOUT => 4, 
        CURLOPT_POSTFIELDS => http_build_query($post) 
    ); 

    $ch = curl_init(); 
    curl_setopt_array($ch, ($options + $defaults)); 
    if( ! $result = curl_exec($ch)) 
    { 
        trigger_error(curl_error($ch)); 
    } 
    curl_close($ch); 
    return $result; 
} 

/** 
* Send a GET requst using cURL 
* @param string $url to request 
* @param array $get values to send 
* @param array $options for cURL 
* @return string 
*/ 
function curl_get($url, array $get = NULL, array $options = array()) 
{    
    $defaults = array( 
        CURLOPT_URL => $url. (strpos($url, '?') === FALSE ? '?' : ''). http_build_query($get), 
        CURLOPT_HEADER => 0, 
        CURLOPT_RETURNTRANSFER => TRUE, 
        CURLOPT_TIMEOUT => 4 
    ); 
    
    $ch = curl_init(); 
    curl_setopt_array($ch, ($options + $defaults)); 
    if( ! $result = curl_exec($ch)) 
    { 
        trigger_error(curl_error($ch)); 
    } 
    curl_close($ch); 
    return $result; 
}

 

GBKUTF8互换

function GBKtoUTF8($str)
{
    if (is_array($str)) {
        foreach ($str as &$value) {
            $value = GBKtoUTF8($value);
        }
        return $str;
    } elseif (is_string($str) && mb_detect_encoding($str, 'UTF-8', true) === false) {
        $str = iconv("GBK", "UTF-8//IGNORE", $str);
        return $str;
    } else {
        return $str;
    }
}

/**
 * @brief UTF8转GBK,传入的数据可为数组或字符串
 * 数组则继续解析到字符串
 * @param $str 字符串或数组
 * @return 转码后字符串或数组
 */
function UTF8toGBK($str)
{
    if (is_array($str)) {
        foreach ($str as &$value) {
            $value = UTF8toGBK($value);
        }
        return $str;
    } elseif (is_string($str) && mb_detect_encoding($str, 'UTF-8', true) !== false) {
        $str = iconv("UTF-8", "GBK//IGNORE", $str);
        return $str;
    } else {
        return $str;
    }
}

 

常用的api接口返回格式化函数

function fmtData($iRet, $sMsg = null, $data = [], $cached = false)
{
    if ($sMsg === null) {
        if ($iRet >= 0) {
            $sMsg = 'ok';
        } else {
            $sMsg = '系统繁忙,请稍候重试!';
        }
    }
    $data = [
        'iRet' => $iRet,
        'sMsg' => $sMsg,
        'jData' => $data
    ];
    if ($cached !== false) {
        $data['cached'] = $cached;
    }

    return GBKtoUTF8($data);
}

 

 

 

 

 

发表评论