Php 如何检查主机是否在线?
当我尝试连接到脱机或不存在的主机时,会出现异常:Php 如何检查主机是否在线?,php,laravel,guzzlehttp,Php,Laravel,Guzzlehttp,当我尝试连接到脱机或不存在的主机时,会出现异常: cURL error 6: Could not resolve host: somedomain.com 那你怎么用这些东西呢?() 我需要知道主机是否在线/离线 编辑: 这对我不起作用,我总是得到:cURL错误6:无法解析主机:somedomain.comGuzzle HTTP客户端引发了一组异常。 可以从异常中获得响应 如果您想使用timeout,那么我可以通过使用guzzlehttp进行定向来提供一个选项 use GuzzleHttp\
cURL error 6: Could not resolve host: somedomain.com
那你怎么用这些东西呢?()
我需要知道主机是否在线/离线
编辑:
这对我不起作用,我总是得到:cURL错误6:无法解析主机:somedomain.comGuzzle HTTP客户端引发了一组异常。 可以从异常中获得响应
如果您想使用timeout,那么我可以通过使用guzzlehttp进行定向来提供一个选项
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
public function checkSiteStatus($host)
{
define("read_timeout", \GuzzleHttp\RequestOptions::READ_TIMEOUT );
try {
$client = new Client();
$response = $response = $client->get(
$host, [
'headers' => [
// your headers if any
],
'stream' => true,
'read_timeout' => 2,
]);
$body = $response->getBody();
// Returns false on timeout
$data = $body->read(1024);
// Returns false on timeout
$line = fgets($body->detach());
// you can use $data or $line if they are false means there is timeout.
} catch (RequestException $e) {
//Access the message or other type of errors and react to them
}
}
您可以在中阅读更多关于它们的信息。您有离线主机要测试吗?嗯。实际上,我没有。我将获得域名或ip地址,需要检查服务器是否在线。有时我会得到一个不存在的域名。这能回答你的问题吗?流式处理为true是必需的,它将流式处理响应,而不是预先下载所有响应。@kamilon123s您得到了什么结果?谢谢兄弟,为我工作了
use Illuminate\Support\Facades\Http;
use GuzzleHttp\Exception\RequestException;
public function checkSiteStatus($host)
{
try {
return Http::timeout(2)->get($host);
} catch (RequestException $e) {
//Access the message or other type of errors and react to them
if (!$e->hasResponse()) {
//No response from server. Assume the host is offline or server is overloaded.
return 'offline';
}
return 'offline';
}
}
use GuzzleHttp\Exception\RequestException;
try {
$client->request('GET', 'https://github.com/_abc_123_404');
} catch (RequestException $e) {
//Access the message or other type of errors and react to them
$e->getMessage();
if (! $e->hasResponse()) {
//No response from server. Assume the host is offline or server is overloaded.
}
}
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
public function checkSiteStatus($host)
{
define("read_timeout", \GuzzleHttp\RequestOptions::READ_TIMEOUT );
try {
$client = new Client();
$response = $response = $client->get(
$host, [
'headers' => [
// your headers if any
],
'stream' => true,
'read_timeout' => 2,
]);
$body = $response->getBody();
// Returns false on timeout
$data = $body->read(1024);
// Returns false on timeout
$line = fgets($body->detach());
// you can use $data or $line if they are false means there is timeout.
} catch (RequestException $e) {
//Access the message or other type of errors and react to them
}
}