<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Erro com flags</title> </head> <body> <?php function abrirArquivo($file = NULL) { if (!$file) { return FALSE; } if (!file_exists($file)) { return FALSE; } if (!($retorno = @file_get_contents($file))) { echo '3'; return FALSE; } } $arquivo = abrirArquivo('arquivo'); echo $arquivo; if (!$arquivo) { echo 'Falha ao abrir o arquivo.'; } else { echo 'Arquivo aberto com sucesso.'; } ?> </body> </html>
if (!file_exists($file)) { trigger_error('Arquivo não existe', E_USER_ERROR); return false; } if (!($retorno = @file_get_contents($file))) { trigger_error('O arquivo não pôde ser lido.', E_USER_WARNING); return false; } } //Fim da função abrirArquivo(). function manipulaErro($numero, $mensagem, $arquivo, $linha) { $mensagem = "Arquivo {$arquivo}: linha {$linha} #nro {$numero}: {$mensagem} <br/>"; //gravando o erro em log $log = fopen('erro.log', 'a'); fwrite($log, $mensagem); fclose($log); if ($numero == E_USER_WARNING) { echo $mensagem . '<br/>'; } elseif ($numero == E_USER_ERROR) { echo $mensagem . '<br/>'; die; } } set_error_handler('manipulaErro'); $arquivo = abrirArquivo("a1rquivo.dat"); echo $arquivo; ?> </body> </html>
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Tratamento de exceções</title> </head> <body> <?php function abrirArquivo($file = NULL) { if (!$file) { throw new Exception('Falta o parãmetro de nome do arquivo'); } if (!file_exists($file)) { throw new Exception('Arquivo não existe'); } if (!($retorno = @file_get_contents($file))) { throw new Exception('Não foi possível ler o arquivo'); } return $retorno; } try { $arquivo = abrirArquivo('arquivo.data'); echo $arquivo; } catch (Exception $exc) { echo $exc->getFile() . ' : ' . $exc->getLine() . ' # ' . $exc->getMessage(); } ?> </body> </html>
<head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Erro usando die()</title> </head> <body> <?php function abrirArquivo($file = NULL) { if (!$file) { die('Falta o parâmetro com o nome do arquivo.'); } if (!file_exists($file)) { die('O arquivo não existe.'); } if (!($retorno = @file_get_contents($file))) { die('Impossível ler o arquivo.'); } } //Fim da função abrirArquivo() //usando a função para abrir um arquivo. Escolher uma das alternativas //pois a função die() aborta a execução. echo 'Usando a função sem parâmetros: ' . '<br/>'; $arquivo = abrirArquivo(); echo '<br/>Usando uma função e passando o nome de um arquivo inexistente:<br/>'; $arquivo01 = abrirArquivo('teste'); echo '<br/>Usando a função para abrir o arquivo:'; $arquivo02 = abrirArquivo('arquivo'); ?> </body> </html>