1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Yiisoft\NetworkUtilities; |
6
|
|
|
|
7
|
|
|
use RuntimeException; |
8
|
|
|
|
9
|
|
|
/** |
10
|
|
|
* DnsHelper contains static methods to work with DNS. |
11
|
|
|
*/ |
12
|
|
|
final class DnsHelper |
13
|
|
|
{ |
14
|
|
|
/** |
15
|
|
|
* Checks DNS MX record availability. |
16
|
|
|
* |
17
|
|
|
* @param string $hostname Hostname without dot at end. |
18
|
|
|
* |
19
|
|
|
* @return bool Whether MX record exists. |
20
|
|
|
*/ |
21
|
3 |
|
public static function existsMx(string $hostname): bool |
22
|
|
|
{ |
23
|
3 |
|
set_error_handler(static function (int $errorNumber, string $errorString) use ($hostname): bool { |
24
|
1 |
|
throw new RuntimeException( |
25
|
1 |
|
sprintf('Failed to get DNS record "%s". ', $hostname) . $errorString, |
26
|
1 |
|
$errorNumber |
27
|
1 |
|
); |
28
|
3 |
|
}); |
29
|
|
|
|
30
|
3 |
|
$hostname = rtrim($hostname, '.') . '.'; |
31
|
3 |
|
$result = dns_get_record($hostname, DNS_MX); |
32
|
|
|
|
33
|
2 |
|
restore_error_handler(); |
34
|
|
|
|
35
|
2 |
|
return count($result) > 0; |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
/** |
39
|
|
|
* Checks DNS A record availability. |
40
|
|
|
* |
41
|
|
|
* @param string $hostname Hostname without dot at end. |
42
|
|
|
* |
43
|
|
|
* @return bool Whether A records exists. |
44
|
|
|
*/ |
45
|
3 |
|
public static function existsA(string $hostname): bool |
46
|
|
|
{ |
47
|
3 |
|
set_error_handler(static function (int $errorNumber, string $errorString) use ($hostname): bool { |
48
|
1 |
|
throw new RuntimeException( |
49
|
1 |
|
sprintf('Failed to get DNS record "%s". ', $hostname) . $errorString, |
50
|
1 |
|
$errorNumber |
51
|
1 |
|
); |
52
|
3 |
|
}); |
53
|
|
|
|
54
|
3 |
|
$result = dns_get_record($hostname, DNS_A); |
55
|
|
|
|
56
|
2 |
|
restore_error_handler(); |
57
|
|
|
|
58
|
2 |
|
return count($result) > 0; |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
/** |
62
|
|
|
* Checks email's domain availability. |
63
|
|
|
* |
64
|
|
|
* @link https://tools.ietf.org/html/rfc5321#section-5 |
65
|
|
|
* |
66
|
|
|
* @param string $hostnameOrEmail Hostname without dot at end or an email. |
67
|
|
|
* |
68
|
|
|
* @return bool Whether email domain is available. |
69
|
|
|
*/ |
70
|
1 |
|
public static function acceptsEmails(string $hostnameOrEmail): bool |
71
|
|
|
{ |
72
|
1 |
|
if (strpos($hostnameOrEmail, '@') !== false) { |
73
|
1 |
|
[, $hostnameOrEmail] = explode('@', $hostnameOrEmail, 2); |
74
|
|
|
} |
75
|
1 |
|
return self::existsMx($hostnameOrEmail) || self::existsA($hostnameOrEmail); |
76
|
|
|
} |
77
|
|
|
} |
78
|
|
|
|