ImapClient.php
2.7 KB
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
<?php
namespace Lib\Imap;
class ImapClient {
/**
* 资源
* @var
*/
private $socket;
protected bool $debug = false;
protected string $host;
/**
* 每请求一次就会+1
* @var int
*/
public int $tagNum = 0;
public function __construct(string $host){
$this->host = $host;
}
public function open(){
$content = stream_context_create([
'ssl' => [
'verify_peer' => false, // 有的证书和域名不匹配,这里关闭认证
'verify_peer_name' => false,// 有的证书和域名不匹配,这里关闭认证
]
]);
$flags = STREAM_CLIENT_CONNECT;
$this->socket = stream_socket_client(
$this->host,
$errno,
$error,
30,
$flags,
$content
);
if($error){
throw new \Exception($error);
}
if (!$this->socket) {
throw new \Exception($this->host." connection fail.");
}
}
/**
* @param bool $debug
* @return $this
* @author:dc
* @time 2024/9/18 9:57
*/
public function setDebug(bool $debug = true): static
{
$this->debug = $debug;
return $this;
}
/**
* 写
* @param string $cmd
* @return false|int
* @author:dc
* @time 2024/9/13 15:47
*/
protected function write(string $cmd){
if($this->debug){
echo 'write: '.$cmd;
}
return fwrite($this->socket,$cmd);
}
/**
* 读
* @return false|string
* @author:dc
* @time 2024/9/13 15:49
*/
protected function readLine(){
$str = fgets($this->socket,2048);
if($this->debug){
echo 'read: '.$str;
}
return $str;
}
/**
*
* @param string $cmd 执行的命令
* @return array
* @author:dc
* @time 2024/9/13 15:57
*/
public function request(string $cmd):array {
$this->tagNum++;
$tag = 'TAG'.$this->tagNum;
// 请求数据
$writeNumber = $this->write($tag.' '.$cmd."\r\n");
$result = [];
if($writeNumber){
// 读取数据
while (1){
$line = $this->readLine();
$result[] = $line;
list($token) = explode(' ',$line,2);
// 结束了
if($token == $tag || $line === false){
break;
}
}
}
return $result;
}
public function __destruct()
{
unset($this->socket);
// TODO: Implement __destruct() method.
}
}