2011-01-05 12 views
19

Voglio verificare se un sito web è su o giù in una particolare istanza utilizzando PHP. Sono venuto a sapere che arricciatura recupererà il contenuto del file ma non voglio leggere il contenuto del sito web. Voglio solo controllare lo stato del sito web. C'è un modo per controllare lo stato del sito? Possiamo usare il ping per controllare lo stato? Per me è sufficiente ottenere i segnali di stato come (404, 403, ecc.) Dal server. Un piccolo frammento di codice potrebbe aiutarmi molto.curl e ping - come verificare se un sito web è su o giù?

+2

Come si definisce 'up'? Una pagina vuota che restituisce HTTP '200' è attiva? – webbiedave

+0

@Nate: Grazie per la tua modifica! – brainless

risposta

42

qualcosa come questo dovrebbe funzionare

$url = 'yoururl'; 
    $ch = curl_init($url); 
    curl_setopt($ch, CURLOPT_NOBODY, true); 
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); 
    curl_exec($ch); 
    $retcode = curl_getinfo($ch, CURLINFO_HTTP_CODE); 
    curl_close($ch); 
    if (200==$retcode) { 
     // All's well 
    } else { 
     // not so much 
    } 
+1

Preferisco anche impostare 'CURLOPT_CONNECTTIMEOUT' e' CURLOPT_TIMEOUT' per abbassare i valori. – machineaddict

+0

@machineaddict Vuoi dire "sito offline" invece di aspettare la connessione? Non vedo la differenza tra controllare 2 volte per una cosa e aspettare un po 'per l'operazione corrente. – erm3nda

+0

@machineaddict Anche se CURLOPT_FOLLOWLOCATION è impostato su true, restituisce comunque un codice di ritorno 301 ... Com'è possibile? –

5

Hai visto la funzione get_headers()? http://it.php.net/manual/en/function.get-headers.php. Sembra fare esattamente quello che ti serve.

Se si utilizza il ricciolo direttamente con il flag -I, restituirà le intestazioni HTTP (404 ecc.) Anziché il codice HTML della pagina. In PHP, l'equivalente è l'opzione curl_setopt($ch, CURLOPT_NOBODY, 1);.

2

ping non farà quello che stai cercando - ti dirà solo se la macchina è attiva (e risponde a ping). Ciò non significa necessariamente che il server web sia attivo, comunque.

Si potrebbe provare a utilizzare il metodo http_head: recupererà le intestazioni che il server Web invia all'utente. Se il server sta rinviando le intestazioni, allora sai che è attivo e funzionante.

+0

Questo hyperlink incorporato http://ca.php.net/http_head reindirizza a http://ca.php.net/manual-lookup.php?pattern=http_head&lang=en&scope=404quickref che il seguente messaggio: *** http_head * * non esiste Partite più vicine: *. La risposta deve essere modificata per contenere il riferimento corretto. –

2

Non è possibile testare un server Web con ping, perché è un servizio diverso. Il server potrebbe essere in esecuzione, ma il daemon webserver potrebbe essere arrestato in ogni caso. Quindi Curl è tuo amico. Ignora semplicemente il contenuto.

9
function checkStatus($url) { 
    $agent = "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_5_8; pt-pt) AppleWebKit/533.20.25 (KHTML, like Gecko) Version/5.0.4 Safari/533.20.27"; 

    // initializes curl session 
    $ch = curl_init(); 

    // sets the URL to fetch 
    curl_setopt($ch, CURLOPT_URL, $url); 

    // sets the content of the User-Agent header 
    curl_setopt($ch, CURLOPT_USERAGENT, $agent); 

    // make sure you only check the header - taken from the answer above 
    curl_setopt($ch, CURLOPT_NOBODY, true); 

    // follow "Location: " redirects 
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); 

    // return the transfer as a string 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 

    // disable output verbose information 
    curl_setopt($ch, CURLOPT_VERBOSE, false); 

    // max number of seconds to allow cURL function to execute 
    curl_setopt($ch, CURLOPT_TIMEOUT, 5); 

    // execute 
    curl_exec($ch); 

    // get HTTP response code 
    $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE); 

    curl_close($ch); 

    if ($httpcode >= 200 && $httpcode < 300) 
     return true; 
    else 
     return false; 
} 

// how to use 
//=================== 
if ($this->checkStatus("http://www.dineshrabara.in")) 
    echo "Website is up"; 
else 
    echo "Website is down"; 
exit; 
6
curl -Is $url | grep HTTP | cut -d ' ' -f2 
+11

Quando si fornisce il codice che risolve il problema, è meglio anche dare almeno una breve spiegazione di come funziona in modo che la lettura della gente non debba analizzarla mentalmente per linea per capire le differenze. – Fluffeh

4

Ecco come ho fatto. Ho impostato l'agente utente per ridurre al minimo la possibilità che il target mi bannasse e disabilitato la verifica SSL poiché conosco il target:

private static function checkSite($url) { 
    $useragent = $_SERVER['HTTP_USER_AGENT']; 

    $options = array(
      CURLOPT_RETURNTRANSFER => true,  // return web page 
      CURLOPT_HEADER   => false,  // do not return headers 
      CURLOPT_FOLLOWLOCATION => true,  // follow redirects 
      CURLOPT_USERAGENT  => $useragent, // who am i 
      CURLOPT_AUTOREFERER => true,  // set referer on redirect 
      CURLOPT_CONNECTTIMEOUT => 2,   // timeout on connect (in seconds) 
      CURLOPT_TIMEOUT  => 2,   // timeout on response (in seconds) 
      CURLOPT_MAXREDIRS  => 10,   // stop after 10 redirects 
      CURLOPT_SSL_VERIFYPEER => false,  // SSL verification not required 
      CURLOPT_SSL_VERIFYHOST => false,  // SSL verification not required 
    ); 
    $ch = curl_init($url); 
    curl_setopt_array($ch, $options); 
    curl_exec($ch); 

    $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE); 
    curl_close($ch); 
    return ($httpcode == 200); 
} 
Problemi correlati