open file_get_contents failed example error ejemplos php function exception-handling warnings

failed - ¿Cómo puedo manejar la advertencia de la función file_get_contents() en PHP?



file_get_contents(); (16)

Escribí un código PHP como este

$site="http://www.google.com"; $content = file_get_content($site); echo $content;

Pero cuando elimino "http: //" de $site , obtengo la siguiente advertencia:

Advertencia: file_get_contents (www.google.com) [function.file-get-contents]: no se pudo abrir la transmisión:

Intenté try catch pero no funcionó.


Así es como lo hice ... No es necesario el bloque try-catch ... La mejor solución es siempre la más simple ... ¡Disfrútalo!

$content = @file_get_contents("http://www.google.com"); if (strpos($http_response_header[0], "200")) { echo "SUCCESS"; } else { echo "FAILED"; }


Así es como manejo eso:

$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(); }


Cambia el archivo php.ini

allow_url_fopen = On allow_url_include = On


Como 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; }


Debe usar la función file_exists () antes de usar file_get_contents (). De esta forma evitarás la advertencia de php.

$file = "path/to/file"; if(file_exists($file)){ $content = file_get_contents($file); }


Esto intentará obtener los datos; si no funciona, detectará el error y le permitirá hacer todo lo que necesite dentro de la captura.

try { $content = file_get_contents($site); } catch(/Exception $e) { return ''The file was not found''; }


Lo mejor sería establecer sus propios controladores de errores y excepciones, que harán algo útil como registrarlos en un archivo o enviar mensajes críticos por correo electrónico. http://www.php.net/set_error_handler


Mi forma favorita de hacer esto es bastante simple:

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"; }

Encontré esto después de experimentar con el try/catch de @enobrev anterior, pero esto permite un código menos largo (y IMO, más legible). Simplemente usamos error_get_last para obtener el texto del último error, y file_get_contents devuelve falso en caso de error, por lo que un simple "si" puede detectar eso.


Paso 1: verifique el código de retorno: if($content === FALSE) { // handle error here... }

Paso 2: suprima la advertencia colocando un operador de control de errores (es decir, @ ) delante de la llamada a file_get_contents () : $content = @file_get_contents($site);


Podrías usar este 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"; }


Puede anteponer un @: $content = @file_get_contents($site);

Esto suprimirá cualquier advertencia - ¡ use con moderación! . Ver Operadores de Control de Errores.

Edición: cuando eliminas ''http: //'' ya no buscas una página web, sino un archivo en tu disco llamado "www.google ....."


También debe configurar el

allow_url_use = On

en su php.ini para dejar de recibir advertencias.


También puede configurar su controlador de errores como una función anónima que llama a una Exception y usar un try / catch en esa excepción.

set_error_handler( create_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();

Parece un montón de código para detectar un pequeño error, pero si está utilizando excepciones en toda la aplicación, solo tendría que hacerlo una vez, en la parte superior (en un archivo de configuración incluido, por ejemplo), y Convierte todos tus errores en Excepciones a lo largo.


Una alternativa es suprimir el error y también lanzar una excepción que puede detectar más tarde. Esto es especialmente útil si hay varias llamadas a file_get_contents () en su código, ya que no es necesario suprimirlas y manejarlas todas manualmente. En su lugar, se pueden hacer varias llamadas a esta función en un solo bloque 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(); }


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 }


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); });