常用
生成一个随机字符串
phpfunction generate_rand($l){ $c= “ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789″; srand((double)microtime()*1000000); for($i=0; $i<$l; $i++) { $rand.= $c[rand()%strlen($c)]; } return $rand; }
随机数
php/** * 获取一定范围内的随机数字 * 跟rand()函数的区别是 位数不足补零 例如 * rand(1,9999)可能会得到 465 * rand_number(1,9999)可能会得到 0465 保证是4位的 * @param integer $min 最小值 * @param integer $max 最大值 * @return string */ function rand_number ($min=1, $max=9999) { $strlen = strlen($max); return sprintf("%0" . $strlen . "d", mt_rand($min, $max)); }
二维数组去重
phpfunction remove_duplicate($arr,$key) { // 建立一个目标数组 $result = []; foreach ($arr as $value){ // 查看有没有重复项 $if_exit = isset($result[$value[$key]]); if ($if_exit) { unset($value[$key]); } else { $result[$value[$key]] = $value; } } foreach($result as $key => $row) { $result[] = $row; unset($result[$key]); } return $result; }
日期时间
上一周/上月/前几天
phpdate("Y-m-d",strtotime("-1 week")); date("Y-m-d",strtotime("-1 month")); date("Y-m-d",strtotime("-1 day"));
表单验证
验证邮箱地址
phpfunction is_valid_email($email, $test_mx = false){ if(eregi(“^([_a-z0-9-]+)(.[_a-z0-9-]+)*@([a-z0-9-]+)(.[a-z0-9-]+)*(.[a-z]{2,4})$”, $email)) if($test_mx) { list($username, $domain) = split(“@”, $email); return getmxrr($domain, $mxrecords); }else return true; else return false; }
服务
获取客户端ip
真实ip,即便他使用代理
phpfunction getRealIPAddr(){ if (!empty($_SERVER['HTTP_CLIENT_IP'])) //check ip from share internet { $ip=$_SERVER['HTTP_CLIENT_IP']; } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) //to check ip is pass from proxy { $ip=$_SERVER['HTTP_X_FORWARDED_FOR']; } else { $ip=$_SERVER['REMOTE_ADDR']; } return $ip; }
模拟发送 POST 请求
phpfunction curl_post($url , $data=[]) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); // 要访问的地址 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // 对认证证书来源的检查 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); // 从证书中检查SSL加密算法是否存在 // POST数据 curl_setopt($ch, CURLOPT_POST, 1); // 把post的变量加上 curl_setopt($ch, CURLOPT_POSTFIELDS, $data); $output = curl_exec($ch); curl_close($ch); return $output; }
数组
array_key_exists([],[])
php
$arrTpye = ['jpeg'=>20000,'jpg'=>20000,'png'=>20000];
array_key_exists('jpg',$arrTpye);in_array($ext,$arrTpye);
php
$arrTpye = ['jpeg','jpg','png'];
in_array('jpg',$arrTpye);array_keys()
将关联数组键值返回
array_keys($arrTpye)
php
$arrTpye = ['jpeg'=>20000,'jpg'=>20000,'png'=>20000];
array_keys($arrTpye)//>>['jpeg','jpg','png']array_change_key_case($array , [1/0])
将数组键名转换为大写(1)或小写(0)