What construction do I need to implement if I call

file_get_contents($target) 

where target is the url of the page, and the server sends a 404 error. If I get an error 404, I must execute at this address

 file_get_contents($target) 

for another address via if / else.

  • use get_headers (only this will be a separate request, although nothing will be received except headers) or curl. - tcpack4

2 answers 2

Official documentation says that the file_get_contents function

The function returns read data or FALSE in case of an error.

The error code can be found by analyzing the $http_response_header after calling the function. This array contains all headers coming from the server.

So the code you should have is

 function getResponseCode($headers) { ..... } $content = file_get_contents($target1); if ( $content === false && // === вместо ==, чтобы отличить '' от false getResponseCode($http_response_header) === 404 ) $content = file_get_contents($target2); 
  • 2
    $http_response_header with you. Formally, of course, not the function returns, but the headers are available - teran
  • @teran did not know. Thanks for the clarification - Anton Shchyrov

The get_headers () function returns an array, the first element of which contains the server response code. I wrote an example of getting this code and following actions, depending on the received code:

 // Первая ссылка $target = 'http://www.example.com'; // Если ошибка, перезаписать ссылку в $target get_status($target) ?: $target = 'http://вторая ссылка'; // Получить контент $content = file_get_contents($target); var_dump($content); function get_status($url) { preg_match('~\d{3}~', get_headers($url)[0], $http); return ($http[0] < 400); }