Handling web page errors with PHP

0

Hello!  Is there a possibility that when there is a 404 error, for example, my server send me an email notifying me of the occurrence through php?

    
asked by anonymous 08.08.2016 / 04:30

1 answer

1

If you are using apache you can create a .htaccess file in the root with this content:

ErrorDocument 404 /home/user/public_html/enviar_erro.php
  

Assuming your "root" folder is public_html

The file send_erro.php:

<?php
$headers = "MIME-Version: 1.1\r\n";
$headers .= "Content-type: text/plain; charset=iso-8859-1\r\n";
$headers .= "From: [email protected]\r\n"; // remetente

$mensagem = 'Url não encontrada: ' . $_SERVER['REQUEST_URI'] . PHP_EOL;

if (empty($_SERVER['HTTP_REFERER'])) {
    $mensagem .= 'Referencia: ' . $_SERVER['HTTP_REFERER'] . PHP_EOL;
}

mail("[email protected]", 'Erro HTTP', $mensagem, $headers);

echo '404 error';

And if you want to catch the script errors you can use as in this other response link , create a file called detectar_erro.php :

<?php
class getErrors
{
    //Seu email
    static private $enviarPara = '[email protected]';

    //Destinatário email
    static private $remetente = '[email protected]';

    static private $writeOk = false;

    //Erro personalizado
    static public function writeErros($e)
    {
        if (self::$writeOk === true) {
            return NULL;
        }

        self::$writeOk = true;

        $req = $_SERVER['HTTP_HOST'] . (
            isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] :
                                                    $_SERVER['PHP_SELF']
        );

        $mensagem = 'Erro: ' . $e['message'] . PHP_EOL .
                    'Página: http://' . $req . PHP_EOL .
                    (empty($_SERVER['HTTP_REFERER']) ? '' :
                        ('Referer: http://' . $req . PHP_EOL)
                    ) .
                    'Linha: ' . $e['line'] . PHP_EOL .
                    'Arquivo: ' . $e['file' PHP_EOL;

        $headers .= "Content-type: text/plain; charset=iso-8859-1\r\n";
        $headers .= "From: " . self::$remetente . "\r\n"; // remetente

        mail(self::$email, 'Erro no PHP', $mensagem, $headers);
    }

    static public function putLastError()
    {
        $e = error_get_last();

        if (NULL !== $e) {
            self::writeErros($e);
        }
    }

    static public function handleErr($tipo, $errstr, $errfile, $errline, $detail)
    {
        self::writeErros(
            array(
                'message' => $tipo . ': ' . $errstr,
                'line'    => $errline,
                'file'    => $errfile
            )
        );

        return false;
    }
}

//Configura a classe para o "handle"
set_error_handler(array('getErrors', 'handleErr'), E_ALL|E_STRICT);

//usar 'error_get_last', geralmente em erros "fatais"
register_shutdown_function(array('getErrors', 'putLastError'));

And top all major files like this:

<?php
require_once 'detectar_erro.php';
    
08.08.2016 / 05:00