Hoe kan ik controleren of een URL bestaat via PHP?

Hoe controleer ik of er een URL bestaat (niet 404) in PHP?


Antwoord 1, autoriteit 100%

Hier:

$file = 'http://www.example.com/somefile.jpg';
$file_headers = @get_headers($file);
if(!$file_headers || $file_headers[0] == 'HTTP/1.1 404 Not Found') {
    $exists = false;
}
else {
    $exists = true;
}

Van hieren rechts onderhet bovenstaande bericht is er een kruloplossing:

function url_exists($url) {
    return curl_init($url) !== false;
}

Antwoord 2, autoriteit 19%

Bij het uitzoeken of een url uit php bestaat, zijn er een paar dingen waar u op moet letten:

  • Is de url zelf geldig (een string, niet leeg, goede syntaxis), dit is snel te controleren aan de serverkant.
  • Wachten op een reactie kan enige tijd duren en de uitvoering van de code blokkeren.
  • Niet alle headers die worden geretourneerd door get_headers() zijn goed gevormd.
  • Gebruik krul (als je kunt).
  • Voorkom dat de hele body/content wordt opgehaald, maar vraag alleen de headers op.
  • Overweeg om URL’s om te leiden:
  • Wilt u dat de eerste code wordt geretourneerd?
  • Of volg alle omleidingen en retourneer de laatste code?
  • Je zou kunnen eindigen met een 200, maar het kan omleiden met behulp van metatags of javascript. Uitzoeken wat er daarna gebeurt, is moeilijk.

Houd er rekening mee dat, welke methode je ook gebruikt, het even duurt om op een reactie te wachten.
Alle code kan (en zal waarschijnlijk) stoppen totdat je het resultaat weet of totdat de verzoeken zijn verlopen.

Bijvoorbeeld: de onderstaande code kan LANG duren om de pagina weer te geven als de URL’s ongeldig of onbereikbaar zijn:

<?php
$urls = getUrls(); // some function getting say 10 or more external links
foreach($urls as $k=>$url){
  // this could potentially take 0-30 seconds each
  // (more or less depending on connection, target site, timeout settings...)
  if( ! isValidUrl($url) ){
    unset($urls[$k]);
  }
}
echo "yay all done! now show my site";
foreach($urls as $url){
  echo "<a href=\"{$url}\">{$url}</a><br/>";
}

De onderstaande functies kunnen nuttig zijn, u wilt ze waarschijnlijk aanpassen aan uw behoeften:

   function isValidUrl($url){
        // first do some quick sanity checks:
        if(!$url || !is_string($url)){
            return false;
        }
        // quick check url is roughly a valid http request: ( http://blah/... ) 
        if( ! preg_match('/^http(s)?:\/\/[a-z0-9-]+(\.[a-z0-9-]+)*(:[0-9]+)?(\/.*)?$/i', $url) ){
            return false;
        }
        // the next bit could be slow:
        if(getHttpResponseCode_using_curl($url) != 200){
//      if(getHttpResponseCode_using_getheaders($url) != 200){  // use this one if you cant use curl
            return false;
        }
        // all good!
        return true;
    }
    function getHttpResponseCode_using_curl($url, $followredirects = true){
        // returns int responsecode, or false (if url does not exist or connection timeout occurs)
        // NOTE: could potentially take up to 0-30 seconds , blocking further code execution (more or less depending on connection, target site, and local timeout settings))
        // if $followredirects == false: return the FIRST known httpcode (ignore redirects)
        // if $followredirects == true : return the LAST  known httpcode (when redirected)
        if(! $url || ! is_string($url)){
            return false;
        }
        $ch = @curl_init($url);
        if($ch === false){
            return false;
        }
        @curl_setopt($ch, CURLOPT_HEADER         ,true);    // we want headers
        @curl_setopt($ch, CURLOPT_NOBODY         ,true);    // dont need body
        @curl_setopt($ch, CURLOPT_RETURNTRANSFER ,true);    // catch output (do NOT print!)
        if($followredirects){
            @curl_setopt($ch, CURLOPT_FOLLOWLOCATION ,true);
            @curl_setopt($ch, CURLOPT_MAXREDIRS      ,10);  // fairly random number, but could prevent unwanted endless redirects with followlocation=true
        }else{
            @curl_setopt($ch, CURLOPT_FOLLOWLOCATION ,false);
        }
//      @curl_setopt($ch, CURLOPT_CONNECTTIMEOUT ,5);   // fairly random number (seconds)... but could prevent waiting forever to get a result
//      @curl_setopt($ch, CURLOPT_TIMEOUT        ,6);   // fairly random number (seconds)... but could prevent waiting forever to get a result
//      @curl_setopt($ch, CURLOPT_USERAGENT      ,"Mozilla/5.0 (Windows NT 6.0) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.89 Safari/537.1");   // pretend we're a regular browser
        @curl_exec($ch);
        if(@curl_errno($ch)){   // should be 0
            @curl_close($ch);
            return false;
        }
        $code = @curl_getinfo($ch, CURLINFO_HTTP_CODE); // note: php.net documentation shows this returns a string, but really it returns an int
        @curl_close($ch);
        return $code;
    }
    function getHttpResponseCode_using_getheaders($url, $followredirects = true){
        // returns string responsecode, or false if no responsecode found in headers (or url does not exist)
        // NOTE: could potentially take up to 0-30 seconds , blocking further code execution (more or less depending on connection, target site, and local timeout settings))
        // if $followredirects == false: return the FIRST known httpcode (ignore redirects)
        // if $followredirects == true : return the LAST  known httpcode (when redirected)
        if(! $url || ! is_string($url)){
            return false;
        }
        $headers = @get_headers($url);
        if($headers && is_array($headers)){
            if($followredirects){
                // we want the last errorcode, reverse array so we start at the end:
                $headers = array_reverse($headers);
            }
            foreach($headers as $hline){
                // search for things like "HTTP/1.1 200 OK" , "HTTP/1.0 200 OK" , "HTTP/1.1 301 PERMANENTLY MOVED" , "HTTP/1.1 400 Not Found" , etc.
                // note that the exact syntax/version/output differs, so there is some string magic involved here
                if(preg_match('/^HTTP\/\S+\s+([1-9][0-9][0-9])\s+.*/', $hline, $matches) ){// "HTTP/*** ### ***"
                    $code = $matches[1];
                    return $code;
                }
            }
            // no HTTP/xxx found in headers:
            return false;
        }
        // no headers :
        return false;
    }

Antwoord 3, autoriteit 15%

$headers = @get_headers($this->_value);
if(strpos($headers[0],'200')===false)return false;

dus elke keer dat je contact opneemt met een website en iets anders krijgt dan 200, zal het werken


Antwoord 4, autoriteit 6%

je kunt curl niet gebruiken op bepaalde servers
je kunt deze code gebruiken

<?php
$url = 'http://www.example.com';
$array = get_headers($url);
$string = $array[0];
if(strpos($string,"200"))
  {
    echo 'url exists';
  }
  else
  {
    echo 'url does not exist';
  }
?>

Antwoord 5, autoriteit 3%

Ik gebruik deze functie:

/**
 * @param $url
 * @param array $options
 * @return string
 * @throws Exception
 */
function checkURL($url, array $options = array()) {
    if (empty($url)) {
        throw new Exception('URL is empty');
    }
    // list of HTTP status codes
    $httpStatusCodes = array(
        100 => 'Continue',
        101 => 'Switching Protocols',
        102 => 'Processing',
        200 => 'OK',
        201 => 'Created',
        202 => 'Accepted',
        203 => 'Non-Authoritative Information',
        204 => 'No Content',
        205 => 'Reset Content',
        206 => 'Partial Content',
        207 => 'Multi-Status',
        208 => 'Already Reported',
        226 => 'IM Used',
        300 => 'Multiple Choices',
        301 => 'Moved Permanently',
        302 => 'Found',
        303 => 'See Other',
        304 => 'Not Modified',
        305 => 'Use Proxy',
        306 => 'Switch Proxy',
        307 => 'Temporary Redirect',
        308 => 'Permanent Redirect',
        400 => 'Bad Request',
        401 => 'Unauthorized',
        402 => 'Payment Required',
        403 => 'Forbidden',
        404 => 'Not Found',
        405 => 'Method Not Allowed',
        406 => 'Not Acceptable',
        407 => 'Proxy Authentication Required',
        408 => 'Request Timeout',
        409 => 'Conflict',
        410 => 'Gone',
        411 => 'Length Required',
        412 => 'Precondition Failed',
        413 => 'Payload Too Large',
        414 => 'Request-URI Too Long',
        415 => 'Unsupported Media Type',
        416 => 'Requested Range Not Satisfiable',
        417 => 'Expectation Failed',
        418 => 'I\'m a teapot',
        422 => 'Unprocessable Entity',
        423 => 'Locked',
        424 => 'Failed Dependency',
        425 => 'Unordered Collection',
        426 => 'Upgrade Required',
        428 => 'Precondition Required',
        429 => 'Too Many Requests',
        431 => 'Request Header Fields Too Large',
        449 => 'Retry With',
        450 => 'Blocked by Windows Parental Controls',
        500 => 'Internal Server Error',
        501 => 'Not Implemented',
        502 => 'Bad Gateway',
        503 => 'Service Unavailable',
        504 => 'Gateway Timeout',
        505 => 'HTTP Version Not Supported',
        506 => 'Variant Also Negotiates',
        507 => 'Insufficient Storage',
        508 => 'Loop Detected',
        509 => 'Bandwidth Limit Exceeded',
        510 => 'Not Extended',
        511 => 'Network Authentication Required',
        599 => 'Network Connect Timeout Error'
    );
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_NOBODY, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    if (isset($options['timeout'])) {
        $timeout = (int) $options['timeout'];
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
    }
    curl_exec($ch);
    $returnedStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    if (array_key_exists($returnedStatusCode, $httpStatusCodes)) {
        return "URL: '{$url}' - Error code: {$returnedStatusCode} - Definition: {$httpStatusCodes[$returnedStatusCode]}";
    } else {
        return "'{$url}' does not exist";
    }
}

Antwoord 6

function urlIsOk($url)
{
    $headers = @get_headers($url);
    $httpStatus = intval(substr($headers[0], 9, 3));
    if ($httpStatus<400)
    {
        return true;
    }
    return false;
}

Antwoord 7

behoorlijk snel:

function http_response($url){
    $resURL = curl_init(); 
    curl_setopt($resURL, CURLOPT_URL, $url); 
    curl_setopt($resURL, CURLOPT_BINARYTRANSFER, 1); 
    curl_setopt($resURL, CURLOPT_HEADERFUNCTION, 'curlHeaderCallback'); 
    curl_setopt($resURL, CURLOPT_FAILONERROR, 1); 
    curl_exec ($resURL); 
    $intReturnCode = curl_getinfo($resURL, CURLINFO_HTTP_CODE); 
    curl_close ($resURL); 
    if ($intReturnCode != 200 && $intReturnCode != 302 && $intReturnCode != 304) { return 0; } else return 1;
}
echo 'google:';
echo http_response('http://www.google.com');
echo '/ ogogle:';
echo http_response('http://www.ogogle.com');

Antwoord 8

Alle bovenstaande oplossingen + extra suiker. (Ultieme AIO-oplossing)

/**
 * Check that given URL is valid and exists.
 * @param string $url URL to check
 * @return bool TRUE when valid | FALSE anyway
 */
function urlExists ( $url ) {
    // Remove all illegal characters from a url
    $url = filter_var($url, FILTER_SANITIZE_URL);
    // Validate URI
    if (filter_var($url, FILTER_VALIDATE_URL) === FALSE
        // check only for http/https schemes.
        || !in_array(strtolower(parse_url($url, PHP_URL_SCHEME)), ['http','https'], true )
    ) {
        return false;
    }
    // Check that URL exists
    $file_headers = @get_headers($url);
    return !(!$file_headers || $file_headers[0] === 'HTTP/1.1 404 Not Found');
}

Voorbeeld:

var_dump ( urlExists('http://stackoverflow.com/') );
// Output: true;

Antwoord 9

om te controleren of de url online of offline is —

function get_http_response_code($theURL) {
    $headers = @get_headers($theURL);
    return substr($headers[0], 9, 3);
}

Antwoord 10

function url_exists($url) {
    $headers = @get_headers($url);
    return (strpos($headers[0],'200')===false)? false:true;
}

Antwoord 11

Ik voer een aantal tests uit om te zien of links op mijn site geldig zijn – waarschuwt me wanneer derden hun links wijzigen. Ik had een probleem met een site met een slecht geconfigureerd certificaat waardoor de get_headers van php niet werkten.

DUS, ik las dat krul sneller was en besloot dat eens te proberen. toen had ik een probleem met linkedin waardoor ik een 999-fout kreeg, wat een user-agent-probleem bleek te zijn.

Het kon me niet schelen of het certificaat niet geldig was voor deze test, en het kon me niet schelen of het antwoord een omleiding was.

Toen bedacht ik dat ik toch get_headers zou gebruiken als curl niet werkte….

Probeer het eens….

/**
 * returns true/false if the $url is valid.
 *
 * @param string $url assumes this is a valid url.
 *
 * @return bool
 */
private function urlExists(string $url): bool
{
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);     // do not output response in stdout
    curl_setopt($ch, CURLOPT_NOBODY, true);             // this does a head request to make it faster.
    curl_setopt($ch, CURLOPT_HEADER, true);             // just the headers
    curl_setopt($ch, CURLOPT_SSL_VERIFYSTATUS, false);  // turn off that pesky ssl stuff - some sys admins can't get it right.
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    // set a real user agent to stop linkedin getting upset.
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36');
    curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    if (($http_code >= 200 && $http_code < 400) || $http_code === 999) {
        curl_close($ch);
        return true;
    }
    //$error = curl_error($ch); // used for debugging.
    curl_close($ch);
    // just try the get_headers - it might work!
    stream_context_set_default(
        ['http' => ['method' => 'HEAD']]
    );
    $file_headers = @get_headers($url);
    if ($file_headers !== false) {
        $response_code = substr($file_headers[0], 9, 3);
        return $response_code >= 200 && $response_code < 400;
    }
    return false;
}

Antwoord 12

Hier is een oplossing die alleen de eerste byte van de broncode leest… false retourneert als de file_get_contents mislukt… Dit werkt ook voor externe bestanden zoals afbeeldingen.

function urlExists($url)
{
    if (@file_get_contents($url,false,NULL,0,1))
    {
        return true;
    }
    return false;
}

Antwoord 13

cURL kan HTTP-code retourneren. Ik denk niet dat al die extra code nodig is?

function urlExists($url=NULL)
    {
        if($url == NULL) return false;
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $data = curl_exec($ch);
        $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch); 
        if($httpcode>=200 && $httpcode<300){
            return true;
        } else {
            return false;
        }
    }

Antwoord 14

Een andere manier om te controleren of een URL geldig is of niet kan zijn:

<?php
  if (isValidURL("https://www.gimepix.com")) {
      echo "URL is valid...";
  } else {
      echo "URL is not valid...";
  }
  function isValidURL($url) {
      $file_headers = @get_headers($url);
      if (strpos($file_headers[0], "200 OK") > 0) {
         return true;
      } else {
        return false;
      }
  }
?>

Antwoord 15

Een ding om rekening mee te houden wanneer u de koptekst voor een 404 controleert, is het geval dat een site niet onmiddellijk een 404 genereert.

Veel sites controleren of een pagina al dan niet bestaat in de PHP/ASP (et cetera) bron en sturen je door naar een 404-pagina. In die gevallen wordt de header in principe uitgebreid met de header van de 404 die wordt gegenereerd. In die gevallen staat de 404-fout niet in de eerste regel van de kop, maar in de tiende.

$array = get_headers($url);
$string = $array[0];
print_r($string) // would generate:
Array ( 
[0] => HTTP/1.0 301 Moved Permanently 
[1] => Date: Fri, 09 Nov 2018 16:12:29 GMT 
[2] => Server: Apache/2.4.34 (FreeBSD) LibreSSL/2.7.4 PHP/7.0.31 
[3] => X-Powered-By: PHP/7.0.31 
[4] => Set-Cookie: landing=%2Freed-diffuser-fig-pudding-50; path=/; HttpOnly 
[5] => Location: /reed-diffuser-fig-pudding-50/ 
[6] => Content-Length: 0 
[7] => Connection: close 
[8] => Content-Type: text/html; charset=utf-8 
[9] => HTTP/1.0 404 Not Found 
[10] => Date: Fri, 09 Nov 2018 16:12:29 GMT 
[11] => Server: Apache/2.4.34 (FreeBSD) LibreSSL/2.7.4 PHP/7.0.31 
[12] => X-Powered-By: PHP/7.0.31 
[13] => Set-Cookie: landing=%2Freed-diffuser-fig-pudding-50%2F; path=/; HttpOnly 
[14] => Connection: close 
[15] => Content-Type: text/html; charset=utf-8 
) 

Antwoord 16

de eenvoudige manier is krullen (en ook SNELLER)

<?php
$mylinks="http://site.com/page.html";
$handlerr = curl_init($mylinks);
curl_setopt($handlerr,  CURLOPT_RETURNTRANSFER, TRUE);
$resp = curl_exec($handlerr);
$ht = curl_getinfo($handlerr, CURLINFO_HTTP_CODE);
if ($ht == '404')
     { echo 'OK';}
else { echo 'NO';}
?>

Antwoord 17

get_headers()retourneert een array met de headers verzonden door de server als reactie op een HTTP-verzoek.

$image_path = 'https://your-domain.com/assets/img/image.jpg';
$file_headers = @get_headers($image_path);
//Prints the response out in an array
//print_r($file_headers); 
if($file_headers[0] == 'HTTP/1.1 404 Not Found'){
   echo 'Failed because path does not exist.</br>';
}else{
   echo 'It works. Your good to go!</br>';
}

Antwoord 18

Het beste en eenvoudigste antwoord tot nu toe met get_headers()
Het beste om te controleren op string “200 ok”. het is veel beter dan te controleren

$file_headers = @get_headers($file-path);
$file_headers[0];

omdat de array-sleutelnummers soms variëren. dus het beste is om te controleren op “200 ok”. Elke URL die up is, zal overal in de get_headers()-reactie “200 ok” hebben.

function url_exist($url) {
        $urlheaders = get_headers($url);
        //print_r($urlheaders);
        $urlmatches  = preg_grep('/200 ok/i', $urlheaders);
         if(!empty($urlmatches)){
           return true;
         }else{
           return false;
         }
}

controleer nu of de functie waar of onwaar is

if(url_exist(php-url-variable-here)
  URL exist
}else{
  URL don't exist
}

Antwoord 19

behoorlijk oud draadje, maar..
ik doe dit:

$file = 'http://www.google.com';
$file_headers = @get_headers($file);
if ($file_headers) {
    $exists = true;
} else {
    $exists = false;
}

Other episodes