【发布时间】:2014-02-12 12:22:09
【问题描述】:
我正在使用file_get_contents 从第 3 方获取数据,但是第 3 方目前正遭受 DDOS 攻击,因此我的大部分网站功能都丢失了。
如果打开流失败,如何设置重定向到另一个页面?
【问题讨论】:
-
检查空(file_get_contents)并用php重定向
标签: php redirect file-get-contents
我正在使用file_get_contents 从第 3 方获取数据,但是第 3 方目前正遭受 DDOS 攻击,因此我的大部分网站功能都丢失了。
如果打开流失败,如何设置重定向到另一个页面?
【问题讨论】:
标签: php redirect file-get-contents
更改默认超时,然后在失败时重定向。
您可以更改用于file_get_contents 的默认超时,如下所示:
ini_set('default_socket_timeout', 10); // 10 seconds
我们需要这样做,因为默认超时时间是 60 秒 - 而且您的访问者不想等待那么久。
然后您只需测试请求是否正常,并根据该请求进行重定向...
$request = file_get_contents($url);
if( !$request )
header("Location: http://someurl.com/");
exit;
(请记住在重定向后退出,或者有时仍然执行之后的代码)。
【讨论】:
这将对您有所帮助:
$url = "http://example.com/url";
$response = get_headers($url);
if($response[0] === 'HTTP/1.1 200 OK') {
// Request response is OK
$content = file_get_contents($url);
} else {
// if header response is NOT OK redirect...
header("Location: someUrlGoesHere");
}
【讨论】:
你可以用 header() 重定向它。
<?php
$data = file_get_contents($attackedUrl);
if(!$data)
header("Location: $pageToRedirect");
?>
【讨论】:
简单。添加验证!
首先是several methods to check if a file exists on a remote server。
其次,如果您使用file_get_contents 获取数据,您可以添加验证以检查它是否是您期望的完整数据(其他答案/cmets 提到使用empty 进行检查,或检查虚假值。这取决于您但是,您如何执行此操作,因为没有提供有关接收到的数据类型的上下文)。 You can also set a timeout value in case it takes too long to fetch!
要重定向,你可以使用PHP's header function,像这样:
header('Location: http://my.redirected/page/href');
但是,如果您已经输出了内容,header() 将不起作用。,因此请确保在运行 header 之前检查您的脚本是否有 echo / print 行
【讨论】:
https://www.php.net/manual/fr/function.is-file.php
<?php
$url = "../../filename.php";
if (is_file($url))
echo "File Exist!";
//$request = file_get_contents($url);
//print(filesize($url))." ko";
else
echo "File not Exist!";
?>
【讨论】: