Download the PHP package cdyun/php-tool without Composer

On this page you can find all versions of the php package cdyun/php-tool. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.

FAQ

After the download, you have to make one include require_once('vendor/autoload.php');. After that you have to import the classes with use statements.

Example:
If you use only one package a project is not needed. But if you use more then one package, without a project it is not possible to import the classes with use statements.

In general, it is recommended to use always a project to download your libraries. In an application normally there is more than one library needed.
Some PHP packages are not free to download and because of that hosted in private repositories. In this case some credentials are needed to access such packages. Please use the auth.json textarea to insert credentials, if a package is coming from a private repository. You can look here for more information.

  • Some hosting areas are not accessible by a terminal or SSH. Then it is not possible to use Composer.
  • To use Composer is sometimes complicated. Especially for beginners.
  • Composer needs much resources. Sometimes they are not available on a simple webspace.
  • If you are using private repositories you don't need to share your credentials. You can set up everything on our site and then you provide a simple download link to your team member.
  • Simplify your Composer build process. Use our own command line tool to download the vendor folder as binary. This makes your build process faster and you don't need to expose your credentials for private repositories.
Please rate this library. Is it a good library?

Informations about the package php-tool

PHP8.1+ 通用工具包

简介

这是一个基于PHP8.1+特性开发的模块化通用工具包,提供了数组处理、字符串处理、时间处理、加解密、消息体、IP地址处理、地理计算、全局辅助方法等功能。支持对象和静态两种调用方式,兼容进程和协程环境。

安装

模块化目录

工具包采用清晰的模块化架构,每个模块专注于特定领域的功能:

数组处理模块

特性

核心方法

方法名 功能描述 调用示例
first() 获取第一个元素 Arr::first([1, 2, 3])
last() 获取最后一个元素 Arr::last([1, 2, 3])
find() 查找满足条件的元素 Arr::find([1, 2, 3], fn($n) => $n > 1)
tree() 数组转树形结构 Arr::tree($list, 'id', 'pid')
list() 树形结构转数组 Arr::list($tree)
deepMerge() 深度合并数组 Arr::deepMerge($arr1, $arr2)

兼容性说明

数组处理模块会自动检测PHP版本,在PHP 8.4+环境下使用原生数组函数以获得最佳性能:

在PHP 8.4以下版本,模块会使用兼容的实现,确保代码在不同PHP版本下都能正常运行。

使用示例

树形结构转换

tree() / toTree() - 数组转树形结构
list() - 树形结构转数组
level() - 数组转层级结构
path() - 数组转路径结构
getParentIds() - 获取叶子节点的所有父节点ID
getChildIds() - 获取所有子节点的ID

数组访问和操作

deepMerge() - 数组深度合并
get() - 数组获取值(支持点语法)
set() - 数组设置值
has() - 数组判断是否存在键
only() - 数组仅保留指定键
except() - 数组排除指定键

多维数组处理

group() - 多维数组分组
count() - 多维数组统计
sum() - 多维数组求和
avg() - 多维数组求平均值
max() - 多维数组求最大值
min() - 多维数组求最小值

PHP 8.4+数组函数

first() - 数组首元素
last() - 数组尾元素
find() - 查找满足条件的元素
findKey() - 查找满足条件的键名
any() - 检查是否存在满足条件的元素
all() - 检查是否所有元素都满足条件

数组查找和判断

map() - 数组映射
filter() - 数组过滤
reduce() - 数组归约
find() - 查找满足条件的第一个元素的键值
findKey() - 查找满足条件的第一个元素的键名
some() - 检查是否存在满足条件的元素(别名方法)
every() - 检查是否所有元素都满足条件(别名方法)
contains() - 数组是否包含指定元素
containsKey() - 数组是否包含指定键名
isEmpty() - 数组是否为空
isAssoc() - 数组是否为关联数组
isIndexed() - 数组是否为索引数组

数组排序

sort() - 升序/降序
multiSort() - 多维数组排序
reverse() - 数组反转
shuffle() - 数组打乱

数组去重

unique() - 数组去重
multiUnique() - 多维数组去重

数组分页和切片

paginate() - 数组分页
slice() - 数组切片
chunk() - 数组分割

数组合并和差集

merge() - 数组合并
mergeRecursive() - 数组合并(保留键名)
diff() - 数组差集
diffKey() - 数组差集(带键名)
intersect() - 数组交集
intersectKey() - 数组交集(带键名)

数组转换

toJson() - 多维数组转JSON
fromJson() - JSON转多维数组
flatten() - 数组扁平化
keys() - 数组键名
values() - 数组键值
flip() - 键名与键值翻转
column() - 数组列提取

数组键值操作

mapKeys() - 数组映射键名
mapValues() - 数组映射键值
combine() - 数组合并键值
fillKeys() - 数组填充键值
fill() - 数组填充

数组随机操作

random() - 数组随机元素
randomMany() - 数组随机多个元素

数组元素操作

shift() - 数组弹出第一个元素
pop() - 数组弹出最后一个元素
unshift() - 数组头部添加元素
push() - 数组尾部添加元素
remove() - 数组删除指定元素
removeKey() - 数组删除指定键名

字符串处理模块

特性

核心方法

方法名 功能描述 调用示例
maskPhone() 手机号脱敏 Str::maskPhone('13800138000')
maskEmail() 邮箱脱敏 Str::maskEmail('[email protected]')
camel() 转驼峰命名 Str::camel('hello_world')
snake() 转蛇形命名 Str::snake('helloWorld')
toBase64() 转Base64编码 Str::toBase64('hello')
fromBase64() Base64解码 Str::fromBase64('aGVsbG8=')

使用示例

脱敏

mask() - 字符串脱敏
maskPhone() - 手机号脱敏
maskEmail() - 邮箱脱敏
maskIdCard() - 身份证号脱敏
maskBankCard() - 银行卡号脱敏
maskName() - 姓名脱敏

字符串长度和截断

length() - 字符串长度
truncate() - 字符串截断
limit() - 字符串限制长度
wordTruncate() - 字符串单词截断

字符串命名转换

snake() - 驼峰转下划线
toSnake() - 驼峰命名转下划线命名(支持数组键名)
camel() - 下划线转驼峰
toCamel() - 下划线命名转驼峰命名(支持数组键名)
studly() - 首字母大写驼峰命名
ucfirst() - 首字母大写
lcfirst() - 首字母小写
ucwords() - 单词首字母大写
upper() - 全部大写
lower() - 全部小写
swap() - 大小写转换
title() - 标题格式

字符串查找和判断

contains() - 是否包含子串
startsWith() - 是否以子串开头
endsWith() - 是否以子串结尾
pos() - 子串首次出现位置
rpos() - 子串最后一次出现位置
count() - 子串出现次数
match() - 字符串是否匹配正则

字符串替换

replace() - 字符串替换
replaceArray() - 字符串批量替换
replaceRegex() - 字符串正则替换
substrReplace() - 字符串截取并替换

字符串分割和连接

split() - 字符串分割
toArray() - 字符串分割为数组
fromArray() - 数组连接为字符串
join() - 字符串连接
concat() - 字符串拼接

字符串去除空白

trim() - 去除首尾空白
ltrim() - 去除左侧空白
rtrim() - 去除右侧空白
clean() - 去除所有空白

字符串填充

padLeft() - 左侧填充
padRight() - 右侧填充
padBoth() - 两侧填充

字符串重复

repeat() - 字符串重复
reverse() - 字符串反转

字符串随机

random() - 生成随机字符串
numeric() - 生成随机数字字符串
alpha() - 生成随机字母字符串

字符串编码解码

toBase64() - Base64编码
fromBase64() - Base64解码
toUrlEncode() - URL编码
fromUrlEncode() - URL解码
toHtmlEntities() - HTML实体编码
fromHtmlEntities() - HTML实体解码
toJson() - JSON编码
fromJson() - JSON解码
toXml() - XML编码
fromXml() - XML解码
toBinary() - 二进制编码
fromBinary() - 二进制解码
toHex() - 十六进制编码
fromHex() - 十六进制解码

字符串哈希

md5() - MD5哈希
sha1() - SHA1哈希
sha256() - SHA256哈希
sha512() - SHA512哈希

字符串验证

isEmail() - 是否为邮箱
isUrl() - 是否为URL
isIp() - 是否为IP地址
isIpv4() - 是否为IPv4地址
isIpv6() - 是否为IPv6地址
isPhone() - 是否为手机号
isIdCard() - 是否为身份证号
isBankCard() - 是否为银行卡号
isNumeric() - 是否为数字
isAlpha() - 是否为字母
isAlnum() - 是否为字母数字
isHex() - 是否为十六进制
isBinary() - 是否为二进制
isJson() - 是否为JSON
isXml() - 是否为XML
isSerialized() - 是否为序列化数据
isBase64() - 是否为Base64

字符串转换

toArray() - 字符串转数组
fromArray() - 数组转字符串
toObject() - 字符串转对象
fromObject() - 对象转字符串
toQuery() - 字符串转查询字符串
fromQuery() - 查询字符串转数组

字符串格式化

format() - 字符串格式化
template() - 字符串模板渲染
indent() - 字符串缩进
unindent() - 字符串去除缩进

字符串字符操作

first() - 获取字符串首字符
last() - 获取字符串尾字符
firstN() - 获取字符串前N个字符
lastN() - 获取字符串后N个字符
removeFirst() - 去除首字符
removeLast() - 去除尾字符
removeFirstN() - 去除前N个字符
removeLastN() - 去除后N个字符

字符串统计

count() - 统计子串出现次数
wordCount() - 统计单词数
charCount() - 统计字符数
byteLength() - 统计字节长度

字符串安全

escapeHtml() - 转义HTML特殊字符
escapeSql() - 转义SQL特殊字符
escapeJs() - 转义JavaScript特殊字符
escapeRegex() - 转义正则表达式特殊字符

字符串比较

compare() - 字符串比较
similarity() - 字符串相似度
distance() - 字符串编辑距离

时间处理模块

特性

核心方法

方法名 功能描述 调用示例
format() 格式化时间 Time::format(time(), 'Y-m-d')
now() 获取当前时间 Time::now()
today() 获取今天日期 Time::today()
yesterday() 获取昨天日期 Time::yesterday()
tomorrow() 获取明天日期 Time::tomorrow()
add() 时间加法 Time::add(time(), 3600)
sub() 时间减法 Time::sub(time(), 3600)
diff() 时间差 Time::diff(time(), time() - 3600)
diffForHumans() 人性化时间差 Time::diffForHumans(time() - 3600)
weekStart() 本周开始时间 Time::weekStart()
weekEnd() 本周结束时间 Time::weekEnd()
monthStart() 本月开始时间 Time::monthStart()
monthEnd() 本月结束时间 Time::monthEnd()

使用示例

时间格式化

format() - 格式化时间
now() - 获取当前时间
today() - 获取今天日期
yesterday() - 获取昨天日期
tomorrow() - 获取明天日期

时间计算

add() - 时间加法
sub() - 时间减法
diff() - 时间差
diffForHumans() - 人性化时间差

周日期范围

weekStart() - 获取本周开始时间
weekEnd() - 获取本周结束时间
$weekEnd = Time::weekEnd(); // 本周日23:59:59的时间戳
$weekEnd = Time::weekEnd(time()); // 指定时间所在周的结束时间
$weekEndFormatted = Time::format(Time::weekEnd(), 'Y-m-d H:i:s'); // '2025-12-28 23:59:59'
lastWeekStart() - 获取上周开始时间
$lastWeekStart = Time::lastWeekStart(); // 上周一00:00:00的时间戳
$lastWeekStartFormatted = Time::format(Time::lastWeekStart(), 'Y-m-d H:i:s'); // '2025-12-15 00:00:00'
lastWeekEnd() - 获取上周结束时间
$lastWeekEnd = Time::lastWeekEnd(); // 上周日23:59:59的时间戳
$lastWeekEndFormatted = Time::format(Time::lastWeekEnd(), 'Y-m-d H:i:s'); // '2025-12-21 23:59:59'

月日期范围

monthStart() - 获取本月开始时间
$monthStart = Time::monthStart(); // 本月1日00:00:00的时间戳
$monthStart = Time::monthStart(time()); // 指定时间所在月的开始时间
$monthStartFormatted = Time::format(Time::monthStart(), 'Y-m-d H:i:s'); // '2025-12-01 00:00:00'
monthEnd() - 获取本月结束时间
$monthEnd = Time::monthEnd(); // 本月最后一天23:59:59的时间戳
$monthEnd = Time::monthEnd(time()); // 指定时间所在月的结束时间
$monthEndFormatted = Time::format(Time::monthEnd(), 'Y-m-d H:i:s'); // '2025-12-31 23:59:59'
lastMonthStart() - 获取上月开始时间
$lastMonthStart = Time::lastMonthStart(); // 上月1日00:00:00的时间戳
$lastMonthStartFormatted = Time::format(Time::lastMonthStart(), 'Y-m-d H:i:s'); // '2025-11-01 00:00:00'
lastMonthEnd() - 获取上月结束时间
$lastMonthEnd = Time::lastMonthEnd(); // 上月最后一天23:59:59的时间戳
$lastMonthEndFormatted = Time::format(Time::lastMonthEnd(), 'Y-m-d H:i:s'); // '2025-11-30 23:59:59'

年日期范围

yearStart() - 获取本年开始时间
$yearStart = Time::yearStart(); // 本年1月1日00:00:00的时间戳
$yearStart = Time::yearStart(time()); // 指定时间所在年的开始时间
$yearStartFormatted = Time::format(Time::yearStart(), 'Y-m-d H:i:s'); // '2025-01-01 00:00:00'
yearEnd() - 获取本年结束时间
$yearEnd = Time::yearEnd(); // 本年12月31日23:59:59的时间戳
$yearEnd = Time::yearEnd(time()); // 指定时间所在年的结束时间
$yearEndFormatted = Time::format(Time::yearEnd(), 'Y-m-d H:i:s'); // '2025-12-31 23:59:59'
lastYearStart() - 获取上年开始时间
$lastYearStart = Time::lastYearStart(); // 上年1月1日00:00:00的时间戳
$lastYearStartFormatted = Time::format(Time::lastYearStart(), 'Y-m-d H:i:s'); // '2024-01-01 00:00:00'
lastYearEnd() - 获取上年结束时间
$lastYearEnd = Time::lastYearEnd(); // 上年12月31日23:59:59的时间戳
$lastYearEndFormatted = Time::format(Time::lastYearEnd(), 'Y-m-d H:i:s'); // '2024-12-31 23:59:59'

时间判断

$timestamp = time();
between() - 判断是否在某个时间区间内
$inRange = Time::between($timestamp, time() - 3600, time() + 3600); // true
$inRange = Time::between(time() - 7200, time() - 3600, time()); // false
isToday() - 判断是否是今天
$isToday = Time::isToday($timestamp); // true
$isToday = Time::isToday(time() - 86400); // false
isYesterday() - 判断是否是昨天
$isYesterday = Time::isYesterday(time() - 86400); // true
$isYesterday = Time::isYesterday(time()); // false
isTomorrow() - 判断是否是明天
$isTomorrow = Time::isTomorrow(time() + 86400); // true
$isTomorrow = Time::isTomorrow(time()); // false
isThisWeek() - 判断是否是本周
$isThisWeek = Time::isThisWeek($timestamp); // true
$isThisWeek = Time::isThisWeek(time() - 604800); // false
isThisMonth() - 判断是否是本月
$isThisMonth = Time::isThisMonth($timestamp); // true
$isThisMonth = Time::isThisMonth(strtotime('2025-11-01')); // false
isThisYear() - 判断是否是本年
$isThisYear = Time::isThisYear($timestamp); // true
$isThisYear = Time::isThisYear(strtotime('2024-01-01')); // false

日期信息获取

daysInMonth() - 获取某个月的天数
$days = Time::daysInMonth(12); // 31(12月有31天)
$days = Time::daysInMonth(2, 2024); // 29(2024年2月有29天,闰年)
$days = Time::daysInMonth(2, 2023); // 28(2023年2月有28天,平年)
dayOfWeek() - 获取某天是周几
$weekday = Time::dayOfWeek(time()); // 0-6(0表示周日,1表示周一,以此类推)
$weekday = Time::dayOfWeek(strtotime('2025-12-26')); // 5(周五)
dayOfWeekName() - 获取某天是周几(中文名称)
$weekdayName = Time::dayOfWeekName(time()); // '周五'
$weekdayName = Time::dayOfWeekName(strtotime('2025-12-28')); // '周日'
dayOfYear() - 获取某天是本年第几天
$dayOfYear = Time::dayOfYear(time()); // 360(2025年第360天)
$dayOfYear = Time::dayOfYear(strtotime('2025-01-01')); // 1(第1天)
weekOfYear() - 获取某天是本年第几周
$weekOfYear = Time::weekOfYear(time()); // 52(第52周)
$weekOfYear = Time::weekOfYear(strtotime('2025-01-01')); // 1(第1周)

年龄计算

age() - 计算年龄
$age = Time::age('1990-01-01'); // 35(假设当前是2025年)
$age = Time::age('2000-12-31'); // 24(假设当前是2025年)
$age = Time::age('2010-06-15'); // 15(假设当前是2025年)

时间戳转换

toTimestamp() - 时间字符串转时间戳
$timestamp = Time::toTimestamp('2025-12-26 12:00:00'); // 1735200000
$timestamp = Time::toTimestamp('2025-12-26'); // 1735152000
$timestamp = Time::toTimestamp('now'); // 当前时间戳
$timestamp = Time::toTimestamp('+1 day'); // 明天同一时间的时间戳
toMillisecond() - 时间戳转毫秒
$millisecond = Time::toMillisecond(time()); // 1735200000000
$millisecond = Time::toMillisecond(1735200000); // 1735200000000
fromMillisecond() - 毫秒转时间戳
$timestamp = Time::fromMillisecond(1735200000000); // 1735200000
millisecond() - 获取当前毫秒时间戳
$millisecond = Time::millisecond(); // 当前时间的毫秒时间戳
microsecond() - 获取当前微秒时间戳
$microsecond = Time::microsecond(); // 当前时间的微秒时间戳
microtime() - 获取当前时间戳(带微秒)
$microtime = Time::microtime(); // 1735200000.123456

时区操作

timezone() - 获取当前时区
$timezone = Time::timezone(); // 'Asia/Shanghai'(或其他时区)
setTimezone() - 设置时区
$success = Time::setTimezone('UTC'); // true
$success = Time::setTimezone('America/New_York'); // true

// 设置时区后获取时间
Time::setTimezone('UTC');
$utcTime = Time::now(); // UTC时间

Time::setTimezone('Asia/Shanghai');
$shanghaiTime = Time::now(); // 上海时间

实际应用场景

// 订单创建时间显示
$createdAt = time() - 3600; // 1小时前创建
$displayTime = Time::diffForHumans($createdAt); // '1小时前'

// 数据统计时间范围
$weekStart = Time::weekStart();
$weekEnd = Time::weekEnd();
// 查询本周数据:WHERE created_at >= $weekStart AND created_at <= $weekEnd

// 用户生日计算
$birthday = '1990-05-15';
$age = Time::age($birthday); // 35岁

// 活动倒计时
$endTime = strtotime('2025-12-31 23:59:59');
$diff = Time::diff(time(), $endTime); // 距离结束的秒数

// 日程安排
$today = Time::today();
$tomorrow = Time::tomorrow();
$weekStart = Time::weekStart();
$weekEnd = Time::weekEnd();

// 数据归档
$lastMonthStart = Time::lastMonthStart();
$lastMonthEnd = Time::lastMonthEnd();
// 归档上月数据:WHERE created_at >= $lastMonthStart AND created_at <= $lastMonthEnd

// 报表生成
$yearStart = Time::yearStart();
$yearEnd = Time::yearEnd();
// 生成本年报表:WHERE created_at >= $yearStart AND created_at <= $yearEnd

// 定时任务检查
if (Time::isToday($taskTime)) {
    // 执行今天的任务
}

// 工作日判断
$weekday = Time::dayOfWeek(time());
if ($weekday >= 1 && $weekday <= 5) {
    // 周一到周五,工作日
} else {
    // 周六周日,休息日
}

// 高精度时间测量
$startTime = Time::microsecond();
// 执行一些代码
$endTime = Time::microsecond();
$duration = $endTime - $startTime; // 微秒

数学计算处理模块

特性

核心方法

方法名 功能描述 调用示例
add() 高精度加法 Math::add('1.1', '2.2')
sub() 高精度减法 Math::sub('3.3', '1.1')
mul() 高精度乘法 Math::mul('2.5', '4')
div() 高精度除法 Math::div('10', '3')
avg() 平均数 Math::avg([1, 2, 3, 4, 5])
median() 中位数 Math::median([1, 2, 3, 4, 5])
discount() 计算折扣价 Math::discount('100', '0.2')
tax() 计算税额 Math::tax('100', '0.13')

使用示例

基础运算

add() - 高精度加法
$sum = Math::add(0.1, 0.2); // 0.3(而不是0.30000000000000004)
$sum = Math::add('1.1', '2.2', 2); // 3.30(保留2位小数)
sub() - 高精度减法
$diff = Math::sub(0.3, 0.1); // 0.2
$diff = Math::sub('5.5', '2.2', 2); // 3.30
mul() - 高精度乘法
$product = Math::mul(0.1, 0.2); // 0.02
$product = Math::mul('1.5', '2.5', 2); // 3.75
div() - 高精度除法
$quotient = Math::div(0.3, 0.1); // 3
$quotient = Math::div('10', '3', 2); // 3.33
mod() - 取模运算
$mod = Math::mod(10, 3); // 1
$mod = Math::mod('10.5', '3'); // 1.5
pow() - 幂运算
$pow = Math::pow(2, 10); // 1024
$pow = Math::pow('2.5', 3, 2); // 15.62
sqrt() - 平方根运算
$sqrt = Math::sqrt(16); // 4
$sqrt = Math::sqrt('2', 4); // 1.4142

取整运算

round() - 四舍五入
$rounded = Math::round(3.14159, 2); // 3.14
$rounded = Math::round(3.5, 0); // 4
ceil() - 向上取整
$ceil = Math::ceil(3.2); // 4
$ceil = Math::ceil(3.8, 1); // 3.8
$ceil = Math::ceil('3.21', 1); // 3.3
floor() - 向下取整
$floor = Math::floor(3.8); // 3
$floor = Math::floor(3.2, 1); // 3.2
$floor = Math::floor('3.89', 1); // 3.8

比较运算

compare() - 比较两个数的大小
$result = Math::compare(5, 3); // 1(5 > 3)
$result = Math::compare(3, 5); // -1(3 < 5)
$result = Math::compare(5, 5); // 0(相等)
equal() - 判断两个数是否相等
$equal = Math::equal(0.1 + 0.2, 0.3); // true(解决浮点数比较问题)
$equal = Math::equal('1.000', '1.00', 2); // true(保留2位小数比较)

格式化

format() - 格式化数字
$formatted = Math::format(1234567.89, 2, true); // 1,234,567.89(带千分位)
$formatted = Math::format(1234567.89, 2, false); // 1234567.89(不带千分位)
$formatted = Math::format('1234567.89123', 3, true); // 1,234,567.891

三角函数

sin() - 正弦函数
$sin = Math::sin(Math::deg2rad(30)); // 0.5(30度的正弦值)
$sin = Math::sin(3.14159 / 2); // 1(π/2的正弦值)
cos() - 余弦函数
$cos = Math::cos(Math::deg2rad(60)); // 0.5(60度的余弦值)
$cos = Math::cos(0); // 1(0度的余弦值)
tan() - 正切函数
$tan = Math::tan(Math::deg2rad(45)); // 1(45度的正切值)
$tan = Math::tan(3.14159 / 4); // 1(π/4的正切值)
asin() - 反正弦函数
$asin = Math::asin(1); // 1.5708(π/2)
$asin = Math::asin(0.5); // 0.5236(π/6)
acos() - 反余弦函数
$acos = Math::acos(0); // 1.5708(π/2)
$acos = Math::acos(0.5); // 1.0472(π/3)
atan() - 反正切函数
$atan = Math::atan(1); // 0.7854(π/4)
$atan = Math::atan(0); // 0

对数运算

ln() - 自然对数(以e为底)
$ln = Math::ln(Math::exp(1)); // 1
$ln = Math::ln(2.71828); // 1
log10() - 常用对数(以10为底)
$log10 = Math::log10(100); // 2
$log10 = Math::log10(1000); // 3
log() - 自定义底数对数
$log = Math::log(8, 2); // 3(2的3次方等于8)
$log = Math::log(100, 10); // 2(10的2次方等于100)

角度转换

rad2deg() - 弧度转角度
$deg = Math::rad2deg(3.14159); // 180(π弧度 = 180度)
$deg = Math::rad2deg(1.5708); // 90(π/2弧度 = 90度)
deg2rad() - 角度转弧度
$rad = Math::deg2rad(180); // 3.14159(180度 = π弧度)
$rad = Math::deg2rad(90); // 1.5708(90度 = π/2弧度)

数值操作

abs() - 绝对值
$abs = Math::abs(-10); // 10
$abs = Math::abs(10); // 10
$abs = Math::abs('-5.5'); // 5.5
factorial() - 阶乘
$factorial = Math::factorial(5); // 120(5! = 5×4×3×2×1)
$factorial = Math::factorial(0); // 1(0! = 1)
gcd() - 最大公约数
$gcd = Math::gcd(12, 18); // 6
$gcd = Math::gcd(24, 36); // 12
lcm() - 最小公倍数
$lcm = Math::lcm(4, 6); // 12
$lcm = Math::lcm(3, 5); // 15

金融计算

percentage() - 百分比计算
$percentage = Math::percentage(25, 100); // 25(25占100的25%)
$percentage = Math::percentage('30', '150', 2); // 20.00
discount() - 折扣计算
$discounted = Math::discount(100, 0.8); // 80(打8折)
$discounted = Math::discount('200', '0.7', 2); // 140.00(打7折)
tax() - 税费计算
$tax = Math::tax(100, 0.1); // 10(100的10%税额)
$tax = Math::tax('500', '0.13', 2); // 65.00(500的13%税额)
taxIncluded() - 含税金额计算
$taxIncluded = Math::taxIncluded(100, 0.1); // 110(100 + 10%税)
$taxIncluded = Math::taxIncluded('500', '0.13', 2); // 565.00
taxExcluded() - 不含税金额计算
$taxExcluded = Math::taxExcluded(110, 0.1); // 100(110 / 1.1)
$taxExcluded = Math::taxExcluded('565', '0.13', 2); // 500.00
simpleInterest() - 简单利息计算
$simpleInterest = Math::simpleInterest(1000, 0.05, 2); // 100(1000本金,5%年利率,2年)
$simpleInterest = Math::simpleInterest('5000', '0.04', 3, 2); // 600.00
compoundInterest() - 复利计算
$compoundInterest = Math::compoundInterest(1000, 0.05, 2); // 1102.5(1000本金,5%年利率,2年复利)
$compoundInterest = Math::compoundInterest('5000', '0.04', 3, 2); // 5624.32

随机数生成

random() - 生成指定范围内的随机数
$random = Math::random(1, 100); // 1-100之间的随机整数
$random = Math::random('1.5', '5.5', 2); // 1.50-5.50之间的随机数(保留2位小数)

范围检查

inRange() - 数值范围检查
$inRange = Math::inRange(5, 1, 10); // true(5在1-10范围内)
$inRange = Math::inRange(15, 1, 10); // false(15不在1-10范围内)
clamp() - 限制数值范围
$clamped = Math::clamp(5, 1, 10); // 5(在范围内,保持不变)
$clamped = Math::clamp(15, 1, 10); // 10(超出最大值,限制为10)
$clamped = Math::clamp(-5, 1, 10); // 1(小于最小值,限制为1)
$clamped = Math::clamp('5.5', '1.0', '10.0', 1); // 5.5

数值判断

isPositive() - 判断是否为正数
$isPositive = Math::isPositive(10); // true
$isPositive = Math::isPositive(-5); // false
$isPositive = Math::isPositive(0); // false
isNegative() - 判断是否为负数
$isNegative = Math::isNegative(-5); // true
$isNegative = Math::isNegative(10); // false
$isNegative = Math::isNegative(0); // false
isZero() - 判断是否为零
$isZero = Math::isZero(0); // true
$isZero = Math::isZero(0.0000000001, 10); // true(保留10位小数比较)
$isZero = Math::isZero(1); // false
isEven() - 判断是否为偶数
$isEven = Math::isEven(4); // true
$isEven = Math::isEven(5); // false
isOdd() - 判断是否为奇数
$isOdd = Math::isOdd(5); // true
$isOdd = Math::isOdd(4); // false
isPrime() - 判断是否为质数
$isPrime = Math::isPrime(7); // true
$isPrime = Math::isPrime(4); // false
$isPrime = Math::isPrime(2); // true
$isPrime = Math::isPrime(1); // false
isValid() - 判断数值是否有效
$isValid = Math::isValid(123); // true
$isValid = Math::isValid('123.45'); // true
$isValid = Math::isValid('abc'); // false
$isValid = Math::isValid(INF); // false(无穷大)
$isValid = Math::isValid(NAN); // false(非数字)

插值运算

lerp() - 线性插值
$lerp = Math::lerp(0, 10, 0.5); // 5(0和10的中点)
$lerp = Math::lerp(0, 10, 0.25); // 2.5(0和10的25%位置)
$lerp = Math::lerp('0', '100', '0.75', 1); // 75.0

统计分析

average() - 平均值计算
$avg = Math::average([1, 2, 3, 4, 5]); // 3
$avg = Math::average([1.5, 2.5, 3.5], 2); // 2.50
median() - 中位数计算
$median = Math::median([1, 2, 3, 4, 5]); // 3
$median = Math::median([1, 2, 3, 4]); // 2.5(2和3的平均值)
$median = Math::median(['1.5', '2.5', '3.5'], 2); // 2.50
mode() - 众数计算
$mode = Math::mode([1, 2, 2, 3, 3, 3]); // 3(出现次数最多)
$mode = Math::mode([1, 2, 3]); // 1(多个众数时返回第一个)
standardDeviation() - 标准差计算
$stdDev = Math::standardDeviation([1, 2, 3, 4, 5]); // 1.414
$stdDev = Math::standardDeviation([10, 20, 30], 2); // 10.00

实际应用场景

// 电商订单金额计算
$subtotal = Math::add('99.99', '49.99'); // 149.98(商品小计)
$discount = Math::discount($subtotal, '0.9'); // 134.98(打9折)
$tax = Math::tax($discount, '0.13'); // 17.55(13%税)
$total = Math::add($discount, $tax, 2); // 152.53(总金额)

// 贷款利息计算
$principal = 100000; // 本金10万
$rate = 0.05; // 年利率5%
$years = 5; // 5年
$simpleInterest = Math::simpleInterest($principal, $rate, $years); // 25000(简单利息)
$compoundInterest = Math::compoundInterest($principal, $rate, $years); // 27628.16(复利)

// 数据分析
$scores = [85, 92, 78, 90, 88, 95, 82];
$avg = Math::average($scores, 2); // 87.14(平均分)
$median = Math::median($scores, 2); // 88.00(中位数)
$stdDev = Math::standardDeviation($scores, 2); // 5.67(标准差)

// 价格范围检查
$price = 99.99;
$minPrice = 50;
$maxPrice = 100;
if (Math::inRange($price, $minPrice, $maxPrice)) {
    echo '价格在合理范围内';
}

// 数值格式化显示
$amount = 1234567.89123;
$formatted = Math::format($amount, 2, true); // 1,234,567.89

地理位置处理模块

特性

核心方法

方法名 功能描述 调用示例
distance() 计算两点距离 Geo::distance(39.9042, 116.4074, 31.2304, 121.4737)
isValid() 验证坐标 Geo::isValid(39.9042, 116.4074)
bearing() 计算方位角 Geo::bearing(39.9042, 116.4074, 31.2304, 121.4737)
midpoint() 计算中点坐标 Geo::midpoint(39.9042, 116.4074, 31.2304, 121.4737)

使用示例

distance() - 计算两个坐标之间的距离
$distance = Geo::distance(39.9042, 116.4074, 31.2304, 121.4737, 'km'); // 北京到上海的距离,约1067公里
isValid() - 坐标验证
$valid = Geo::isValidCoordinate(39.9042, 116.4074); // true
midpoint() - 计算两个坐标之间的中点
$midpoint = Geo::midpoint(39.9042, 116.4074, 31.2304, 121.4737); // [35.593729492520936,119.07801023725797]
bearing() - 计算两个坐标之间的方位角
$bearing = Geo::bearing(39.9042, 116.4074, 31.2304, 121.4737); // 153.0726752205012
toRadians() - 将角度转换为弧度
$bearing = Geo::toRadians(90); // 1.5707963267948966
toDegrees() - 将弧度转换为角度
$bearing = Geo::toDegrees(1.5707963267948966); // 90
toDMS() - 将十进制度数转换为度分秒(DMS)
$bearing = Geo::toDMS(90, true); // [90,0,0,"N"]
$bearing = Geo::toDMS(90, false); // [90,0,0,"E"]
toDecimal() - 将度分秒(DMS)转换为十进制度数
$bearing = Geo::toDecimal(90,0,0,"N"); // 90
gcj02ToBd09() - GCJ02坐标转BD09坐标
$bd01 = Geo::gcj02ToBd09(39.9042, 116.4074); // [39.9105, 116.4138]
bd09ToGcj02() - BD09坐标转GCJ02坐标
$gcj01 = Geo::bd09ToGcj02(39.9105, 116.4138); // [39.9042, 116.4074]
wgs84ToGcj02() - WGS84坐标转GCJ02坐标(中国火星坐标系)
$gcj02 = Geo::wgs84ToGcj02(39.9042, 116.4074); // [39.9056, 116.4136]
gcj02ToWgs84() - GCJ02坐标转WGS84坐标
$wgs01 = Geo::gcj02ToWgs84(39.9056, 116.4136); // [39.9042, 116.4074]
wgs84ToBd09() - WGS84坐标转BD09坐标
$bd02 = Geo::wgs84ToBd09(39.9042, 116.4074); // [39.9119, 116.4200]
bd09ToWgs84() - BD09坐标转WGS84坐标
$wgs02 = Geo::bd09ToWgs84(39.9119, 116.4200); // [39.9042, 116.4074]

IP地址处理模块

特性

核心方法

方法名 功能描述 调用示例
getLocation() 获取IP地址位置信息 Ip::getLocation(192.168.10.88)
isValid() 验证IP地址格式 Ip::isValid(192.168.10.88)
isPrivate() 检查IP地址是否为私有/内部地址 Ip::isPrivate(192.168.10.88)
getVersion() 获取IP地址版本 Ip::getVersion(192.168.10.88)

使用示例

getRealIp() - 获取真实客户端IP地址
$ip = Ip::getRealIp();
isValid() - 验证IP地址格式是否有效
$valid = Ip::isValid('192.168.1.1'); // true
isPrivate() - 检查IP地址是否为私有/内部地址
$private = Ip::isPrivate('192.168.1.1'); // true
getVersion() - 获取IP地址版本
$ip = Ip::isPrivate();
toLong() - 将IP地址转换为长整数
$long = Ip::toLong('192.168.1.1'); // 3232235777
fromLong() - 将长整数转换为IP地址
$ipStr = Ip::toString(3232235777); // '192.168.1.1'
getLocation() - 获取IP地址位置信息
$local = Ip::getLocation('192.168.1.1');
isFromCountry() - 检查IP地址是否来自特定国家
$ip = Ip::isFromCountry('192.168.1.1', 'CN');
getType() - 获取IP地址类型
$type = Ip::getType('192.168.1.1');

代码生成模块

特性

核心方法

方法名 功能描述 调用示例
uuid() 生成UUID Crypto::uuid()
orderNo() 生成订单号 Crypto::orderNo('')
inviteCode() 生成邀请码 Crypto::inviteCode(6, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789')
urlSafeCode() 生成URL安全码 Crypto::urlSafeCode(16)
registerCode() 生成注册码 Crypto::registerCode(16, 4, '-')

使用示例

uuid() - 生成uuid
$uuid = Generate::uuid();
orderNo() - 生成订单号
// 生成不带前缀的订单号
$orderNo = Generate::orderNo(); // 202512251200001234

// 生成带前缀的订单号
$orderNo = Generate::orderNo('ORD'); // ORD202507261234561234
inviteCode() - 生成邀请码
$inviteCode = Generate::inviteCode(8); // 8位邀请码
urlSafeCode() - 生成URL安全码
$urlSafe = Generate::urlSafeCode(16); // URL安全的随机码
registerCode() - 生成注册码
$registerCode = Generate::registerCode(12, 4); // 12位注册码,每4位分隔

加解密处理模块

特性

核心方法

方法名 功能描述 调用示例
md5() MD5加密(支持加盐) Crypto::md5('123456', 'salt')
passwordHash() 密码哈希 Crypto::passwordHash('123456')
passwordVerify() 密码验证 Crypto::passwordVerify('123456', $hash)
sslEncrypt() SSL对称加密 Crypto::sslEncrypt('data', $key)
sslDecrypt() SSL对称解密 Crypto::sslDecrypt($encrypted, $key)

使用示例

Crypto - 加密引擎说明
use Cdyun\PhpTool\Crypto;

// Sodium引擎 - 推荐使用(性能更高,安全性更强)
// 需要PHP扩展:sodium
$crypto = new Crypto('your_key', Crypto::ENGINE_SODIUM);

// OpenSSL引擎 - 通用选择
// 需要PHP扩展:openssl
$crypto = new Crypto('your_key', Crypto::ENGINE_OPENSSL);

// 自动选择引擎 - 自动选择最优引擎
$crypto = new Crypto('your_key', Crypto::ENGINE_AUTO);
Crypto - 加密模式说明
use Cdyun\PhpTool\Crypto;

// 标准模式 - Base64编码
$crypto = new Crypto('your_key', Crypto::ENGINE_AUTO, Crypto::MODE_STANDARD);
$encrypted = $crypto->encrypt('敏感数据');
// 输出示例: VEhJUz1mYWxzZVZlcnNpb249MS4wJmtleT1zZWN1cmVfazEyMw==

// URL安全模式 - Base64URL编码(无=号,适合URL传输)
$crypto = new Crypto('your_key', Crypto::ENGINE_AUTO, Crypto::MODE_URL_SAFE);
$encrypted = $crypto->encrypt('敏感数据');
// 输出示例: VEhJUz1mYWxzZVZlcnNpb249MS4wJmtleT1zZWN1cmVfazEyMw

// 紧凑模式 - 十六进制编码(最短长度,适合存储)
$crypto = new Crypto('your_key', Crypto::ENGINE_AUTO, Crypto::MODE_COMPACT);
$encrypted = $crypto->encrypt('敏感数据');
// 输出示例: 54484349533b66756c73652076657273696f6e20312e302e303b6b65793d7365637572655f6b313233
Crypto - 基础加解密
use Cdyun\PhpTool\Crypto;

// 创建加密实例
$crypto = new Crypto('your_secret_key_2025');

// 加密数据
$encrypted = $crypto->encrypt('这是需要加密的敏感数据');
echo $encrypted;
// 输出示例: VEhJUz1mYWxzZVZlcnNpb249MS4wJmtleT1zZWN1cmVfazEyMw==

// 解密数据
$decrypted = $crypto->decrypt($encrypted);
echo $decrypted;
// 输出: 这是需要加密的敏感数据

// 使用不同的密钥
$crypto2 = new Crypto('another_key');
$encrypted2 = $crypto2->encrypt('另一个敏感数据');

// 解密(需要使用相同的密钥)
$decrypted2 = $crypto2->decrypt($encrypted2);
Crypto - 静态方法调用
use Cdyun\PhpTool\Crypto;

// 静态加密(使用默认密钥)
$encrypted = Crypto::encrypt('敏感数据');
$decrypted = Crypto::decrypt($encrypted);

// 使用自定义密钥的静态方法
$encrypted = (new Crypto('custom_key'))->encrypt('敏感数据');
$decrypted = (new Crypto('custom_key'))->decrypt($encrypted);
md5() - MD5加密(支持加盐)
// 基础MD5加密
$md5 = Crypto::md5('123456'); // e10adc3949ba59abbe56e057f20f883e

// 加盐MD5加密
$salt = 'your_custom_salt';
$md5WithSalt = Crypto::md5('123456', $salt); // 52c69e3a57331081823331c4e6999d23

// 多次加盐(提高安全性)
$doubleSalt = Crypto::md5(Crypto::md5('123456'), $salt);
passwordHash() - 密码哈希
$password = 'my_secure_password';
$hash = Crypto::passwordHash($password);
passwordVerify() - 密码哈希验证
// 密码正确
$isValid = Crypto::passwordVerify('my_secure_password', $hash);

// 密码错误
$isValid = Crypto::passwordVerify('wrong_password', $hash);

// 密码哈希更新(重新哈希)
if (password_needs_rehash($hash, PASSWORD_DEFAULT)) {
    $newHash = Crypto::passwordHash($password);
}
Crypto - HMAC签名
use Cdyun\PhpTool\Crypto\Crypto;

// SHA256签名(默认)
$signature = Crypto::hmac('待签名数据', 'your_secret_key');
echo $signature;
// 输出示例: 3a6eb0790f39ac87c94f3856b2dd2c5d110e0f9b0e9c9d6e7b8c9d0e1f2a3b4c

// SHA512签名
$signature512 = Crypto::hmac('待签名数据', 'your_secret_key', 'sha512');
echo $signature512;
// 输出示例: a4e6b8c0d1e2f3a4b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1c2

// MD5签名
$signatureMd5 = Crypto::hmac('待签名数据', 'your_secret_key', 'md5');
echo $signatureMd5;
// 输出示例: 1a1dc06f7a0b2c8d9e0f1a2b3c4d5e6f7

// 数据完整性验证
$originalData = '订单数据';
$originalSignature = Crypto::hmac($originalData, 'api_secret');

$receivedData = '订单数据';
$receivedSignature = $_SERVER['HTTP_SIGNATURE'] ?? '';

if (hash_equals($originalSignature, $receivedSignature)) {
    echo '数据完整性验证通过';
} else {
    echo '数据可能被篡改';
}
Crypto - SSL对称加解密
use Cdyun\PhpTool\Crypto;

// 使用自定义密钥进行SSL加密
$key = 'your_ssl_key_32_bytes_long!';
$crypto = new Crypto();

$encrypted = $crypto->sslEncrypt('SSL加密数据', $key);
echo $encrypted;
// 输出示例: VGhpc0lzU1NMY0VuY3J5cHRlZERhdGE=

$decrypted = $crypto->sslDecrypt($encrypted, $key);
echo $decrypted;
// 输出: SSL加密数据
Crypto - 错误处理
use Cdyun\PhpTool\Crypto;

$crypto = new Crypto('your_key');

try {
    $encrypted = $crypto->encrypt('敏感数据');
    $decrypted = $crypto->decrypt($encrypted);
    echo '加解密成功: ' . $decrypted;
} catch (\Exception $e) {
    echo '加解密失败: ' . $e->getMessage();
}

// 密钥错误时的解密异常
try {
    $wrongCrypto = new Crypto('wrong_key');
    $decrypted = $wrongCrypto->decrypt($encrypted);
} catch (\Exception $e) {
    echo '解密失败(密钥错误): ' . $e->getMessage();
}

使用场景

use Cdyun\PhpTool\Crypto;

// 场景1:用户敏感信息加密存储
function saveUserSensitiveData(Crypto $crypto, array $data): array
{
    return [
        'id' => $data['id'],
        'name' => $data['name'],
        'encrypted_phone' => $crypto->encrypt($data['phone']),
        'encrypted_id_card' => $crypto->encrypt($data['id_card'])
    ];
}

function getUserSensitiveData(Crypto $crypto, array $userData): array
{
    return [
        'id' => $userData['id'],
        'name' => $userData['name'],
        'phone' => $crypto->decrypt($userData['encrypted_phone']),
        'id_card' => $crypto->decrypt($userData['encrypted_id_card'])
    ];
}

// 场景2:API请求签名验证
function verifyApiRequest(Crypto $crypto, array $params, string $signature): bool
{
    $expectedSignature = Crypto::hmac(json_encode($params), $apiSecret);
    return hash_equals($expectedSignature, $signature);
}

// 场景3:密码安全存储
function registerUser(string $password): string
{
    return Crypto::passwordHash($password);
}

function verifyUserPassword(string $password, string $hash): bool
{
    return Crypto::passwordVerify($password, $hash);
}

HTTP请求处理模块

特性

核心方法

方法名 功能描述 调用示例
get() GET请求 Curl::get('https://api.example.com', $data)
post() POST请求 Curl::post('https://api.example.com', $data)
put() PUT请求 Curl::put('https://api.example.com/1', $data)
delete() DELETE请求 Curl::delete('https://api.example.com/1')
head() HEAD请求 Curl::head('https://api.example.com')
options() OPTIONS请求 Curl::options('https://api.example.com')

使用示例

setDefaultOptions() - 设置默认配置
Curl::setDefaultOptions([
        'timeout' => 60,
        'connect_timeout' => 20,
    ])
getDefaultOptions() - 获取默认配置
Curl::getDefaultOptions()
// 返回默认配置
//  [
//        'timeout' => 60,
//        'connect_timeout' => 20,
//        'verify' => true,
//  ]
reset() - 重置客户端实例
Curl::reset()
options() - OPTIONS请求
$response = Curl::options('https://api.example.com', [], []);
head() - HEAD请求
$response = Curl::head('https://api.example.com', [], [], []);
get() - GET请求
$response = Curl::get('https://api.example.com', [], [], []);

$response = Curl::get('https://api.example.com/users', ['page' => 1, 'limit' => 10]);
post() - POST请求
$response = Curl::post('https://api.example.com', [], [], []);

$response = Curl::post('https://api.example.com', ['name' => 'John', 'email' => '[email protected]']);
postForm() - POST表单请求
$response = Curl::postForm('https://api.example.com', [], [], []);

$response = Curl::postForm('https://api.example.com', ['name' => 'John', 'email' => '[email protected]']);
postMultipart() - POST文件上传请求
$response = Curl::postMultipart(
    'https://api.example.com/upload', 
    [
        ['name' => 'file', 'contents' => fopen('/path/to/file.jpg', 'r')]
    ]
);
put() - PUT请求
$response = Curl::put('https://api.example.com/users/1', [], [], []);

$response = Curl::put('https://api.example.com/users/1', ['name' => 'Updated Name']);
putForm() - PUT表单请求
$response = Curl::put('https://api.example.com/users/1', [], [], []);

$response = Curl::put('https://api.example.com/users/1', ['name' => 'Updated Name']);
delete() - PUT请求
$response = Curl::delete('https://api.example.com/users/1', [], [], []);

$response = Curl::delete('https://api.example.com/users/1');
patch() - PATCH请求
$response = Curl::patch('https://api.example.com/users/1', [], [], []);

$response = Curl::patch('https://api.example.com/users/1', [
    'status' => 'active'
]);

目录文件处理

使用示例

scanFolder() - 搜索指定路径下的【直系】文件夹
$list = Dir::scanFolder($path);
getFileContent() - 获取文件内容
$content = Dir::getFileContent($path, $fileName);
listFileContent() - 获取指定路径文件夹下所有直系文件夹中所有指定文件名的php文件内容
$list = Dir::listFileContent($path, $fileName);
deleteDirFile() - 清除指定文件夹下文件
$list = Dir::deleteDirFile($dir_name);
scanFile() - 搜索文件夹下全部文件,指定扩展名,暂时不支持中文文件名
$list = Dir::scanFile($path, $ext);
scanFileTree() - 搜索文件夹下全部文件返回树形结构,指定扩展名,暂时不支持中文文件名
$list = Dir::scanFileTree($path, $prefix, $ext);

版本要求

许可证

MIT License


All versions of php-tool with dependencies

PHP Build Version
Package Version
Requires php Version >=8.1
ext-openssl Version *
ext-json Version *
ext-mbstring Version *
ext-gd Version *
ext-sodium Version *
guzzlehttp/guzzle Version ^7.9
Composer command for our command line client (download client) This client runs in each environment. You don't need a specific PHP version etc. The first 20 API calls are free. Standard composer command

The package cdyun/php-tool contains the following files

Loading the files please wait ...