1、curl 常用post和get:
function curl_post($url, $data)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
function curl_get($url){
$ch=curl_init($url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Linux; U; Android 4.4.1; zh-cn; R815T Build/JOP40D) AppleWebKit/533.1 (KHTML, like Gecko)Version/4.0 MQQBrowser/4.5 Mobile Safari/533.1');
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
$content=curl_exec($ch);
curl_close($ch);
return($content);
}
2、取随机数
function nonce_str($length=16) {
$returnStr='';
$pattern = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
for($i = 0; $i < $length; $i ++) {
$returnStr .= $pattern {mt_rand ( 0, 61 )};
}
return $returnStr;
}
3、获取客户端IP
function get_ip() {
if (isset($_SERVER)) {
if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$realip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
$realip = $_SERVER['HTTP_CLIENT_IP'];
} else {
$realip = $_SERVER['REMOTE_ADDR'];
}
} else {
if (getenv("HTTP_X_FORWARDED_FOR")) {
$realip = getenv( "HTTP_X_FORWARDED_FOR");
} elseif (getenv("HTTP_CLIENT_IP")) {
$realip = getenv("HTTP_CLIENT_IP");
} else {
$realip = getenv("REMOTE_ADDR");
}
}
return $realip;
}
4、图片转base64
/**
* 图片转base64编码
* @param $image_file
* @return string
*/
function base64_encode_image ($image_file) {
$base64_image = '';
$image_info = getimagesize($image_file);
$image_data = fread(fopen($image_file, 'r'), filesize($image_file));
$base64_image = 'data:' . $image_info['mime'] . ';base64,' . chunk_split(base64_encode($image_data));
return $base64_image;
}
5、根据类型变量生成UUID
/**
* 根据PHP各种类型变量生成唯一标识号
* @param mixed $mix 变量
* @return string
*/
function to_guid_string($mix)
{
if (is_object($mix)) {
return spl_object_hash($mix);
} elseif (is_resource($mix)) {
$mix = get_resource_type($mix) . strval($mix);
} else {
$mix = serialize($mix);
}
return md5($mix);
}
6、字符串截取
/**
* 字符截取
* @param $string 需要截取的字符串
* @param $length 长度
* @param $dot
*/
function str_cut($sourcestr, $length, $dot = '...')
{
$returnstr = '';
$i = 0;
$n = 0;
$str_length = strlen($sourcestr); //字符串的字节数
while (($n < $length) && ($i <= $str_length)) {
$temp_str = substr($sourcestr, $i, 1);
$ascnum = Ord($temp_str); //得到字符串中第$i位字符的ascii码
if ($ascnum >= 224) { //如果ASCII位高与224,
$returnstr = $returnstr . substr($sourcestr, $i, 3); //根据UTF-8编码规范,将3个连续的字符计为单个字符
$i = $i + 3; //实际Byte计为3
$n++; //字串长度计1
} elseif ($ascnum >= 192) { //如果ASCII位高与192,
$returnstr = $returnstr . substr($sourcestr, $i, 2); //根据UTF-8编码规范,将2个连续的字符计为单个字符
$i = $i + 2; //实际Byte计为2
$n++; //字串长度计1
} elseif ($ascnum >= 65 && $ascnum <= 90) {
//如果是大写字母,
$returnstr = $returnstr . substr($sourcestr, $i, 1);
$i = $i + 1; //实际的Byte数仍计1个
$n++; //但考虑整体美观,大写字母计成一个高位字符
} else {
//其他情况下,包括小写字母和半角标点符号,
$returnstr = $returnstr . substr($sourcestr, $i, 1);
$i = $i + 1; //实际的Byte数计1个
$n = $n + 0.5; //小写字母和半角标点等与半个高位字符宽...
}
}
if ($str_length > strlen($returnstr)) {
$returnstr = $returnstr . $dot; //超过长度时在尾处加上省略号
}
return $returnstr;
}
7、常用生成难验名方法[适用于微信]
/**
* 数据签名认证
* @param array $data 被认证的数据
* @return string 签名
*/
function data_auth_sign($data)
{
//数据类型检测
if (!is_array($data)) {
$data = (array) $data;
}
ksort($data); //排序
$code = http_build_query($data); //url编码并生成query字符串
$sign = sha1($code); //生成签名
return $sign;
}
8、生成唯一订单号
/**
*生成订单号
*@return string
*/
function neworder_num(){
$yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
$orderSn = $yCode[intval(date('Y')) - 2011] . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));
return $orderSn;
}
9、通用格式化字符串方法(适用于隐藏银行卡、手机号、身份证号等 )
/**
* 隐藏字符串
* @param string $str 格式化之前的原数据
* @param string $replacement 替换为的字符一般如:*,.,x...
* @param string $start, $length 从哪位到哪位
* @return string 格式化的字符串
*/function fmt_card($str, $replacement = '*', $start = 5, $length = 10)
{
$len = mb_strlen($str,'utf-8');
if ($len > intval($start+$length)) {
$str1 = mb_substr($str,0,$start,'utf-8');
$str2 = mb_substr($str,intval($start+$length),NULL,'utf-8');
} else {
$str1 = mb_substr($str,0,1,'utf-8');
$str2 = mb_substr($str,$len-1,1,'utf-8');
$length = $len - 2;
}
$new_str = $str1;
for ($i = 0; $i < $length; $i++) {
$new_str .= $replacement;
}
$new_str .= $str2;
return $new_str;
}
10、验证手机号
//验证手机号
function check_phone($number){
if(preg_match("/^1\d{10}$/",$number)){
return true;
}else{
return false;
}
}
11、验证银行卡
function check_bankcode($s){
$n = 0;
for ($i = strlen($s); $i >= 1; $i--){
$index=$i-1;
//偶数位
if ($i % 2==0){
$n += $s{$index};
}else{//奇数位
$t = $s{$index} * 2;
if ($t > 9) {
$t = (int)($t/10)+ $t%10;
}
$n += $t;
}
}
return ($n % 10) == 0;
}
12、根据IP获取所属省市
function ip_city_str($str){
return str_replace(array('省','市'),'',$str);
}
function get_ip_city($ip) //太平洋接口
{
$url = 'http://whois.pconline.com.cn/ipJson.jsp?json=true&ip=';
$city = curl_get($url . $ip);
$city = mb_convert_encoding($city, "UTF-8", "GB2312");
$city = json_decode($city, true);
if ($city['city']) {
$location = ip_city_str($city['pro']).ip_city_str($city['city']);
} else {
$location = ip_city_str($city['pro']);
}
if($location){
return $location;
}else{
return false;
}
}
function get_ip_city3($ip) //淘宝接口
{
$url = 'http://ip.taobao.com/service/getIpInfo.php?ip=';
@$data = file_get_contents($url . $ip);
$arr = json_decode($data, true);
if (array_key_exists('code',$arr) && $arr['code']==0) {
if ($arr['data']['city']) {
$location = $arr['data']['region'].$arr['data']['city'];
} else {
$location = $arr['data']['region'];
}
}
if($location){
return $location;
}else{
return false;
}
}
13、随机模拟生成IP
function generate_rand_ip(){
$ip2id= round(rand(600000, 2550000) / 10000); //第一种方法,直接生成
$ip3id= round(rand(600000, 2550000) / 10000);
$ip4id= round(rand(600000, 2550000) / 10000);
//下面是第二种方法,在以下数据中随机抽取
$arr_1 = array("218","218","66","66","218","218","60","60","202","204","66","66","66","59","61","60","222","221","66","59","60","60","66","218","218","62","63","64","66","66","122","211");
$randarr= mt_rand(0,count($arr_1)-1);
$ip1id = $arr_1[$randarr];
return $ip1id.".".$ip2id.".".$ip3id.".".$ip4id;
}
14、微信发送模板消息
function messages($content,$from,$openid,$nick){
$template = array(
'touser'=>$openid,
'template_id'=>"FkBrGCTtFhVRj8GmUm-YXBZqHyLKJcIp60i3jtfEyz0",
'url'=>"http://www.uuuho.com",
'topcolor'=>"#576b95",
'data'=>array(
'first'=>array('value'=>urlencode($nick.",您有一条新的消息"),'color'=>"#576b95"),
'keyword1'=>array('value'=>urlencode($from),'color'=>'#576b95'),
'keyword2'=>array('value'=>urlencode(date('Y-m-d H:i:s',time())),'color'=>'#576b95'),
'keyword3'=>array('value'=>urlencode($content),'color'=>'#0e0e0e'),
'remark'=>array('value'=>urlencode('点击立即回复'),'color'=>'#576b95'), )
);
$json_token=http_request("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=SECRET");
$access_token=json_decode($json_token,true);
$access_tokens=$access_token['access_token'];
$json_template=json_encode($template);
$url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$access_tokens;
$res=http_request($url,urldecode($json_template));
$res = json_decode($res,true);
return 1;
}
15、根据日期判断星座
/*
* 计算星座的函数 string get_zodiac_sign(string month, string day)
* 输入:月份,日期
* 输出:星座名称或者错误信息
*/
function get_zodiac_sign($month, $day)
{
// 检查参数有效性
if ($month < 1 || $month > 12 || $day < 1 || $day > 31)
return (false);
// 星座名称以及开始日期
$signs = array(
array( "20" => "水瓶座"),
array( "19" => "双鱼座"),
array( "21" => "白羊座"),
array( "20" => "金牛座"),
array( "21" => "双子座"),
array( "22" => "巨蟹座"),
array( "23" => "狮子座"),
array( "23" => "处女座"),
array( "23" => "天秤座"),
array( "24" => "天蝎座"),
array( "22" => "射手座"),
array( "22" => "摩羯座")
);
list($sign_start, $sign_name) = each($signs[(int)$month-1]);
if ($day < $sign_start)
list($sign_start, $sign_name) = each($signs[($month -2 < 0) ? $month = 11: $month -= 2]);
return $sign_name;
}
16、计算距离现在的时间
/**
* 传入时间戳,计算距离现在的时间
* @param number $time 时间戳
* @return string 返回多少以前
*/
function word_time($time) {
$time = (int) substr($time, 0, 10);
$int = time() - $time;
$str = '';
if ($int <= 2){
$str = sprintf('刚刚', $int);
}elseif ($int < 60){
$str = sprintf('%d秒前', $int);
}elseif ($int < 3600){
$str = sprintf('%d分钟前', floor($int / 60));
}elseif ($int < 86400){
$str = sprintf('%d小时前', floor($int / 3600));
}elseif ($int < 1728000){
$str = sprintf('%d天前', floor($int / 86400));
}else{
$str = date('Y-m-d H:i:s', $time);
}
return $str;
}
17、获取当前页面网址
/**
* 获取当前的url 地址
* @return type
*/
function get_url() {
$sys_protocal = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
$php_self = $_SERVER['PHP_SELF'] ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME'];
$path_info = isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : '';
$relate_url = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : $php_self.(isset($_SERVER['QUERY_STRING']) ? '?'.$_SERVER['QUERY_STRING'] : $path_info);
return $sys_protocal.(isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '').$relate_url;
}
18、计算两个日期相隔多少天
function diffBetweenTwoDays ($day1, $day2)
{
$second1 = strtotime($day1);
$second2 = strtotime($day2);
if ($second1 < $second2) {
$tmp = $second2;
$second2 = $second1;
$second1 = $tmp;
}
return ($second1 - $second2) / 86400;
}
19、正则简单使用
$html = file_get_contents("http://wwww.baidu.com");
//简单使用(.*?)可以匹配到数据
$rule = '/<span id="title" style="color:red;">(.*?)<\/span>/ies';
$res = preg_match_all($rule,$html,$match); //结果匹配数组渲染进$match
var_dump($match);die; //输出查看结果
$title = $match[0][0];