Program Tip

URL이 존재하지 않는 경우 file_get_contents

programtip 2020. 11. 9. 20:32
반응형

URL이 존재하지 않는 경우 file_get_contents


URL에 액세스하기 위해 file_get_contents ()를 사용하고 있습니다.

file_get_contents('http://somenotrealurl.com/notrealpage');

URL이 실제가 아닌 경우이 오류 메시지를 반환합니다. 페이지가 존재하지 않는다는 것을 알고이 오류 메시지를 표시하지 않고 적절하게 작동하도록 오류가 발생하도록하려면 어떻게해야합니까?

file_get_contents('http://somenotrealurl.com/notrealpage') 
[function.file-get-contents]: 
failed to open stream: HTTP request failed! HTTP/1.0 404 Not Found 
in myphppage.php on line 3

예를 들어 zend에서는 다음과 같이 말할 수 있습니다. if ($request->isSuccessful())

$client = New Zend_Http_Client();
$client->setUri('http://someurl.com/somepage');

$request = $client->request();

if ($request->isSuccessful()) {
 //do stuff with the result
}

HTTP 응답 코드 를 확인해야합니다 .

function get_http_response_code($url) {
    $headers = get_headers($url);
    return substr($headers[0], 9, 3);
}
if(get_http_response_code('http://somenotrealurl.com/notrealpage') != "200"){
    echo "error";
}else{
    file_get_contents('http://somenotrealurl.com/notrealpage');
}

PHP에서 이러한 명령을 사용하면 이러한 @경고를 억제하기 위해 접두사를 붙일 수 있습니다 .

@file_get_contents('http://somenotrealurl.com/notrealpage');

file_get_contents ()FALSE실패가 발생하면 반환하므로 반환 된 결과를 확인하면 실패를 처리 할 수 ​​있습니다.

$pageDocument = @file_get_contents('http://somenotrealurl.com/notrealpage');

if ($pageDocument === false) {
    // Handle error
}

file_get_contentshttp 래퍼를 사용하여 호출 할 때마다 로컬 범위의 변수가 생성됩니다. $ http_response_header

이 변수는 모든 HTTP 헤더를 포함합니다. 이 방법은 get_headers()하나의 요청 만 실행되기 때문에 기능 보다 좋습니다 .

참고 : 2 개의 요청이 다르게 종료 될 수 있습니다. 예를 들어, get_headers()503을 반환하고 file_get_contents ()는 200을 반환합니다. 적절한 출력을 얻을 수 있지만 get_headers () 호출에서 503 오류로 인해 사용하지 않습니다.

function getUrl($url) {
    $content = file_get_contents($url);
    // you can add some code to extract/parse response number from first header. 
    // For example from "HTTP/1.1 200 OK" string.
    return array(
            'headers' => $http_response_header,
            'content' => $content
        );
}

// Handle 40x and 50x errors
$response = getUrl("http://example.com/secret-message");
if ($response['content'] === FALSE)
    echo $response['headers'][0];   // HTTP/1.1 401 Unauthorized
else
    echo $response['content'];

이 aproach는 file_get_contents ()를 사용하는 경우 $ http_response_header 가 로컬 범위에서 덮어 쓰기 되기 때문에 다른 변수에 저장된 요청 헤더가 거의 없음을 추적 할 수 있습니다 .


file_get_contents매우 간결하고 편리 하지만 더 나은 제어를 위해 Curl 라이브러리를 선호하는 경향이 있습니다. 여기에 예가 있습니다.

function fetchUrl($uri) {
    $handle = curl_init();

    curl_setopt($handle, CURLOPT_URL, $uri);
    curl_setopt($handle, CURLOPT_POST, false);
    curl_setopt($handle, CURLOPT_BINARYTRANSFER, false);
    curl_setopt($handle, CURLOPT_HEADER, true);
    curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($handle, CURLOPT_CONNECTTIMEOUT, 10);

    $response = curl_exec($handle);
    $hlength  = curl_getinfo($handle, CURLINFO_HEADER_SIZE);
    $httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
    $body     = substr($response, $hlength);

    // If HTTP response is not 200, throw exception
    if ($httpCode != 200) {
        throw new Exception($httpCode);
    }

    return $body;
}

$url = 'http://some.host.com/path/to/doc';

try {
    $response = fetchUrl($url);
} catch (Exception $e) {
    error_log('Fetch URL failed: ' . $e->getMessage() . ' for ' . $url);
}

간단하고 기능적 (어디에서나 사용하기 쉬움) :

function file_contents_exist($url, $response_code = 200)
{
    $headers = get_headers($url);

    if (substr($headers[0], 9, 3) == $response_code)
    {
        return TRUE;
    }
    else
    {
        return FALSE;
    }
}

예:

$file_path = 'http://www.google.com';

if(file_contents_exist($file_path))
{
    $file = file_get_contents($file_path);
}

To avoid double requests as commented by Orbling on the answer of ynh you could combine their answers. If you get a valid response in the first place, use that. If not find out what the problem was (if needed).

$urlToGet = 'http://somenotrealurl.com/notrealpage';
$pageDocument = @file_get_contents($urlToGet);
if ($pageDocument === false) {
     $headers = get_headers($urlToGet);
     $responseCode = substr($headers[0], 9, 3);
     // Handle errors based on response code
     if ($responseCode == '404') {
         //do something, page is missing
     }
     // Etc.
} else {
     // Use $pageDocument, echo or whatever you are doing
}

You may add 'ignore_errors' => true to options:

$options = array(
  'http' => array(
    'ignore_errors' => true,
    'header' => "Content-Type: application/json\r\n"
    )
);
$context  = stream_context_create($options);
$result = file_get_contents('http://example.com', false, $context);

In that case you will be able to read a response from the server.


$url = 'https://www.yourdomain.com';

Normal

function checkOnline($url) {
    $headers = get_headers($url);
    $code = substr($headers[0], 9, 3);
    if ($code == 200) {
        return true;
    }
    return false;
}

if (checkOnline($url)) {
    // URL is online, do something..
    $getURL = file_get_contents($url);     
} else {
    // URL is offline, throw an error..
}

Pro

if (substr(get_headers($url)[0], 9, 3) == 200) {
    // URL is online, do something..
}

Wtf level

(substr(get_headers($url)[0], 9, 3) == 200) ? echo 'Online' : echo 'Offline';

참고URL : https://stackoverflow.com/questions/4358130/file-get-contents-when-url-doesnt-exist

반응형