【问题标题】:Strange result of a URLURL的奇怪结果
【发布时间】:2012-12-06 15:58:55
【问题描述】:
http://!@#$%^&*().com

这似乎是一个无效的 URL,实际上浏览器说它是一个无效的 URL。

但是当我通过 file_get_contents (XAMPP) 获取这个 URL 时,它给出了“500 Internal Server Error”的异常,因为这个 URL 不存在为什么我没有得到 404?

检查我正在使用的响应

$http_response_header

这是我的代码:

$url = "http://!@#$%^&*().com";
$contents = @file_get_contents($url);   
print_r($http_response_header);

当我在另一台机器 (WAMP) 上运行相同的程序时,它会说 $http_response_header 是一个未定义的变量。

有人知道这里有什么问题吗?

【问题讨论】:

标签: php url file-get-contents


【解决方案1】:

您没有收到404,因为该域不存在。尝试使用有效域。使用http://.@#$%^&*().com 将返回failed to open stream: operation failed,而有效域将返回failed to open stream: HTTP request failed

请注意,一个是operation failed,另一个是HTTP request failed,只有在HTTP请求失败时才会出现HTTP错误

例子

error_reporting(E_ALL);
ini_set("display_errors", "On");

$url = "http://stockoverflow.com/xxxx"; // URL does not exist 
$response = @file_get_contents($url);
var_dump($response,$http_response_header);

输出

boolean false
array (size=7)
  0 => string 'HTTP/1.1 404 Not Found' (length=22)  <--- you get your 404
  1 => string 'Content-Type: text/html' (length=23)
  2 => string 'Server: Microsoft-IIS/7.5' (length=25)
  3 => string 'X-Powered-By: ASP.NET' (length=21)
  4 => string 'Date: Wed, 19 Dec 2012 10:26:20 GMT' (length=35)
  5 => string 'Connection: close' (length=17)
  6 => string 'Content-Length: 1245' (length=20)

【讨论】:

    【解决方案2】:

    您正在抑制file_get_contents 调用中的错误,您输入的域实际上是无效的,正如您所说,函数调用将返回 false 并触发以下警告

    file_get_contents(http://.@#$%^&*().com): failed to open stream: operation failed
    

    您不会收到 404,因为域无效并且可能从未发送过 http 请求,因此您的 $http_response_header 为空。

    也许 XAMPP 和 WAMP 在操作系统或 PHP 版本上的差异解释了为什么它们的行为不同?

    我的建议是首先检查 file_get_contents 的返回值,只有当它不是 false 时才继续检查响应头。

    【讨论】:

    • 你是对的,但想在这里补充一点。填充 $http_response_header 的机器也在运行带有 XAMPP 的 IIS,因此对于这些类型的 URL,X-POWERED 值始终是 IIS 和 ASP.NET
    • 好的,我明白了。如果 URL 无效,$http_response_header 实际上是在向我显示上次调用的结果。
    猜你喜欢
    • 1970-01-01
    • 2016-11-28
    • 2012-12-16
    • 2016-08-24
    • 2018-01-24
    • 2021-03-01
    • 2014-08-17
    • 1970-01-01
    • 2023-03-18
    相关资源
    最近更新 更多