PHP 系列 (一)

浮点数计算不准确|保留两位小数不四舍五入

1
2
3
4
5
6
7
8
9
// 结果 float(0.099999999999998) 
var_dump(19.45 - 19.35);

// 设置所有bc数学函数的小数点保留位数
bcscale(2);
var_dump(bcsub(19.45, 19.35));

// 保留两位小数,不四舍五入
var_dump(bcsub(1.339, 0, 2));

DateTime 获取当前时间, 以微秒为单位

1
2
3
4
5
// 输出当前时间, 以微秒为单位, 若直接将 $timeZone 作为 createFromFormat 的第三个参数是无效的, 问题是 microtime() 和 time()  返回的是当前时区的时间戳
// 参考 http://php.net/manual/zh/datetime.createfromformat.php#120552
$timeZone = new DateTimeZone(date_default_timezone_get() ? : 'Asia/Shanghai');
$ds = DateTime::createFromFormat('U.u', microtime(true))->setTimezone($timeZone);
var_dump($ds->format('Y-m-d H:i:s.u'));

删除不可见字符与BOM头

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// 删除ASCII码 0-31,127-255 字符
$string = preg_replace('/[\x00-\x1F\x7F-\xFF]/', '', $string);

// 删除ASCII码 0-31,127 字符
$string = preg_replace('/[\x00-\x1F\x7F]/', '', $string);

// 删除BOM,BOM的ASCII码为 239,187,191
$string = trim($string, "\xEF\xBB\xBF");

// IOS提交的不可见字符
$string = "‭1234567890‬";
var_dump(json_encode([$string]));
$string = preg_replace('/[\x7F-\xFF]/', '', $string);
var_dump(json_encode([$string]));

cURL 自定义 HEADER 参数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<?php
$method = strtoupper($_SERVER['REQUEST_METHOD']);
if ($method == 'POST') {
$postData = $_POST;
$headers = [];
$paramsArray = ['USERID', 'RANDOM'];
foreach ($paramsArray as $param) {
$headers[$param] = $_SERVER['HTTP_' . $param];
}

header('content-type:application/json;charset=utf8');
die(json_encode([$postData, $headers]));
} else {
$url = 'http://localhost:8080/index.php';
$header = ['USERID:1', 'RANDOM:' . mt_rand(1, 1000)];
$content = ['name' => 'test'];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($content));
$response = curl_exec($ch);
curl_close($ch);
var_dump($response);
}

二维数组指定字段排序

1
2
3
4
5
6
7
8
9
<?php
$array = [
['name' => 't1', 'val' => 1],
['name' => 't3', 'val' => 3],
['name' => 't2', 'val' => 2],
];
array_multisort($array, array_column($array, 'val'));
//array_multisort(array_column($array, 'val'), SORT_ASC, $array);
var_dump($array);

图片转换数据流

1
2
3
4
5
6
7
8
9
<?php
$imgPath = './1.jpg';
if (file_exists($imgPath)) {
$img = base64_encode(file_get_contents($imgPath));
$img = 'data:image/jpg;base64,' . $img;
} else {
$img = 'data:image/jpg;base64,/9j/4AAQSkZJRgABAQEASABIAAD/4QAiRXhpZgAATU0AKgAAAAgAAQESAAMAAAABAAEAAAAAAAD/2wBDAAIBAQIBAQICAgICAgICAwUDAwMDAwYEBAMFBwYHBwcGBwcICQsJCAgKCAcHCg0KCgsMDAwMBwkODw0MDgsMDAz/2wBDAQICAgMDAwYDAwYMCAcIDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAz/wAARCAAkADIDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgc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d/wARPjF4Es21jULFtQ1Sz020XUo7UG+tVmW9VnEz7mlkCwqBJcea2WYkljuBRXZltSapVLN7P8jTEQjO3Mr+8lr2ujovFvwy01fiZqHi3U2vvEXiDVNOj0Ke41W6e4gWzSUhYY7XItokBO7bHEq7stjc7lvYvCv7OfgrS9LOpXHh3S9Wv7hBum1C3S42rwAqqRtVQMDCgdBRRXmKTlK8tf8AhjPEScYWjpqPl8L6BbyNHH4W8KrHGSqqNHt8ADoPu0UUVtZHHzy7n//Z';
}
echo "<img src='{$img}' />";

HEADER 介绍

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
<?php
header('HTTP/1.1 200 OK'); // ok 正常访问
header('HTTP/1.1 404 Not Found'); // 通知浏览器 页面不存在
header('HTTP/1.1 301 Moved Permanently'); // 设置地址被永久的重定向 301
header('Location: http://www.ruonu.com/'); // 跳转到一个新的地址
header('Refresh: 10; url=http://www.ruonu.com/'); // 延迟转向 也就是隔几秒跳转
header('X-Powered-By: PHP/6.0.0'); // 修改 X-Powered-By信息
header('Content-language: en'); // 文档语言
header('Content-Length: 1234'); // 设置内容长度
header('Last-Modified: ' . gmdate('D, d M Y H:i:s', $time) . ' GMT'); // 告诉浏览器最后一次修改时间
header('HTTP/1.1 304 Not Modified'); // 告诉浏览器文档内容没有发生改变

###内容类型###
header('Content-Type: text/html; charset=utf-8'); // 网页编码
header('Content-Type: text/plain'); // 纯文本格式
header('Content-Type: image/jpeg'); // JPG、JPEG
header('Content-Type: application/zip'); // ZIP文件
header('Content-Type: application/pdf'); // PDF文件
header('Content-Type: audio/mpeg'); // 音频文件
header('Content-type: text/css'); // css文件
header('Content-type: text/javascript'); // js文件
header('Content-type: application/json'); // json
header('Content-type: application/pdf'); // pdf
header('Content-type: text/xml'); // xml
header('Content-Type: application/x-shockw**e-flash'); // Flash动画
header('Content-Type: application/octet-stream'); // .*( 二进制流, 不知道下载文件类型)
######

###声明一个下载的文件###
header('Content-Description:File'); // 描述
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="ITblog.zip"');
header('Content-Transfer-Encoding: binary');
readfile('test.zip');
######

###对当前文档禁用缓存###
header('Cache-Control: no-cache, no-store, max-age=0, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
######

###显示一个需要验证的登陆对话框###
header('HTTP/1.1 401 Unauthorized');
header('WWW-Authenticate: Basic realm="Top Secret"');
######


###声明一个需要下载的xls文件###
header('Content-Disposition: attachment; filename=ithhc.xlsx');
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Length: '.filesize('./test.xls'));
header('Content-Transfer-Encoding: binary');
header('Cache-Control: must-revalidate');
header('Pragma: public');
readfile('./test.xls');
######
0%