|
1
|
|
|
<?php |
|
2
|
|
|
/** |
|
3
|
|
|
* Class Base64 |
|
4
|
|
|
* @link https://www.icy2003.com/ |
|
5
|
|
|
* @author icy2003 <[email protected]> |
|
6
|
|
|
* @copyright Copyright (c) 2017, icy2003 |
|
7
|
|
|
*/ |
|
8
|
|
|
|
|
9
|
|
|
namespace icy2003\php\ihelpers; |
|
10
|
|
|
|
|
11
|
|
|
use icy2003\php\icomponents\file\LocalFile; |
|
12
|
|
|
|
|
13
|
|
|
/** |
|
14
|
|
|
* Base64 相关 |
|
15
|
|
|
*/ |
|
16
|
|
|
class Base64 |
|
17
|
|
|
{ |
|
18
|
|
|
|
|
19
|
|
|
/** |
|
20
|
|
|
* 判断字符串是否是 base64 字符串 |
|
21
|
|
|
* |
|
22
|
|
|
* @param string $string |
|
23
|
|
|
* |
|
24
|
|
|
* @return boolean |
|
25
|
|
|
* |
|
26
|
|
|
* @test icy2003\php\tests\ihelpers\Base64Test::testIsBase64 |
|
27
|
|
|
*/ |
|
28
|
2 |
|
public static function isBase64($string) |
|
29
|
|
|
{ |
|
30
|
2 |
|
return $string == base64_encode(base64_decode($string)); |
|
31
|
|
|
} |
|
32
|
|
|
|
|
33
|
|
|
/** |
|
34
|
|
|
* base64 编码 |
|
35
|
|
|
* |
|
36
|
|
|
* @param string $string 字符串 |
|
37
|
|
|
* |
|
38
|
|
|
* @return string |
|
39
|
|
|
*/ |
|
40
|
1 |
|
public static function encode($string) |
|
41
|
|
|
{ |
|
42
|
1 |
|
return base64_encode($string); |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
|
|
/** |
|
46
|
|
|
* base64 解码 |
|
47
|
|
|
* |
|
48
|
|
|
* - 如果给的不是 base64 字符串,则返回 false |
|
49
|
|
|
* |
|
50
|
|
|
* @param string $string base64 字符串 |
|
51
|
|
|
* |
|
52
|
|
|
* @return string|boolean |
|
53
|
|
|
*/ |
|
54
|
1 |
|
public static function decode($string) |
|
55
|
|
|
{ |
|
56
|
1 |
|
return self::isBase64($string) ? base64_decode($string) : false; |
|
57
|
|
|
} |
|
58
|
|
|
|
|
59
|
|
|
/** |
|
60
|
|
|
* 文件转成 base64 字符串 |
|
61
|
|
|
* |
|
62
|
|
|
* @param string $file 文件路径 |
|
63
|
|
|
* |
|
64
|
|
|
* @return string|boolean |
|
65
|
|
|
* |
|
66
|
|
|
* @test icy2003\php\tests\ihelpers\Base64Test::testFromFile |
|
67
|
|
|
*/ |
|
68
|
1 |
|
public static function fromFile($file) |
|
69
|
|
|
{ |
|
70
|
1 |
|
$base64 = false; |
|
71
|
1 |
|
$local = new LocalFile(); |
|
72
|
1 |
|
$local->isFile($file) && $base64 = base64_encode($local->getFileContent($file)); |
|
73
|
1 |
|
return $base64; |
|
74
|
|
|
} |
|
75
|
|
|
|
|
76
|
|
|
/** |
|
77
|
|
|
* base64 字符串转成文件 |
|
78
|
|
|
* |
|
79
|
|
|
* @param string $string base64 字符串 |
|
80
|
|
|
* @param string $file 文件路径 |
|
81
|
|
|
* |
|
82
|
|
|
* @return boolean |
|
83
|
|
|
* |
|
84
|
|
|
* @test icy2003\php\tests\ihelpers\Base64Test::testToFile |
|
85
|
|
|
*/ |
|
86
|
1 |
|
public static function toFile($string, $file = null) |
|
87
|
|
|
{ |
|
88
|
1 |
|
null === $file && $file = './Base64_toFile_' . date('YmdHis') . '.txt'; |
|
89
|
1 |
|
return (bool) file_put_contents($file, base64_decode($string)); |
|
90
|
|
|
} |
|
91
|
|
|
} |
|
92
|
|
|
|