PHP code example of kode / tools
1. Go to this page and download the library: Download kode/tools library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
kode / tools example snippets
use Kode\Message\Message;
// 默认200,msg="成功"
Message::result();
// 结果: ['code' => 200, 'msg' => '成功']
// 指定状态码和消息
Message::code(20001)->msg('请求数据有误')->result();
// 结果: ['code' => 20001, 'msg' => '请求数据有误']
// 传入data数据(无data不显示data字段)
Message::data(['id' => 1])->result();
// 结果: ['code' => 200, 'msg' => '成功', 'data' => ['id' => 1]]
// 链式调用位置不约束
Message::data(['id' => 1])->code(20001)->msg('请求数据有误')->result();
// 结果: ['code' => 20001, 'msg' => '请求数据有误', 'data' => ['id' => 1]]
// 动态添加任意字段
Message::data(['id' => 1])->page(1)->name('张三')->result();
// 结果: ['code' => 200, 'msg' => '成功', 'data' => ['id' => 1], 'page' => 1, 'name' => '张三']
// HTTP标准码
200 => 'OK', 400 => 'Bad Request', 401 => 'Unauthorized',
403 => 'Forbidden', 404 => 'Not Found', 500 => 'Internal Server Error'
// 业务码
300000 => 'Token无效', 300001 => 'Token已过期',
400000 => '参数错误', 500000 => '数据库错误'
use Kode\Crypto\Crypto;
// AES加密解密(密钥至少16字符)
$crypto = new Crypto('mykey1234567890ab'); // 17字符密钥
$encrypted = $crypto->encrypt('敏感数据');
// 加密结果: JeB6LDA+LM9Yu87injOYd0ToSPfb4f/XBcEv7/qI6TWDczdBd3...
$decrypted = $crypto->decrypt($encrypted);
// 解密结果: 敏感数据
// 特殊字符/中文/emoji完全支持
$crypto->encrypt('你好世界 🌍');
// 加密结果: DKJaDjUoVt8mHZHlNba/XKk1pRY9dYV23kR2FTPkhnq69Er2OP...
// MD5哈希(加盐)
Crypto::md5('123456', 'salt');
// 结果: 2e4475e67a7d80f8c1e5c3f5e5c3a8f5
// 密码哈希
$hash = Crypto::passwordHash('123456');
// 结果: $2y$10$LQv3c1yqBwe...(随机哈希)
Crypto::passwordVerify('123456', $hash);
// 结果: true
// UUID/Token生成
Crypto::uuid();
// 结果: 58d1b3c9-5ec4-4356-8007-e7ec469d1dae
Crypto::token(32);
// 结果: 89eb2398743a88f5fdcf33c727242a3d
// HMAC签名
Crypto::hmac('数据', '密钥', 'sha256');
// 结果: 3d5f8e2b1a9c4d7e6f8a3b2c1d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f
use Kode\Crypto\Crypto;
// 创建URL安全加密实例
$crypto = new Crypto('your_secret_key_16chars');
$crypto->mode(Crypto::MODE_URL_SAFE);
// 加密数据
$original = '{"user_id":123,"token":"jwt..."}';
$encrypted = $crypto->encrypt($original);
// 加密结果: r50Mzv6rf1t5q6AJvQt5Pc-Zqy5ykcrgX8jSEgGi...
// 构建URL
$url = 'https://api.example.com/user?' . http_build_query(['data' => $encrypted]);
// 服务器端解密
$received = $_GET['data'] ?? $encrypted;
$decrypted = $crypto->decrypt($received);
// 解密结果: {"user_id":123,"token":"jwt..."}
use Kode\String\Str;
// XSS攻击示例
$attacks = [
'<script>alert("XSS")</script>',
'javascript:alert("XSS")',
'<img src=x onerror=alert("XSS")>',
];
// 防护处理
foreach ($attacks as $input) {
$safe = Str::xssSafe($input);
echo $safe;
// 输出: <script>alert("XSS")</script>
}
use Kode\String\Str;
$userInput = "'; DROP TABLE users; --";
$safe = Str::sqlSafe($userInput);
// 输出: \'\'; DROP TABLE users; --
// 严格模式(去除所有非字母数字字符)
$strict = Str::sqlSafe($userInput, true);
// 输出: DROPTABLEUSERS
use Kode\String\Str;
$html = '<div class="test">Hello & "World"</div>';
$escaped = Str::htmlEscape($html);
// 输出: <div class="test">Hello & "World"</div>
use Kode\Curl\Curl;
// GET请求
$response = Curl::get('https://api.example.com/users', ['page' => 1])
->timeout(30)
->headers(['Authorization' => 'Bearer xxx'])
->send();
// 响应: Response对象,可调用 $response->json() 获取数据
// POST请求
$response = Curl::post('https://api.example.com/users', ['name' => '张三'])
->withJson(['name' => '张三'])
->send();
// 响应: Response对象
// 链式调用
$response = Curl::create('https://api.example.com/users')
->method('POST')
->withJson(['name' => '张三'])
->authorization('Bearer xxx')
->send();
// 响应: Response对象
// Promise风格
$result = Curl::get('https://api.example.com/users')
->then(fn($response) => $response->json())
->catch(fn($response) => $response->getErrorMessage());
// 成功: 返回JSON数据
// 失败: 返回错误消息
use Kode\Array\Arr;
// 数组转树形
$tree = Arr::tree([
['id' => 1, 'parent_id' => 0, 'name' => 'A'],
['id' => 2, 'parent_id' => 1, 'name' => 'B'],
['id' => 3, 'parent_id' => 1, 'name' => 'C'],
], 'id', 'parent_id');
// 结果: [['id' => 1, 'parent_id' => 0, 'name' => 'A', 'children' => [...]]]
// 获取首尾元素
Arr::first([1, 2, 3]);
// 结果: 1
Arr::last([1, 2, 3]);
// 结果: 3
// 查找元素
Arr::find([1, 2, 3], fn($n) => $n > 1);
// 结果: 2
// 深度合并
Arr::deepMerge(['a' => 1], ['a' => 2, 'b' => 3]);
// 结果: ['a' => 2, 'b' => 3]
use Kode\String\Str;
// 脱敏
Str::maskPhone('13800138000');
// 结果: 138****8000
Str::maskEmail('[email protected] ');
// 结果: us**@example.com
// 命名转换
Str::camel('hello_world');
// 结果: helloWorld
Str::snake('helloWorld');
// 结果: hello_world
Str::studly('hello_world');
// 结果: HelloWorld
// Base64
Str::toBase64('hello');
// 结果: aGVsbG8=
Str::fromBase64('aGVsbG8=');
// 结果: hello
// UUID
Str::uuid();
// 结果: a24e88d8-b560-4196-a34b-63626c1e489d
// 验证
Str::validatePhone('13800138000');
// 结果: true
Str::validateEmail('[email protected] ');
// 结果: true
Str::validateIdCard('110101199001011234');
// 结果: true
use Kode\Time\Time;
// 获取当前时间
Time::now();
// 结果: 2026-04-01 12:00:00
Time::today();
// 结果: 2026-04-01
Time::yesterday();
// 结果: 2026-03-31
Time::tomorrow();
// 结果: 2026-04-02
// 人性化显示
Time::diffForHumans('2024-01-01');
// 结果: 2年前
// 日期范围
Time::weekStart();
// 结果: 2026-03-30
Time::weekEnd();
// 结果: 2026-04-05
Time::monthStart();
// 结果: 2026-04-01
Time::monthEnd();
// 结果: 2026-04-30
// 时间戳操作
Time::add(time(), 86400);
// 结果: 明天的时间戳
Time::sub(time(), 3600);
// 结果: 一小时前的时间戳
use Kode\Math\Math;
// 高精度计算
Math::add('1.1', '2.2');
// 结果: 3.3000000000
Math::sub('5.5', '3.3');
// 结果: 2.2000000000
Math::mul('1.5', '2.5');
// 结果: 3.7500000000
Math::div('10', '3');
// 结果: 3.3333333333
// 折扣计算
Math::discount('100', '0.8');
// 结果: 80
// 税费计算
Math::tax('100', '0.13');
// 结果: 13
// 统计
Math::average([1, 2, 3, 4, 5]);
// 结果: 3
Math::median([1, 2, 3, 4, 5]);
// 结果: 3
Math::mode([1, 2, 2, 3]);
// 结果: 2
Math::standardDeviation([1, 2, 3, 4, 5]);
// 结果: 1.4142135624
use Kode\Geo\Geo;
// 两点距离(默认公里)
$distance = Geo::distance(39.9042, 116.4074, 31.2304, 121.4737);
// 结果: 1068.51
// 两点距离(米)
$distanceM = Geo::distance(39.9042, 116.4074, 31.2304, 121.4737, 'm');
// 结果: 1068506.82
// 坐标验证
Geo::isValid(39.9042, 116.4074);
// 结果: true
// 方位角
Geo::bearing(39.9042, 116.4074, 31.2304, 121.4737);
// 结果: -141.67
use Kode\Ip\Ip;
// IP验证
Ip::isValid('192.168.1.1');
// 结果: true
// 私有IP判断
Ip::isPrivate('192.168.1.1');
// 结果: true
Ip::isPublic('8.8.8.8');
// 结果: true
// 获取客户端IP
Ip::get();
// 结果: 127.0.0.1
Ip::getRealIp();
// 结果: 真实IP
// IP类型
Ip::getType('192.168.1.1');
// 结果: private
Ip::getType('8.8.8.8');
// 结果: public
// IP转长整数
Ip::toLong('192.168.1.1');
// 结果: 3232235777
Ip::fromLong(3232235777);
// 结果: 192.168.1.1
use Kode\Qrcode\Qr;
// 生成二维码图片
$qr = Qr::text('https://example.com')
->size(300)
->margin(10)
->generate();
// 保存到文件
Qr::text('https://example.com')
->save('qrcode.png');
// 生成Base64
$base64 = Qr::text('https://example.com')
->base64();
// 数组函数
arr_first([1, 2, 3]);
// 结果: 1
arr_last([1, 2, 3]);
// 结果: 3
arr_find([1, 2, 3], fn($n) => $n > 1);
// 结果: 2
arr_random([1, 2, 3]);
// 结果: 随机一个元素
arr_deep_merge(['a' => 1], ['b' => 2]);
// 结果: ['a' => 1, 'b' => 2]
arr_multi_sort($array, ['created_at'], ['desc']);
// 结果: 排序后的数组
// 字符串函数
str_mask_phone('13800138000');
// 结果: 138****8000
str_mask_email('[email protected] ');
// 结果: us***@example.com
str_mask_id_card('110101199001011234');
// 结果: 110101********1234
str_to_base64('hello');
// 结果: aGVsbG8=
str_from_base64('aGVsbG8=');
// 结果: hello
str_truncate('abcdefghijk', 5);
// 结果: abcde...
str_camel('hello_world');
// 结果: helloWorld
str_snake('helloWorld');
// 结果: hello_world
str_starts_with('hello', 'he');
// 结果: true
str_ends_with('hello', 'lo');
// 结果: true
str_contains('hello world', 'world');
// 结果: true
str_uuid();
// 结果: 50f53907-b0e9-4c5c-9b67-8ec6aa888c5e
// 时间函数
time_now();
// 结果: 2026-04-01 08:40:15
time_today();
// 结果: 2026-04-01
time_yesterday();
// 结果: 2026-03-31
time_tomorrow();
// 结果: 2026-04-02
time_diff_for_humans('2024-01-01');
// 结果: 2年前
// 数学函数
math_add('1.1', '2.2');
// 结果: 3.3000000000
math_sub('5.5', '3.3');
// 结果: 2.2000000000
math_mul('1.5', '2.5');
// 结果: 3.7500000000
math_div('10', '3');
// 结果: 3.3333333333
math_discount('100', '0.8');
// 结果: 80
math_tax('100', '0.13');
// 结果: 13
math_average([1, 2, 3, 4, 5]);
// 结果: 3
math_median([1, 2, 3, 4, 5]);
// 结果: 3
// 地理位置函数
geo_distance(39.9042, 116.4074, 31.2304, 121.4737);
// 结果: 1068.5058062575(北京到上海距离,单位:公里)
geo_distance(39.9042, 116.4074, 31.2304, 121.4737, 'm');
// 结果: 1068505.8062575(单位:米)
geo_is_valid(39.9042, 116.4074);
// 结果: true
// IP函数
ip_get();
// 结果: 127.0.0.1(客户端IP)
ip_get_real();
// 结果: 真实客户端IP(支持代理)
ip_is_valid('192.168.1.1');
// 结果: true
ip_is_private('192.168.1.1');
// 结果: true
ip_is_public('8.8.8.8');
// 结果: true
// HTTP请求函数
curl_get('https://api.example.com/users', ['page' => 1]);
// 结果: Response对象
curl_post('https://api.example.com/users', ['name' => '张三']);
// 结果: Response对象
// 二维码函数
qr_text('https://example.com')->save('qrcode.png');
// 结果: 保存二维码图片
qr_wifi('MyWiFi', 'password123')->base64();
// 结果: Base64编码的二维码
// 辅助函数
uuid();
// 结果: 06c32c05-c0e8-4e9e-b80f-3919404f923c
random_string(16);
// 结果: xK7d9f2mAb3cL5nP