0
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是一个未定义的变量。

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

4

2 回答 2

1

You are suppressing errors at the file_get_contents call, the domain you entered is actually invalid as you stated and the function call will return false and trigger the following warning

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

You won't get a 404 because the domain is invalid and the http request is probably never sent, hence your $http_response_header is empty.

Maybe a difference in OS or PHP version between XAMPP and WAMP explain why they act differently?

My advice is first checking the return value of file_get_contents and only when it's not false continue with inspecting the response headers.

于 2012-12-19T10:27:59.293 回答
0

You are not getting 404 because the domain does not exist. Try using valid domain. Using http://.@#$%^&*().com would return failed to open stream: operation failed while a valid domain would return failed to open stream: HTTP request failed

Please note one is operation failed and the other HTTP request failed you can only get HTTP error when there is HTTP request failed

Example

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);

Output

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)
于 2012-12-19T10:27:38.423 回答