当前位置:网站首页>编程干货│PHP 常见方法封装
编程干货│PHP 常见方法封装
2022-06-21 21:58:00 【极客飞兔】
目录
一、curl的get请求
function get_curl($url, $timeout = 5) {
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true );
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
$result = curl_exec( $ch );
curl_close($ch);
return $result;
}二、curl的post请求
function post_curl($url, $data, $timeout = 5) {
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true );
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch,CURLOPT_POSTFIELDS,$data);
$result = curl_exec( $ch );
curl_close($ch);
return $result;
}三、随机字符串
function random_str($len=10, $type=1){
switch($type){
case 2:
$chars='0123456789';
break;
case 3:
$chars='abcdefghijklmnopqrstuvwxyz';
break;
case 4:
$chars='ABDEFGHIJKLMNOPQRSTUVWXYZ';
break;
case 5:
$chars='abcdefghijklmnopqrstuvwxyzABDEFGHIJKLMNOPQRSTUVWXYZ';
break;
case 6:
$chars='abcdefghijklmnopqrstuvwxyz0123456789';
break;
default:
$chars='abcdefghijklmnopqrstuvwxyzABDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
break;
}
$str = '';
for ( $i = 0; $i <$len; $i++ ){
$str .= $chars[ mt_rand(0, strlen($chars) - 1) ];
}
return $str;
}四、返回json数据
function json_back($data, $is_exit = true) {
$callback = $_GET['callback'] ?? '';
if ($callback) {
echo '' . $callback . "(" . json_encode($data, JSON_UNESCAPED_UNICODE) . ")";
} else {
echo json_encode($data, JSON_UNESCAPED_UNICODE);
}
if ($is_exit) exit();
}五、数据过滤
function check_data($data){
if(is_array($data)){
foreach($data as $key => $v){
$data[$key] = $this->check_data($v);
}
}else{
$data = trim($data);
$data = strip_tags($data);
$data = htmlspecialchars($data);
$data = addslashes($data);
}
return $data;
}六、重定向
function redirect($url = 'https://blog.csdn.net/weixin_41635750'){
if (!headers_sent()) {
header("Location: {$url}");
exit();
}else{
$str = "<meta http-equiv='Refresh' content='0;URL={$url}'>";
exit($str);
}
}
七、获取客户端ip
function get_real_ip() {
if(@$_SERVER["HTTP_ALI_CDN_REAL_IP"]){
$ip = $_SERVER["HTTP_ALI_CDN_REAL_IP"];
}
elseif (@$_SERVER["HTTP_X_FORWARDED_FOR"] ?: false) {
$ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
$ips = explode(',', $ip);
$ip = $ips[0];
} elseif (@$_SERVER["HTTP_CDN_SRC_IP"] ?: false) {
$ip = $_SERVER["HTTP_CDN_SRC_IP"];
} elseif (getenv('HTTP_CLIENT_IP')) {
$ip = getenv('HTTP_CLIENT_IP');
} elseif (getenv('HTTP_X_FORWARDED')) {
$ip = getenv('HTTP_X_FORWARDED');
} elseif (getenv('HTTP_FORWARDED_FOR')) {
$ip = getenv('HTTP_FORWARDED_FOR');
} elseif (getenv('HTTP_FORWARDED')) {
$ip = getenv('HTTP_FORWARDED');
} else {
$ip = $_SERVER['REMOTE_ADDR'];
}
$ip = str_replace(array('::ffff:', '[', ']'), array('', '', ''), $ip);
return $ip;
}八、格式化链接
function formatLink($url, array $param = []) {
if (!empty($param)) {
$suffix = http_build_query($param);
$url = strpos($url, '?') > 0 ? $url . '&' . $suffix : $url . '?' . $suffix;
}
return $url;
}九、隐藏中间字符串
function hiddenPartStr($str) {
$strLen = mb_strlen($str);
if ($strLen > 1 && $strLen <= 3) $str = mb_substr($str, 0, 1) . str_repeat('*', $strLen - 1);
if ($strLen > 3) {
$halfPosition = (int)($strLen / 2);
$startPosition = (int)($halfPosition / 2);
$diffPosition = $halfPosition - $startPosition;
$endPosition = $strLen % 2 == 0 ? $halfPosition + $diffPosition : (++$halfPosition) + $diffPosition;
$str = mb_substr($str, 0, $startPosition) . str_repeat('*', $endPosition - $startPosition) . mb_substr($str, $endPosition, $strLen - $endPosition);
}
return $str;
}十、是否时间格式
function isDatetime($datetime) {
$isTime = strtotime($datetime);
return $isTime !== FALSE && $isTime != -1;
}十一、大小格式化
function toSize($bytes, $precision = 2) {
$rank = 0;
$size = $bytes;
$unit = "B";
while ($size > 1024) {
$size = $size / 1024;
$rank++;
}
$size = round($size, $precision);
switch ($rank) {
case "1":
$unit = "KB";
break;
case "2":
$unit = "MB";
break;
case "3":
$unit = "GB";
break;
case "4":
$unit = "TB";
break;
}
return $size . "" . $unit;
}十二、删除文件夹
function deleteDir($dirname) {
if (!file_exists($dirname)) return false;
array_map('unlink', glob("{$dirname}/*"));
@rmdir($dirname);
return true;
}十三、判断是否整形
function isInt($str) {
if (is_string($str)) {
return ctype_digit($str);
} else {
return is_int($str);
}
}十四、金额转中文
function moneyToString($num) {
$c1 = "零壹贰叁肆伍陆柒捌玖";
$c2 = "分角元拾佰仟万拾佰仟亿";
//精确到分后面就不要了,所以只留两个小数位
$num = round($num, 2);
//将数字转化为整数
$num = $num * 100;
if (strlen($num) > 10) {
return "金额太大,请检查";
}
$i = 0;
$c = "";
while (1) {
if ($i == 0) {
//获取最后一位数字
$n = substr($num, strlen($num) - 1, 1);
} else {
$n = $num % 10;
}
//每次将最后一位数字转化为中文
$p1 = substr($c1, 3 * $n, 3);
$p2 = substr($c2, 3 * $i, 3);
if ($n != '0' || ($n == '0' && ($p2 == '亿' || $p2 == '万' || $p2 == '元'))) {
$c = $p1 . $p2 . $c;
} else {
$c = $p1 . $c;
}
$i = $i + 1;
//去掉数字最后一位了
$num = $num / 10;
$num = (int)$num;
//结束循环
if ($num == 0) {
break;
}
}
$j = 0;
$slen = strlen($c);
while ($j < $slen) {
//utf8一个汉字相当3个字符
$m = substr($c, $j, 6);
//处理数字中很多0的情况,每次循环去掉一个汉字“零”
if ($m == '零元' || $m == '零万' || $m == '零亿' || $m == '零零') {
$left = substr($c, 0, $j);
$right = substr($c, $j + 3);
$c = $left . $right;
$j = $j - 3;
$slen = $slen - 3;
}
$j = $j + 3;
}
//这个是为了去掉类似23.0中最后一个“零”字
if (substr($c, strlen($c) - 3, 3) == '零') {
$c = substr($c, 0, strlen($c) - 3);
}
//将处理的汉字加上“整”
if (empty($c)) {
return "零元整";
} else {
return $c . "整";
}
}十五、检测大陆身份证
function verifyIdCard($idCard) {
if (!is_numeric(substr($idCard, 0, 3))) return true;
$set = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
$ver = ['1', '0', 'x', '9', '8', '7', '6', '5', '4', '3', '2'];
$arr = str_split($idCard);
$sum = 0;
for ($i = 0; $i < 17; $i++) {
if (!is_numeric($arr[$i])) {
return false;
}
$sum += $arr[$i] * $set[$i];
}
$mod = $sum % 11;
if (strcasecmp($ver[$mod], $arr[17]) != 0) {
return false;
}
return true;
}十六、计算年龄
function getAge($birthDate) {
$age = strtotime($birthDate);
if ($age === false) return 0;
list($y1, $m1, $d1) = explode("-", date("Y-m-d", $age));
$now = strtotime("now");
list($y2, $m2, $d2) = explode("-", date("Y-m-d", $now));
$age = $y2 - $y1;
if ((int)($m2 . $d2) < (int)($m1 . $d1))
$age -= 1;
return $age;
}十七、获取周几
function getWeekCN($timestamp = 0) {
$week = ['日', '一', '二', '三', '四', '五', '六'];
if ($timestamp == 0) $timestamp = time();
return $week[date("w", $timestamp)];
}十八、xml转数组
function xmlToArray($xml) {
return json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
}十九、数组转xml
function arrayToXml($arr) {
$xml = "<xml>";
foreach ($arr as $key => $val) {
if (is_numeric($val)) {
$xml .= "<" . $key . ">" . $val . "</" . $key . ">";
} else {
$xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
}
}
$xml .= "</xml>";
return $xml;
}二十、不区分大小写的in_array实现
function inArrayCase($value, $array) {
return in_array(strtolower($value), array_map('strtolower', $array));
}边栏推荐
- Uni app advanced style framework / production environment [Day10]
- Contracting of development environment and test environment (and request encapsulation of uniapp)
- How to use metric unit buffer in PostGIS
- 硬件开发笔记(五):硬件开发基本流程,制作一个USB转RS232的模块(四):创建CON连接器件封装并关联原理图元器件
- Enterprise wechat built-in application H5 development record-1
- 记一次MQ并发消费导致任务状态异常问题
- [use four tricky examples to help you understand] how data is stored in memory
- redis主从复制(九)
- keep-alive的使用注意点
- Native applet application applet - publishing process
猜你喜欢

Promise error capture processing -- promise Technology

關於 麒麟系統開發錯誤“fatal error: GL/gl.h: No such file or directory“ 的解决方法

樹莓派開發筆記(十六):樹莓派4B+安裝mariadb數據庫(mysql開源分支)並測試基本操作

C delegate

You have a chance, here is a stage

Layout roadmap, the perfect combination of spatial layout and data visualization

Some users of uniapp wechat authorization cannot be authorized normally
![[use four tricky examples to help you understand] how data is stored in memory](/img/ef/372ae4483bda909318cbdc05bd38f0.png)
[use four tricky examples to help you understand] how data is stored in memory

Software testing Q & A

Software testing concepts
随机推荐
How to open a VIP account in flush? Is it safe?
211 thèse de maîtrise en divinité à l'Université! 75 lignes et 20 mauvaises lignes! Réponse de l'école: le tuteur a arrêté d'inscrire...
Kirin System Development Notes (V): making and installing the startup USB flash disk of the Kirin system, installing the Kirin system on the physical machine, and building a Qt development environment
You have a chance, here is a stage
在线文本按行批量反转工具
Danfoss inverter maintenance vlt5000/vlt6000/vlt8000
IPD芯片出货量超10亿颗,芯和半导体亮相IMS2022
Go语言学习教程(十二)
Golang calls sdl2, plays PCM audio, and reports an error signal arrived during external code execution.
windows sql server 如何卸载干净?
开发环境和测试环境的发包(及uniapp的request封装)
CISSP certification 2021 textbook OSG 9th Edition added (modified) knowledge points: comparison with the 8th Edition
同花顺VIP开户怎么开户,安全吗?
泰山OFFICE技术讲座:微软雅黑字体故意设置的坑,粗体错误
Contracting of development environment and test environment (and request encapsulation of uniapp)
leetcode1337. Row K with the weakest combat effectiveness in the matrix
树莓派开发笔记(十七):树莓派4B+上Qt多用户连接操作Mysql数据库同步(单条数据悲观锁)
Notes on the development of raspberry pie (17): QT multi-user connection operation on raspberry pie 4b+ MySQL database synchronization (pessimistic lock of single data)
keep-alive的使用注意点
企业综合组网实训二