Come posso gestire l'avviso della funzione file_get_contents () in PHP?
-
07-07-2019 - |
Domanda
Ho scritto un codice PHP come questo
$site="http://www.google.com";
$content = file_get_content($site);
echo $content;
Ma quando rimuovo " http: // " da $ site
ricevo il seguente avviso:
Attenzione: file_get_contents (www.google.com) [function.file-get-contents]: non riuscito per aprire lo stream:
Ho provato try
e catch
ma non ha funzionato.
Soluzione
Passaggio 1: controlla il codice di ritorno: if ($ content === FALSE) {// gestisce l'errore qui ...}
Passaggio 2: sopprimere l'avvertenza inserendo un operatore di controllo degli errori (ad es. @
) davanti alla chiamata a file_get_contents () :
$ content = @file_get_contents ($ site);
Altri suggerimenti
Puoi anche impostare il gestore degli errori come funzione anonima che chiama un Eccezione e usa un tentativo / cattura su quell'eccezione.
set_error_handler(
function ($severity, $message, $file, $line) {
throw new ErrorException($message, $severity, $severity, $file, $line);
}
);
try {
file_get_contents('www.google.com');
}
catch (Exception $e) {
echo $e->getMessage();
}
restore_error_handler();
Sembra che un sacco di codice rilevi un piccolo errore, ma se stai usando eccezioni in tutta la tua app, dovresti farlo solo una volta, in alto (ad esempio in un file di configurazione incluso), e convertirà tutti i tuoi errori in Eccezioni in tutto.
Il mio modo preferito per farlo è abbastanza semplice:
if (!$data = file_get_contents("http://www.google.com")) {
$error = error_get_last();
echo "HTTP request failed. Error was: " . $error['message'];
} else {
echo "Everything went better than expected";
}
L'ho trovato dopo aver sperimentato il try / catch
da @enobrev sopra, ma questo consente un codice meno lungo (e IMO, più leggibile). Usiamo semplicemente error_get_last
per ottenere il testo dell'ultimo errore e file_get_contents
restituisce false in caso di fallimento, quindi un semplice "if" posso prenderlo.
Puoi anteporre un @:
$ content = @file_get_contents ($ site);
Questo sopprimerà qualsiasi avvertimento - usa con parsimonia! . Vedi Operatori di controllo errori
Modifica: quando rimuovi "http: //" non stai più cercando una pagina web, ma un file sul tuo disco chiamato " www.google ..... "
Un'alternativa è sopprimere l'errore e generare anche un'eccezione che è possibile rilevare in seguito. Ciò è particolarmente utile se nel tuo codice sono presenti più chiamate a file_get_contents (), poiché non è necessario eliminarle e gestirle tutte manualmente. Al contrario, è possibile effettuare diverse chiamate a questa funzione in un singolo blocco try / catch.
// Returns the contents of a file
function file_contents($path) {
$str = @file_get_contents($path);
if ($str === FALSE) {
throw new Exception("Cannot access '$path' to read contents.");
} else {
return $str;
}
}
// Example
try {
file_contents("a");
file_contents("b");
file_contents("c");
} catch (Exception $e) {
// Deal with it.
echo "Error: " , $e->getMessage();
}
Ecco come l'ho fatto ... Non c'è bisogno del blocco try-catch ... La soluzione migliore è sempre la più semplice ... Divertiti!
$content = @file_get_contents("http://www.google.com");
if (strpos($http_response_header[0], "200")) {
echo "SUCCESS";
} else {
echo "FAILED";
}
function custom_file_get_contents($url) {
return file_get_contents(
$url,
false,
stream_context_create(
array(
'http' => array(
'ignore_errors' => true
)
)
)
);
}
$content=FALSE;
if($content=custom_file_get_contents($url)) {
//play with the result
} else {
//handle the error
}
Ecco come lo gestisco:
$this->response_body = @file_get_contents($this->url, false, $context);
if ($this->response_body === false) {
$error = error_get_last();
$error = explode(': ', $error['message']);
$error = trim($error[2]) . PHP_EOL;
fprintf(STDERR, 'Error: '. $error);
die();
}
La cosa migliore sarebbe impostare i propri gestori di errori ed eccezioni che faranno qualcosa di utile come registrarlo in un file o inviare per e-mail quelli critici. http://www.php.net/set_error_handler
Puoi usare questo script
$url = @file_get_contents("http://www.itreb.info");
if ($url) {
// if url is true execute this
echo $url;
} else {
// if not exceute this
echo "connection error";
}
Poiché PHP 4 usa error_reporting () :
$site="http://www.google.com";
$old_error_reporting = error_reporting(E_ALL ^ E_WARNING);
$content = file_get_content($site);
error_reporting($old_error_reporting);
if ($content === FALSE) {
echo "Error getting '$site'";
} else {
echo $content;
}
Il modo più semplice per farlo è semplicemente anteporre un @ prima di file_get_contents, i & nbsp; e:..
$content = @file_get_contents($site);
qualcosa del genere:
public function get($curl,$options){
$context = stream_context_create($options);
$file = @file_get_contents($curl, false, $context);
$str1=$str2=$status=null;
sscanf($http_response_header[0] ,'%s %d %s', $str1,$status, $str2);
if($status==200)
return $file
else
throw new \Exception($http_response_header[0]);
}
Questo tenterà di ottenere i dati, se non funziona, rileverà l'errore e ti consentirà di fare tutto il necessario all'interno della cattura.
try {
$content = file_get_contents($site);
} catch(\Exception $e) {
return 'The file was not found';
}
È necessario utilizzare la funzione file_exists () prima di utilizzare file_get_contents (). In questo modo eviterai l'avvertimento php.
$file = "path/to/file";
if(file_exists($file)){
$content = file_get_contents($file);
}
Modifica il file php.ini
allow_url_fopen = On
allow_url_include = On
try {
$site="http://www.google.com";
$content = file_get_content($site);
echo $content;
} catch (ErrorException $e) {
// fix the url
}
set_error_handler(function ($errorNumber, $errorText, $errorFile,$errorLine )
{
throw new ErrorException($errorText, 0, $errorNumber, $errorFile, $errorLine);
});
Dovresti anche impostare
allow_url_use = On
nel tuo php.ini
per interrompere la ricezione di avvisi.