SlideShare uma empresa Scribd logo
1 de 102
Baixar para ler offline
Falhando miseravelmente com PHP
Augusto Pascutti
50min para resolver:
A página ta toda em branco
aqui, de novo.
Usuário do sistema
Como eu faço pro PHP não
exibir esse monte de
E_NOTICE chato?
Desenvolvedor querendo fazer merda
Tem um E_WARNING e alguma
coisa sobre data na página.
Usuário do sistema
Eu entro e dá erro.
Usuários
50 minutos sobre:
Erros e outras mensagens relevantes
Utilidade dessas mensagens
Geração dessas mensagens
Erros
e outras mensagens relevantes
Since the beginning, life has
relied upon the transmission of
messages.
RFC 3164:The BSD syslog Protocol
Severidades
Tipos de mensagens relevantes
Severidades:
• Emergency: deu merda. Sistema inutilizado
• Alert: vai da merda. Faça alguma coisa logo
• Critical: tem tudo pra dar merda
• Error: coisas que não deveriam acontecer
• Warning: aviso.Tome mais cuidado
• Notice: normal, mas ainda assim significativo
• Informational
• Debug
Severidades precisam de um
contexto
Eu mesmo, agora há pouco.
Severidades no PHP
Ou as utilizadas e disponíveis no PHP de todo mundo.
E_ERROR
Um erro sem recuperação, a execução é interrompida.
E_PARSE
Erros de sintaxe, a execução é interrompida.
E_WARNING
Um erro não fatal, a execução continua.
E_NOTICE
Indica um erro muito provável, a execução continua.
E_DEPRECATED
Indica uso de código que deixará de funcionar em
versões futuras.
E_STRICT
Sugestões para melhor interoperabilidade e
compatibilidade futura.
Utilidade
dessas mensagens
Um arquivo de log é como uma
mulher: quanto mais gostosa(o),
mais atenção você presta.
Newton
Baiduspider/2.0; +http://www.baidu.com/search/spider.html)"
123.125.68.79 - - [20/Jun/2012:19:53:24 +0200] "GET / HTTP/1.1" 200 625 "-" "Mozilla/5.0 (compatible;
Baiduspider/2.0; +http://www.baidu.com/search/spider.html)"
178.154.210.252 - - [20/Jun/2012:19:54:10 +0200] "GET /?C=S;O=A HTTP/1.1" 200 663 "-" "Mozilla/5.0
(compatible; YandexBot/3.0; +http://yandex.com/bots)"
74.125.126.102 - - [20/Jun/2012:20:15:28 +0200] "GET / HTTP/1.1" 200 606 "http://www.google.com/url?
sa=t&rct=j&q=error&source=web&cd=1&ved=0CFAQFjAG&url=http%3A%2F%2Fwww.isrolab.com
%2F&ei=GxPiT5PsL4e04AHPtgE&usg=AFQjCNHnmjmdkUV584ORIpOXz7zAPX0UHQ" "Mozilla/4.0 (compatible; MSIE 7.0; Windows
NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; InfoPath.2; .NET
CLR 3.0.4506.2152; .NET CLR 3.5.30729)"
74.125.126.103 - - [20/Jun/2012:20:15:29 +0200] "GET /icons/blank.gif HTTP/1.1" 200 383 "http://
www.isrolab.com/" "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR
2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; InfoPath.2; .NET CLR 3.0.4506.2152; .NET CLR
3.5.30729)"
74.125.126.93 - - [20/Jun/2012:20:15:29 +0200] "GET /icons/folder.gif HTTP/1.1" 200 460 "http://
www.isrolab.com/" "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR
2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; InfoPath.2; .NET CLR 3.0.4506.2152; .NET CLR
3.5.30729)"
74.125.126.82 - - [20/Jun/2012:20:15:30 +0200] "GET /favicon.ico HTTP/1.1" 404 449 "-" "Mozilla/4.0
(compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR
3.5.21022; InfoPath.2; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)"
184.82.92.239 - - [20/Jun/2012:21:03:44 +0200] "GET /logs/access.log HTTP/1.1" 200 2519 "http://isrolab.com/"
"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; Mozilla/4.0 (compatible; MSIE 6.0; Windows NT
5.1; SV1) ; .NET CLR 3.5.30729)"
173.236.21.106 - - [20/Jun/2012:21:16:22 +0200] "GET /robots.txt HTTP/1.0" 404 488 "-" "Mozilla/5.0
(compatible; MJ12bot/v1.4.3; http://www.majestic12.co.uk/bot.php?+)"
173.236.21.106 - - [20/Jun/2012:21:16:23 +0200] "GET / HTTP/1.0" 200 621 "-" "Mozilla/5.0 (compatible;
MJ12bot/v1.4.3; http://www.majestic12.co.uk/bot.php?+)"
213.186.122.2 - - [20/Jun/2012:21:27:53 +0200] "GET /logs/?C=D;O=D HTTP/1.1" 200 658 "-" "Mozilla/5.0
(compatible; AhrefsBot/3.0; +http://ahrefs.com/robot/)"
66.249.72.65 - - [20/Jun/2012:21:28:00 +0200] "GET /robots.txt HTTP/1.1" 404 508 "-" "Mozilla/5.0 (compatible;
Googlebot/2.1; +http://www.google.com/bot.html)"
66.249.72.65 - - [20/Jun/2012:21:28:00 +0200] "GET /logs/ HTTP/1.1" 200 723 "-" "Mozilla/5.0 (compatible;
Googlebot/2.1; +http://www.google.com/bot.html)"
123.125.71.44 - - [20/Jun/2012:21:38:57 +0200] "GET / HTTP/1.1" 200 913 "-" "Mozilla/5.0 (compatible;
Baiduspider/2.0; +http://www.baidu.com/search/spider.html)"
220.181.108.88 - - [20/Jun/2012:21:39:48 +0200] "GET / HTTP/1.1" 200 913 "-" "Mozilla/5.0 (compatible;
Baiduspider/2.0; +http://www.baidu.com/search/spider.html)"
178.154.210.252 - - [20/Jun/2012:21:45:12 +0200] "GET /logs/ HTTP/1.1" 200 728 "-" "Mozilla/5.0 (compatible;
YandexBot/3.0; +http://yandex.com/bots)"
139.18.2.209 - - [20/Jun/2012:22:31:43 +0200] "GET / HTTP/1.1" 200 912 "-" "findlinks/2.6 (+http://
wortschatz.uni-leipzig.de/findlinks/)"
Pegue já seu exemplo!
!g filetype:log access.log
Eu não preciso disso, já tenho o
Analytics em todas as páginas.
Algum desenvolvedor
Como usar isso?
O (meu) jeito *nix
word, line, character, and byte count
wc
#!/bin/bash
[~/Apache] $ wc -l access.log
65063 access.log
print lines matching a pattern
grep
#!/bin/bash
[~/Apache] $ wc -l access.log
65063 access.log
[~/Apache] $ grep "HTTP/1.1" access.log | wc -l
52129
#!/bin/bash
[~/Apache] $ wc -l access.log
65063 access.log
[~/Apache] $ grep "HTTP/1.1" access.log | wc -l
52129
[~/Apache] $ grep "HTTP/1.0" access.log | wc -l
13007
#!/bin/bash
[~/Apache] $ wc -l access.log
65063 access.log
[~/Apache] $ grep "HTTP/1.1" access.log | wc -l
52129
[~/Apache] $ grep "HTTP/1.0" access.log | wc -l
13007
[~/Apache] $ grep -v "HTTP/1.1" access.log | grep -v "HTTP/1.0"
114.66.65.89 - - [24/Dec/2012:07:46:27 +0100] "GET /logs/
access.log vxc2xa4Nxd41.0" 200 1963700 "http://
www.isrolab.com/" "Mozilla/5.0 (Windows NT 6.1; rv:2.0b7pre)
Gecko/20100921 Firefox/4.0b7pre"
#!/bin/bash
[~/Apache] $ wc -l access.log
65063 access.log
[~/Apache] $ grep "HTTP/1.1" access.log | wc -l
52129
[~/Apache] $ grep "HTTP/1.0" access.log | wc -l
13007
[~/Apache] $ grep -v "HTTP/1.1" access.log | grep -v "HTTP/1.0"
114.66.65.89 - - [24/Dec/2012:07:46:27 +0100] "GET /logs/
access.log vxc2xa4Nxd41.0" 200 1963700 "http://
www.isrolab.com/" "Mozilla/5.0 (Windows NT 6.1; rv:2.0b7pre)
Gecko/20100921 Firefox/4.0b7pre"
Procura isso no Analytics agora.
Augusto Pascutti
display first lines of a file
head
#!/bin/bash
[~/Apache]$ head -n 1 access.log
1.202.218.8 - - [20/Jun/2012:19:05:12 +0200] "GET /robots.txt
HTTP/1.0" 404 492 "-" ""Mozilla/5.0"
pattern-directed scanning and processing language
awk
#!/bin/bash
[~/Apache]$ head -n 1 access.log
1.202.218.8 - - [20/Jun/2012:19:05:12 +0200] "GET /robots.txt
HTTP/1.0" 404 492 "-" ""Mozilla/5.0"
[~/Apache]$ head -n 1 access.log | awk '{print $1}'
1.202.218.8
#!/bin/bash
[~/Apache]$ head -n 1 access.log
1.202.218.8 - - [20/Jun/2012:19:05:12 +0200] "GET /robots.txt
HTTP/1.0" 404 492 "-" ""Mozilla/5.0"
[~/Apache]$ head -n 1 access.log | awk '{print $1}'
1.202.218.8
[~/Apache]$ awk '{print $1}' access.log | head -n 10
1.202.218.8
208.115.113.91
123.125.71.20
220.181.108.101
123.125.68.79
178.154.210.252
74.125.126.102
74.125.126.103
74.125.126.93
74.125.126.82
sort lines of text files
sort
#!/bin/bash
[~/Apache]$ awk '{print $1}' access.log | head -n 5
1.202.218.8
208.115.113.91
123.125.71.20
220.181.108.101
123.125.68.79
#!/bin/bash
[~/Apache]$ awk '{print $1}' access.log | head -n 5
1.202.218.8
208.115.113.91
123.125.71.20
220.181.108.101
123.125.68.79
[~/Apache]$ awk '{print $1}' access.log | head -n 5 | sort
1.202.218.8
123.125.68.79
123.125.71.20
208.115.113.91
220.181.108.101
report or filter out repeated lines in a file
uniq
#!/bin/bash
[~/Apache]$ awk '{print $1}' access.log | sort | uniq | wc -l
7967
#!/bin/bash
[~/Apache]$ awk '{print $1}' *.log | sort | uniq | wc -l
7967
[~/Apache]$ awk '{print $1}' *.log | sort | uniq | head -n 10
1.0.250.121
1.179.147.2
1.2.209.130
1.2.215.151
1.2.216.110
1.2.217.90
1.202.218.13
1.202.218.14
1.202.218.15
1.202.218.21
Quais os IPs que mais acessaram
o access.log dele?
Já que sabemos que não fomos os únicos.
Você já ouviu falar em “bash
script”, certo?
Eu
#!/bin/bash
[~/Apache]$ for ip in `awk '{print $1}' *.log | sort | uniq`; do
> count=`grep “$ip” access.log | grep 'access.log' | wc -l`;
> echo "$count $ip" >> ip-safadenhos.txt;
> done;
#!/bin/bash
[~/Apache]$ wc -l *.txt
9479 ip-safadenhos.txt
#!/bin/bash
[~/Apache]$ wc -l *.txt
9479 ip-safadenhos.txt
[~/Apache]$ awk '{print $1}' *.txt | grep -v 0 | wc -l
5619
Top 10
#!/bin/bash
[~/Apache]$ sort -nr ip-safadenhos.txt | head -n 10
246 88.250.57.232
184 216.151.130.179
121 88.190.16.36
90 199.59.56.24
84 80.93.217.38
73 216.152.251.7
71 89.233.105.125
68 120.196.161.251
68 120.196.161.251
58 190.254.21.236
Como usar isso no dia a dia?
Já que ninguém tem tempo sobrando.
Pegue já seu outro exemplo!
!g filetype:log error.log E_ERROR
Log do PHP
Via linha de comando.
LC_Page_Admin.php(69)] from 126.29.228.69
login_id = ()[acf83d9069c4c9036fa852909503b631]
2013/01/30 00:49:03 [/hiroshima-gift.co.jp/html/admin/index.php] Fatal error(E_ERROR): Call to a member
function doAction() on a non-object on [/home/bravecreate/www/hiroshima-gift.co.jp/data/class/pages/admin/
LC_Page_Admin.php(69)] from 126.29.228.69
login_id = ()[acf83d9069c4c9036fa852909503b631]
2013/01/30 00:50:38 [/hiroshima-gift.co.jp/html/admin/index.php] Fatal error(E_ERROR): Call to a member
function doAction() on a non-object on [/home/bravecreate/www/hiroshima-gift.co.jp/data/class/pages/admin/
LC_Page_Admin.php(69)] from 126.29.228.69
login_id = ()[acf83d9069c4c9036fa852909503b631]
2013/01/30 00:50:59 [/hiroshima-gift.co.jp/html/admin/index.php] Fatal error(E_ERROR): Call to a member
function doAction() on a non-object on [/home/bravecreate/www/hiroshima-gift.co.jp/data/class/pages/admin/
LC_Page_Admin.php(69)] from 126.29.228.69
login_id = ()[acf83d9069c4c9036fa852909503b631]
2013/04/02 14:09:39 [/hiroshima-gift.co.jp/html/index.php] Fatal error(E_USER_ERROR):
DB処çê †ãÅ §ã‚¨ãƒ©ãƒ¼ãÅ Œç™ºç”ŸãÅ —ãÅ ¾ãÅ —ãÅ Ÿã€‚
SQL: [SET SESSION storage_engine = InnoDB]
PlaceHolder: [array (
)]
MDB2 Error: insufficient permissions
_doQuery: [Error message: Could not select the database: bravecreate_nagasakiya_ec]
[Last executed query: SET SESSION storage_engine = InnoDB]
[Native code: 1044]
[Native message: Access denied for user 'bravecreate'@'%' to database 'bravecreate_nagasakiya_ec']
on [/home/bravecreate/www/hiroshima-gift.co.jp/data/class/SC_Query.php(1008)] from 66.249.74.233
customer_id =
/home/bravecreate/www/hiroshima-gift.co.jp/html/index.php(32): LC_Page_Index_Ex->init
/home/bravecreate/www/hiroshima-gift.co.jp/data/class_extends/page_extends/LC_Page_Index_Ex.php(47):
LC_Page_Index->init
/home/bravecreate/www/hiroshima-gift.co.jp/data/class/pages/LC_Page_Index.php(45): LC_Page->init
/home/bravecreate/www/hiroshima-gift.co.jp/data/class/pages/LC_Page.php(97): SC_Helper_PageLayout-
>sfGetPageLayout
/home/bravecreate/www/hiroshima-gift.co.jp/data/class/helper/SC_Helper_PageLayout.php(54):
SC_Helper_PageLayout->getPageProperties
/home/bravecreate/www/hiroshima-gift.co.jp/data/class/helper/SC_Helper_PageLayout.php(112):
SC_Query::getSingletonInstance
/home/bravecreate/www/hiroshima-gift.co.jp/data/class/SC_Query.php(104): SC_Query->__construct
/home/bravecreate/www/hiroshima-gift.co.jp/data/class/SC_Query.php(88): SC_DB_DBFactory_MYSQL->initObjQuery
/home/bravecreate/www/hiroshima-gift.co.jp/data/class/db/dbfactory/SC_DB_DBFactory_MYSQL.php(323): SC_Query-
>exec
/home/bravecreate/www/hiroshima-gift.co.jp/data/class/SC_Query.php(231): SC_Query->query
/home/bravecreate/www/hiroshima-gift.co.jp/data/class/SC_Query.php(814): SC_Query->execute
/home/bravecreate/www/hiroshima-gift.co.jp/data/class/SC_Query.php(971): SC_Query->error
#!/bin/bash
[~/PHP]$ awk '/(E_[A-Z])/ {print $5}' error.log | sort | uniq -c
24 error(E_ERROR):
15 error(E_USER_ERROR):
#!/bin/bash
[~/PHP]$ awk '/(E_[A-Z])/ {print $5}' error.log | sort | uniq -c
24 error(E_ERROR):
15 error(E_USER_ERROR):
[~/PHP]$ awk -F: '/E_ERROR/ {print $4}' error.log | sort | uniq
Call to a member function doAction() on a non-object on [/home/
bravecreate/www/hiroshima-gift.co.jp/data/class/
SC_View.php(137)]
Call to a member function doAction() on a non-object on [/home/
bravecreate/www/hiroshima-gift.co.jp/data/class/
SC_View.php(137)]
Call to a member function doAction() on a non-object on [/home/
bravecreate/www/hiroshima-gift.co.jp/data/class/pages/admin/
LC_Page_Admin.php(69)]
Geração
dessas mensagens
Configurações
Ou coisas que podem provocar diferentes resultados
no seu PHP.
display_errors
Você quer ver esses erros?
ini_set(‘display_errors’,‘On’)
Exibe erros em HTML para usuário.
(Ideal para ambiente de desenvolvimento)
ini_set(‘display_errors’,‘Off’)
Não exibe erros.
(Ideal para ambiente de produção)
log_errors
Envia os erros para o arquivo de log configurado.
ini_set(‘log_errors’,‘On’)
Salva os erros no arquivo de log.
(Ideal em todos os ambientes)
ini_set(‘log_errors’,‘Off’)
Não salva erros no arquivo de log.
(Não sei porque você irá querer isso)
error_log
Onde você deseja que o arquivo de log seja gerado?
error_reporting
Quais severidades utilizar?
1 <?php
2 ini_set('display_errors', 1);
3 error_reporting(E_ALL);
4
5 if ($_POST['user']) {
6 // ...
7 }
8 /**
9 * Output:
10 *
11 * PHP Notice: Undefined index: user in notices.php on line 5
12 */
1 <?php
2 ini_set('display_errors', 1);
3 error_reporting(E_ALL ^ E_NOTICE);
4
5 if ($_POST['user']) {
6 // ...
7 }
8 /**
9 * Output:
10 *
11 */
1 <?php
2 ini_set('display_errors', 1);
3 error_reporting(E_ALL);
4
5 echo date('l').PHP_EOL;
6
7 date_default_timezone_set('America/Sao_Paulo');
8
9 echo date('l').PHP_EOL;
10
11 /**
12 * Output:
13 *
14 * PHP Warning: date(): It is not safe to rely on the system's
15 * timezone settings. You are *required* to use the date.timezone
16 * setting or the date_default_timezone_set() function.
17 * In case you used any of those methods and you are still getting
18 * this warning, you most likely misspelled the timezone identifier.
19 * We selected the timezone 'UTC' for now, but please set date.timezone
20 * to select your timezone. in date.php on line 5
21 *
22 * Saturday
23 * Saturday
24 */
1 <?php
2 ini_set('display_errors', 1);
3 error_reporting(E_ALL);
4
5 include 'nao-existe.php';
6
7 /**
8 * Output:
9 *
10 * PHP Warning: include(nao-existe.php): failed to open stream:
11 * No such file or directory in warning.php on line 5
12 */
1 <?php
2 ini_set('display_errors', 1);
3 error_reporting(E_ALL);
4
5 require 'nao-existe.php';
6 /**
7 * Output:
8 *
9 * PHP Warning: require(nao-existe.php): failed to open stream:
10 * No such file or directory in warning.php on line 5
11 *
12 * Fatal error: require(): Failed opening required
13 * 'nao-existe.php' in error.php on line 5
14 */
Procedural
trigger_error()
Gera uma mensagem de determinada severidade.
1 <?php
2 date_default_timezone_set('America/Sao_Paulo');
3 error_reporting(-1);
4 ini_set('log_errors', 1);
5 ini_set('error_log', 'duh.log');
6
7 define('APP_ENV', getenv('APP_ENV') ?: 'dev');
8 switch (APP_ENV) {
9 case 'live':
10 ini_set('display_errors', 0);
11 break;
12 default:
13 ini_set('display_errors', 1);
14 break;
15 }
16
17 if (false === extension_loaded('xdebug')) {
18 trigger_error('Conhece o xDebug?', X_USER_NOTICE);
19 }
20
21 if (false === version_compare($current=PHP_VERSION, $required='6.4.0', '>=')) {
22 $msg = sprintf('Versão mínima do PHP requerida %s. (%s)', $required, $current);
23 trigger_error($msg, E_USER_ERROR);
24 unset($required, $current);
25 }
26
27 if (false === file_exists($autoload = 'vendor/autoload.php')) {
28 trigger_error('Por favor, rode a instale com `make install`.', E_USER_ERROR);
29 }
30
error_log()
Envia mensagem para o log de erros.
1 <?php
2 ini_set('display_errors', 0);
3 ini_set('log_errors', 1);
4 error_reporting(-1);
5
6 error_log('É nóis na fita!');
7 error_log('Não me deixa cair no SPAM!', 1, 'a@a.com');
1 <?php
2 ini_set('display_errors', 0);
3 ini_set('log_errors', 1);
4 error_reporting(-1);
5
6 error_log('É nóis na fita!');
7 error_log('Não me deixa cair no SPAM!', 1, 'a@a.com');
Exceptions
Erros num paradigma Orientado a Objetos
1 <?php
2
3 namespace Math;
4
5 class Operation
6 {
7 public static function sum()
8 {
9 $args = func_get_args();
10 $result = 0;
11 foreach ($args as $arg) {
12 if (false == is_int($arg)) {
13 $msg = 'Somente inteiros permitidos';
14 throw new InvalidArgumentException($msg);
15 }
16 $result += (integer) $arg;
17 }
18
19 return $result;
20 }
21 }
22
23 echo Operation::sum(1,2,3,5.0);
1 <?php
2
3 namespace Math;
4
5 require 'math.php'; // use autoload, por favor!
6
7 use InvalidArgumentException;
8 use Exception;
9
10 class Grades
11 {
12 public static function average($prova1, $prova2, $prova3)
13 {
14 try {
15 $total = Operation::sum($prova1, $prova2, $prova3);
16 } catch (InvalidArgumentException $e) {
17 $msg = 'Alguma nota esta errada.';
18 throw new InvalidArgumentException($msg, null, $e);
19 } catch (Exception $e) {
20 $msg = 'Calcular media de notas.';
21 throw new RuntimeException($msg, null, $e);
22 }
23 }
24 }
25
26 echo Grades::average(10, 10, 9.8);
SPL Exceptions
http://php.net/spl
Quer saber mais?
Acabou de sair do forno.
PSR-3
Um padrão de logs para o PHP
Concluindo
Falhando miseravelmente com PHP
Uma re-interpretação do título.
Falhando miseravelmente com PHP
Erros e mensagens do sistema DEVEM ser expostos
sempre que possível.
Falhando miseravelmente com PHP
Expostos pra todos os desenvolvedores (e administradores)
envolvidos na manutenção do sistema, não para usuários.
Muito menos para toda internet.
Falhando miseravelmente com PHP
PELO MENOS os gerados pelo próprio PHP.
Dúvidas?
ou críticas, sugestões, declarações, conjecturações, etc...

Mais conteúdo relacionado

Semelhante a Falhando miseralvelmente com PHP

Oficina postgresql avançado_consegi2010
Oficina postgresql avançado_consegi2010Oficina postgresql avançado_consegi2010
Oficina postgresql avançado_consegi2010
Fabrízio Mello
 
LabMM3 - Aula teórica 04
LabMM3 - Aula teórica 04LabMM3 - Aula teórica 04
LabMM3 - Aula teórica 04
Carlos Santos
 
Alterar password linux user pam autentication
Alterar password linux user   pam autenticationAlterar password linux user   pam autentication
Alterar password linux user pam autentication
Carlos Eduardo
 

Semelhante a Falhando miseralvelmente com PHP (20)

Adeus Wordpress. Ola Pelican!
Adeus Wordpress. Ola Pelican!Adeus Wordpress. Ola Pelican!
Adeus Wordpress. Ola Pelican!
 
Oficina postgresql avançado_consegi2010
Oficina postgresql avançado_consegi2010Oficina postgresql avançado_consegi2010
Oficina postgresql avançado_consegi2010
 
TDC 2016 - PHP7
TDC 2016 - PHP7TDC 2016 - PHP7
TDC 2016 - PHP7
 
Docker na vida real
Docker na vida realDocker na vida real
Docker na vida real
 
Puppet – Torne Seu Datacenter áGil
Puppet – Torne Seu Datacenter áGilPuppet – Torne Seu Datacenter áGil
Puppet – Torne Seu Datacenter áGil
 
Organizando a casa
Organizando a casaOrganizando a casa
Organizando a casa
 
Organizandoacasa 120316203302-phpapp02
Organizandoacasa 120316203302-phpapp02Organizandoacasa 120316203302-phpapp02
Organizandoacasa 120316203302-phpapp02
 
Como ser programador durante o dia e mesmo assim dormir bem à noite
Como ser programador durante o dia e mesmo assim dormir bem à noiteComo ser programador durante o dia e mesmo assim dormir bem à noite
Como ser programador durante o dia e mesmo assim dormir bem à noite
 
Project HA
Project HAProject HA
Project HA
 
Efficient rails
Efficient railsEfficient rails
Efficient rails
 
Introdução ao framework CakePHP
Introdução ao framework CakePHPIntrodução ao framework CakePHP
Introdução ao framework CakePHP
 
LabMM3 - Aula teórica 04
LabMM3 - Aula teórica 04LabMM3 - Aula teórica 04
LabMM3 - Aula teórica 04
 
Sapo Sessions PHP
Sapo Sessions PHPSapo Sessions PHP
Sapo Sessions PHP
 
Logs, pra que te quero! @ Meetup PHP Vale
Logs, pra que te quero! @ Meetup PHP ValeLogs, pra que te quero! @ Meetup PHP Vale
Logs, pra que te quero! @ Meetup PHP Vale
 
Minicurso Web. Front-end e HTML5 (parte 2)
Minicurso Web. Front-end e HTML5 (parte 2)Minicurso Web. Front-end e HTML5 (parte 2)
Minicurso Web. Front-end e HTML5 (parte 2)
 
Alterar password linux user pam autentication
Alterar password linux user   pam autenticationAlterar password linux user   pam autentication
Alterar password linux user pam autentication
 
XSS Desvendado
XSS DesvendadoXSS Desvendado
XSS Desvendado
 
DevDay - O elo perdido: sincronizando webapps
DevDay - O elo perdido: sincronizando webappsDevDay - O elo perdido: sincronizando webapps
DevDay - O elo perdido: sincronizando webapps
 
Rodando PHP em um container Java
Rodando PHP em um container JavaRodando PHP em um container Java
Rodando PHP em um container Java
 
Implementando PSR-3 com Monolog @ PHP Community Summit 2019
Implementando PSR-3 com Monolog @ PHP Community Summit 2019Implementando PSR-3 com Monolog @ PHP Community Summit 2019
Implementando PSR-3 com Monolog @ PHP Community Summit 2019
 

Mais de Augusto Pascutti

Orientação a Objetos com PHP
Orientação a Objetos com PHPOrientação a Objetos com PHP
Orientação a Objetos com PHP
Augusto Pascutti
 

Mais de Augusto Pascutti (17)

Errors
ErrorsErrors
Errors
 
Melhorando sua API com DSLs
Melhorando sua API com DSLsMelhorando sua API com DSLs
Melhorando sua API com DSLs
 
Logs: O que comem, onde vivem e como se reproduzem.
Logs: O que comem, onde vivem e como se reproduzem.Logs: O que comem, onde vivem e como se reproduzem.
Logs: O que comem, onde vivem e como se reproduzem.
 
TDD - Test Driven Development (em PHP)
TDD - Test Driven Development (em PHP)TDD - Test Driven Development (em PHP)
TDD - Test Driven Development (em PHP)
 
SfCon: Test Driven Development
SfCon: Test Driven DevelopmentSfCon: Test Driven Development
SfCon: Test Driven Development
 
Orientação a objetos v2
Orientação a objetos v2Orientação a objetos v2
Orientação a objetos v2
 
Como escalar aplicações PHP
Como escalar aplicações PHPComo escalar aplicações PHP
Como escalar aplicações PHP
 
The small things
The small thingsThe small things
The small things
 
Somos jardineiros
Somos jardineirosSomos jardineiros
Somos jardineiros
 
PHP - O que, porquê e como
PHP - O que, porquê e comoPHP - O que, porquê e como
PHP - O que, porquê e como
 
Frameworks PHP
Frameworks PHPFrameworks PHP
Frameworks PHP
 
Testar é bom, integrar é ainda melhor
Testar é bom, integrar é ainda melhorTestar é bom, integrar é ainda melhor
Testar é bom, integrar é ainda melhor
 
PHPSC Conference 2010 - Testar é bom, integrar é melhor ainda!
PHPSC Conference 2010 - Testar é bom, integrar é melhor ainda!PHPSC Conference 2010 - Testar é bom, integrar é melhor ainda!
PHPSC Conference 2010 - Testar é bom, integrar é melhor ainda!
 
Segurança em PHP
Segurança em PHPSegurança em PHP
Segurança em PHP
 
Orientação a Objetos com PHP
Orientação a Objetos com PHPOrientação a Objetos com PHP
Orientação a Objetos com PHP
 
Boas Práticas, Práticas !
Boas Práticas, Práticas !Boas Práticas, Práticas !
Boas Práticas, Práticas !
 
Mitos do PHP
Mitos do PHPMitos do PHP
Mitos do PHP
 

Último

Assessement Boas Praticas em Kubernetes.pdf
Assessement Boas Praticas em Kubernetes.pdfAssessement Boas Praticas em Kubernetes.pdf
Assessement Boas Praticas em Kubernetes.pdf
Natalia Granato
 

Último (6)

Assessement Boas Praticas em Kubernetes.pdf
Assessement Boas Praticas em Kubernetes.pdfAssessement Boas Praticas em Kubernetes.pdf
Assessement Boas Praticas em Kubernetes.pdf
 
ATIVIDADE 1 - GCOM - GESTÃO DA INFORMAÇÃO - 54_2024.docx
ATIVIDADE 1 - GCOM - GESTÃO DA INFORMAÇÃO - 54_2024.docxATIVIDADE 1 - GCOM - GESTÃO DA INFORMAÇÃO - 54_2024.docx
ATIVIDADE 1 - GCOM - GESTÃO DA INFORMAÇÃO - 54_2024.docx
 
Padrões de Projeto: Proxy e Command com exemplo
Padrões de Projeto: Proxy e Command com exemploPadrões de Projeto: Proxy e Command com exemplo
Padrões de Projeto: Proxy e Command com exemplo
 
Boas práticas de programação com Object Calisthenics
Boas práticas de programação com Object CalisthenicsBoas práticas de programação com Object Calisthenics
Boas práticas de programação com Object Calisthenics
 
ATIVIDADE 1 - LOGÍSTICA EMPRESARIAL - 52_2024.docx
ATIVIDADE 1 - LOGÍSTICA EMPRESARIAL - 52_2024.docxATIVIDADE 1 - LOGÍSTICA EMPRESARIAL - 52_2024.docx
ATIVIDADE 1 - LOGÍSTICA EMPRESARIAL - 52_2024.docx
 
ATIVIDADE 1 - CUSTOS DE PRODUÇÃO - 52_2024.docx
ATIVIDADE 1 - CUSTOS DE PRODUÇÃO - 52_2024.docxATIVIDADE 1 - CUSTOS DE PRODUÇÃO - 52_2024.docx
ATIVIDADE 1 - CUSTOS DE PRODUÇÃO - 52_2024.docx
 

Falhando miseralvelmente com PHP

  • 1. Falhando miseravelmente com PHP Augusto Pascutti
  • 3. A página ta toda em branco aqui, de novo. Usuário do sistema
  • 4. Como eu faço pro PHP não exibir esse monte de E_NOTICE chato? Desenvolvedor querendo fazer merda
  • 5. Tem um E_WARNING e alguma coisa sobre data na página. Usuário do sistema
  • 6. Eu entro e dá erro. Usuários
  • 7. 50 minutos sobre: Erros e outras mensagens relevantes Utilidade dessas mensagens Geração dessas mensagens
  • 9. Since the beginning, life has relied upon the transmission of messages. RFC 3164:The BSD syslog Protocol
  • 11. Severidades: • Emergency: deu merda. Sistema inutilizado • Alert: vai da merda. Faça alguma coisa logo • Critical: tem tudo pra dar merda • Error: coisas que não deveriam acontecer • Warning: aviso.Tome mais cuidado • Notice: normal, mas ainda assim significativo • Informational • Debug
  • 12. Severidades precisam de um contexto Eu mesmo, agora há pouco.
  • 13. Severidades no PHP Ou as utilizadas e disponíveis no PHP de todo mundo.
  • 14. E_ERROR Um erro sem recuperação, a execução é interrompida.
  • 15. E_PARSE Erros de sintaxe, a execução é interrompida.
  • 16. E_WARNING Um erro não fatal, a execução continua.
  • 17. E_NOTICE Indica um erro muito provável, a execução continua.
  • 18. E_DEPRECATED Indica uso de código que deixará de funcionar em versões futuras.
  • 19. E_STRICT Sugestões para melhor interoperabilidade e compatibilidade futura.
  • 21. Um arquivo de log é como uma mulher: quanto mais gostosa(o), mais atenção você presta. Newton
  • 22. Baiduspider/2.0; +http://www.baidu.com/search/spider.html)" 123.125.68.79 - - [20/Jun/2012:19:53:24 +0200] "GET / HTTP/1.1" 200 625 "-" "Mozilla/5.0 (compatible; Baiduspider/2.0; +http://www.baidu.com/search/spider.html)" 178.154.210.252 - - [20/Jun/2012:19:54:10 +0200] "GET /?C=S;O=A HTTP/1.1" 200 663 "-" "Mozilla/5.0 (compatible; YandexBot/3.0; +http://yandex.com/bots)" 74.125.126.102 - - [20/Jun/2012:20:15:28 +0200] "GET / HTTP/1.1" 200 606 "http://www.google.com/url? sa=t&rct=j&q=error&source=web&cd=1&ved=0CFAQFjAG&url=http%3A%2F%2Fwww.isrolab.com %2F&ei=GxPiT5PsL4e04AHPtgE&usg=AFQjCNHnmjmdkUV584ORIpOXz7zAPX0UHQ" "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; InfoPath.2; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)" 74.125.126.103 - - [20/Jun/2012:20:15:29 +0200] "GET /icons/blank.gif HTTP/1.1" 200 383 "http:// www.isrolab.com/" "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; InfoPath.2; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)" 74.125.126.93 - - [20/Jun/2012:20:15:29 +0200] "GET /icons/folder.gif HTTP/1.1" 200 460 "http:// www.isrolab.com/" "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; InfoPath.2; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)" 74.125.126.82 - - [20/Jun/2012:20:15:30 +0200] "GET /favicon.ico HTTP/1.1" 404 449 "-" "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; InfoPath.2; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)" 184.82.92.239 - - [20/Jun/2012:21:03:44 +0200] "GET /logs/access.log HTTP/1.1" 200 2519 "http://isrolab.com/" "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) ; .NET CLR 3.5.30729)" 173.236.21.106 - - [20/Jun/2012:21:16:22 +0200] "GET /robots.txt HTTP/1.0" 404 488 "-" "Mozilla/5.0 (compatible; MJ12bot/v1.4.3; http://www.majestic12.co.uk/bot.php?+)" 173.236.21.106 - - [20/Jun/2012:21:16:23 +0200] "GET / HTTP/1.0" 200 621 "-" "Mozilla/5.0 (compatible; MJ12bot/v1.4.3; http://www.majestic12.co.uk/bot.php?+)" 213.186.122.2 - - [20/Jun/2012:21:27:53 +0200] "GET /logs/?C=D;O=D HTTP/1.1" 200 658 "-" "Mozilla/5.0 (compatible; AhrefsBot/3.0; +http://ahrefs.com/robot/)" 66.249.72.65 - - [20/Jun/2012:21:28:00 +0200] "GET /robots.txt HTTP/1.1" 404 508 "-" "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)" 66.249.72.65 - - [20/Jun/2012:21:28:00 +0200] "GET /logs/ HTTP/1.1" 200 723 "-" "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)" 123.125.71.44 - - [20/Jun/2012:21:38:57 +0200] "GET / HTTP/1.1" 200 913 "-" "Mozilla/5.0 (compatible; Baiduspider/2.0; +http://www.baidu.com/search/spider.html)" 220.181.108.88 - - [20/Jun/2012:21:39:48 +0200] "GET / HTTP/1.1" 200 913 "-" "Mozilla/5.0 (compatible; Baiduspider/2.0; +http://www.baidu.com/search/spider.html)" 178.154.210.252 - - [20/Jun/2012:21:45:12 +0200] "GET /logs/ HTTP/1.1" 200 728 "-" "Mozilla/5.0 (compatible; YandexBot/3.0; +http://yandex.com/bots)" 139.18.2.209 - - [20/Jun/2012:22:31:43 +0200] "GET / HTTP/1.1" 200 912 "-" "findlinks/2.6 (+http:// wortschatz.uni-leipzig.de/findlinks/)"
  • 23. Pegue já seu exemplo! !g filetype:log access.log
  • 24. Eu não preciso disso, já tenho o Analytics em todas as páginas. Algum desenvolvedor
  • 25. Como usar isso? O (meu) jeito *nix
  • 26.
  • 27. word, line, character, and byte count wc
  • 28. #!/bin/bash [~/Apache] $ wc -l access.log 65063 access.log
  • 29. print lines matching a pattern grep
  • 30. #!/bin/bash [~/Apache] $ wc -l access.log 65063 access.log [~/Apache] $ grep "HTTP/1.1" access.log | wc -l 52129
  • 31. #!/bin/bash [~/Apache] $ wc -l access.log 65063 access.log [~/Apache] $ grep "HTTP/1.1" access.log | wc -l 52129 [~/Apache] $ grep "HTTP/1.0" access.log | wc -l 13007
  • 32. #!/bin/bash [~/Apache] $ wc -l access.log 65063 access.log [~/Apache] $ grep "HTTP/1.1" access.log | wc -l 52129 [~/Apache] $ grep "HTTP/1.0" access.log | wc -l 13007 [~/Apache] $ grep -v "HTTP/1.1" access.log | grep -v "HTTP/1.0" 114.66.65.89 - - [24/Dec/2012:07:46:27 +0100] "GET /logs/ access.log vxc2xa4Nxd41.0" 200 1963700 "http:// www.isrolab.com/" "Mozilla/5.0 (Windows NT 6.1; rv:2.0b7pre) Gecko/20100921 Firefox/4.0b7pre"
  • 33. #!/bin/bash [~/Apache] $ wc -l access.log 65063 access.log [~/Apache] $ grep "HTTP/1.1" access.log | wc -l 52129 [~/Apache] $ grep "HTTP/1.0" access.log | wc -l 13007 [~/Apache] $ grep -v "HTTP/1.1" access.log | grep -v "HTTP/1.0" 114.66.65.89 - - [24/Dec/2012:07:46:27 +0100] "GET /logs/ access.log vxc2xa4Nxd41.0" 200 1963700 "http:// www.isrolab.com/" "Mozilla/5.0 (Windows NT 6.1; rv:2.0b7pre) Gecko/20100921 Firefox/4.0b7pre"
  • 34.
  • 35. Procura isso no Analytics agora. Augusto Pascutti
  • 36. display first lines of a file head
  • 37. #!/bin/bash [~/Apache]$ head -n 1 access.log 1.202.218.8 - - [20/Jun/2012:19:05:12 +0200] "GET /robots.txt HTTP/1.0" 404 492 "-" ""Mozilla/5.0"
  • 38. pattern-directed scanning and processing language awk
  • 39. #!/bin/bash [~/Apache]$ head -n 1 access.log 1.202.218.8 - - [20/Jun/2012:19:05:12 +0200] "GET /robots.txt HTTP/1.0" 404 492 "-" ""Mozilla/5.0" [~/Apache]$ head -n 1 access.log | awk '{print $1}' 1.202.218.8
  • 40. #!/bin/bash [~/Apache]$ head -n 1 access.log 1.202.218.8 - - [20/Jun/2012:19:05:12 +0200] "GET /robots.txt HTTP/1.0" 404 492 "-" ""Mozilla/5.0" [~/Apache]$ head -n 1 access.log | awk '{print $1}' 1.202.218.8 [~/Apache]$ awk '{print $1}' access.log | head -n 10 1.202.218.8 208.115.113.91 123.125.71.20 220.181.108.101 123.125.68.79 178.154.210.252 74.125.126.102 74.125.126.103 74.125.126.93 74.125.126.82
  • 41. sort lines of text files sort
  • 42. #!/bin/bash [~/Apache]$ awk '{print $1}' access.log | head -n 5 1.202.218.8 208.115.113.91 123.125.71.20 220.181.108.101 123.125.68.79
  • 43. #!/bin/bash [~/Apache]$ awk '{print $1}' access.log | head -n 5 1.202.218.8 208.115.113.91 123.125.71.20 220.181.108.101 123.125.68.79 [~/Apache]$ awk '{print $1}' access.log | head -n 5 | sort 1.202.218.8 123.125.68.79 123.125.71.20 208.115.113.91 220.181.108.101
  • 44. report or filter out repeated lines in a file uniq
  • 45. #!/bin/bash [~/Apache]$ awk '{print $1}' access.log | sort | uniq | wc -l 7967
  • 46. #!/bin/bash [~/Apache]$ awk '{print $1}' *.log | sort | uniq | wc -l 7967 [~/Apache]$ awk '{print $1}' *.log | sort | uniq | head -n 10 1.0.250.121 1.179.147.2 1.2.209.130 1.2.215.151 1.2.216.110 1.2.217.90 1.202.218.13 1.202.218.14 1.202.218.15 1.202.218.21
  • 47. Quais os IPs que mais acessaram o access.log dele? Já que sabemos que não fomos os únicos.
  • 48. Você já ouviu falar em “bash script”, certo? Eu
  • 49. #!/bin/bash [~/Apache]$ for ip in `awk '{print $1}' *.log | sort | uniq`; do > count=`grep “$ip” access.log | grep 'access.log' | wc -l`; > echo "$count $ip" >> ip-safadenhos.txt; > done;
  • 50. #!/bin/bash [~/Apache]$ wc -l *.txt 9479 ip-safadenhos.txt
  • 51. #!/bin/bash [~/Apache]$ wc -l *.txt 9479 ip-safadenhos.txt [~/Apache]$ awk '{print $1}' *.txt | grep -v 0 | wc -l 5619
  • 52.
  • 54. #!/bin/bash [~/Apache]$ sort -nr ip-safadenhos.txt | head -n 10 246 88.250.57.232 184 216.151.130.179 121 88.190.16.36 90 199.59.56.24 84 80.93.217.38 73 216.152.251.7 71 89.233.105.125 68 120.196.161.251 68 120.196.161.251 58 190.254.21.236
  • 55. Como usar isso no dia a dia? Já que ninguém tem tempo sobrando.
  • 56. Pegue já seu outro exemplo! !g filetype:log error.log E_ERROR
  • 57. Log do PHP Via linha de comando.
  • 58. LC_Page_Admin.php(69)] from 126.29.228.69 login_id = ()[acf83d9069c4c9036fa852909503b631] 2013/01/30 00:49:03 [/hiroshima-gift.co.jp/html/admin/index.php] Fatal error(E_ERROR): Call to a member function doAction() on a non-object on [/home/bravecreate/www/hiroshima-gift.co.jp/data/class/pages/admin/ LC_Page_Admin.php(69)] from 126.29.228.69 login_id = ()[acf83d9069c4c9036fa852909503b631] 2013/01/30 00:50:38 [/hiroshima-gift.co.jp/html/admin/index.php] Fatal error(E_ERROR): Call to a member function doAction() on a non-object on [/home/bravecreate/www/hiroshima-gift.co.jp/data/class/pages/admin/ LC_Page_Admin.php(69)] from 126.29.228.69 login_id = ()[acf83d9069c4c9036fa852909503b631] 2013/01/30 00:50:59 [/hiroshima-gift.co.jp/html/admin/index.php] Fatal error(E_ERROR): Call to a member function doAction() on a non-object on [/home/bravecreate/www/hiroshima-gift.co.jp/data/class/pages/admin/ LC_Page_Admin.php(69)] from 126.29.228.69 login_id = ()[acf83d9069c4c9036fa852909503b631] 2013/04/02 14:09:39 [/hiroshima-gift.co.jp/html/index.php] Fatal error(E_USER_ERROR): DB処çê †ãÅ §ã‚¨ãƒ©ãƒ¼ãÅ Œç™ºç”ŸãÅ —ãÅ ¾ãÅ —ãÅ Ÿã€‚ SQL: [SET SESSION storage_engine = InnoDB] PlaceHolder: [array ( )] MDB2 Error: insufficient permissions _doQuery: [Error message: Could not select the database: bravecreate_nagasakiya_ec] [Last executed query: SET SESSION storage_engine = InnoDB] [Native code: 1044] [Native message: Access denied for user 'bravecreate'@'%' to database 'bravecreate_nagasakiya_ec'] on [/home/bravecreate/www/hiroshima-gift.co.jp/data/class/SC_Query.php(1008)] from 66.249.74.233 customer_id = /home/bravecreate/www/hiroshima-gift.co.jp/html/index.php(32): LC_Page_Index_Ex->init /home/bravecreate/www/hiroshima-gift.co.jp/data/class_extends/page_extends/LC_Page_Index_Ex.php(47): LC_Page_Index->init /home/bravecreate/www/hiroshima-gift.co.jp/data/class/pages/LC_Page_Index.php(45): LC_Page->init /home/bravecreate/www/hiroshima-gift.co.jp/data/class/pages/LC_Page.php(97): SC_Helper_PageLayout- >sfGetPageLayout /home/bravecreate/www/hiroshima-gift.co.jp/data/class/helper/SC_Helper_PageLayout.php(54): SC_Helper_PageLayout->getPageProperties /home/bravecreate/www/hiroshima-gift.co.jp/data/class/helper/SC_Helper_PageLayout.php(112): SC_Query::getSingletonInstance /home/bravecreate/www/hiroshima-gift.co.jp/data/class/SC_Query.php(104): SC_Query->__construct /home/bravecreate/www/hiroshima-gift.co.jp/data/class/SC_Query.php(88): SC_DB_DBFactory_MYSQL->initObjQuery /home/bravecreate/www/hiroshima-gift.co.jp/data/class/db/dbfactory/SC_DB_DBFactory_MYSQL.php(323): SC_Query- >exec /home/bravecreate/www/hiroshima-gift.co.jp/data/class/SC_Query.php(231): SC_Query->query /home/bravecreate/www/hiroshima-gift.co.jp/data/class/SC_Query.php(814): SC_Query->execute /home/bravecreate/www/hiroshima-gift.co.jp/data/class/SC_Query.php(971): SC_Query->error
  • 59. #!/bin/bash [~/PHP]$ awk '/(E_[A-Z])/ {print $5}' error.log | sort | uniq -c 24 error(E_ERROR): 15 error(E_USER_ERROR):
  • 60. #!/bin/bash [~/PHP]$ awk '/(E_[A-Z])/ {print $5}' error.log | sort | uniq -c 24 error(E_ERROR): 15 error(E_USER_ERROR): [~/PHP]$ awk -F: '/E_ERROR/ {print $4}' error.log | sort | uniq Call to a member function doAction() on a non-object on [/home/ bravecreate/www/hiroshima-gift.co.jp/data/class/ SC_View.php(137)] Call to a member function doAction() on a non-object on [/home/ bravecreate/www/hiroshima-gift.co.jp/data/class/ SC_View.php(137)] Call to a member function doAction() on a non-object on [/home/ bravecreate/www/hiroshima-gift.co.jp/data/class/pages/admin/ LC_Page_Admin.php(69)]
  • 61.
  • 62.
  • 63.
  • 65.
  • 66. Configurações Ou coisas que podem provocar diferentes resultados no seu PHP.
  • 68. ini_set(‘display_errors’,‘On’) Exibe erros em HTML para usuário. (Ideal para ambiente de desenvolvimento)
  • 69.
  • 71.
  • 72. log_errors Envia os erros para o arquivo de log configurado.
  • 73. ini_set(‘log_errors’,‘On’) Salva os erros no arquivo de log. (Ideal em todos os ambientes)
  • 74. ini_set(‘log_errors’,‘Off’) Não salva erros no arquivo de log. (Não sei porque você irá querer isso)
  • 75. error_log Onde você deseja que o arquivo de log seja gerado?
  • 77. 1 <?php 2 ini_set('display_errors', 1); 3 error_reporting(E_ALL); 4 5 if ($_POST['user']) { 6 // ... 7 } 8 /** 9 * Output: 10 * 11 * PHP Notice: Undefined index: user in notices.php on line 5 12 */
  • 78. 1 <?php 2 ini_set('display_errors', 1); 3 error_reporting(E_ALL ^ E_NOTICE); 4 5 if ($_POST['user']) { 6 // ... 7 } 8 /** 9 * Output: 10 * 11 */
  • 79. 1 <?php 2 ini_set('display_errors', 1); 3 error_reporting(E_ALL); 4 5 echo date('l').PHP_EOL; 6 7 date_default_timezone_set('America/Sao_Paulo'); 8 9 echo date('l').PHP_EOL; 10 11 /** 12 * Output: 13 * 14 * PHP Warning: date(): It is not safe to rely on the system's 15 * timezone settings. You are *required* to use the date.timezone 16 * setting or the date_default_timezone_set() function. 17 * In case you used any of those methods and you are still getting 18 * this warning, you most likely misspelled the timezone identifier. 19 * We selected the timezone 'UTC' for now, but please set date.timezone 20 * to select your timezone. in date.php on line 5 21 * 22 * Saturday 23 * Saturday 24 */
  • 80. 1 <?php 2 ini_set('display_errors', 1); 3 error_reporting(E_ALL); 4 5 include 'nao-existe.php'; 6 7 /** 8 * Output: 9 * 10 * PHP Warning: include(nao-existe.php): failed to open stream: 11 * No such file or directory in warning.php on line 5 12 */
  • 81. 1 <?php 2 ini_set('display_errors', 1); 3 error_reporting(E_ALL); 4 5 require 'nao-existe.php'; 6 /** 7 * Output: 8 * 9 * PHP Warning: require(nao-existe.php): failed to open stream: 10 * No such file or directory in warning.php on line 5 11 * 12 * Fatal error: require(): Failed opening required 13 * 'nao-existe.php' in error.php on line 5 14 */
  • 83. trigger_error() Gera uma mensagem de determinada severidade.
  • 84. 1 <?php 2 date_default_timezone_set('America/Sao_Paulo'); 3 error_reporting(-1); 4 ini_set('log_errors', 1); 5 ini_set('error_log', 'duh.log'); 6 7 define('APP_ENV', getenv('APP_ENV') ?: 'dev'); 8 switch (APP_ENV) { 9 case 'live': 10 ini_set('display_errors', 0); 11 break; 12 default: 13 ini_set('display_errors', 1); 14 break; 15 } 16 17 if (false === extension_loaded('xdebug')) { 18 trigger_error('Conhece o xDebug?', X_USER_NOTICE); 19 } 20 21 if (false === version_compare($current=PHP_VERSION, $required='6.4.0', '>=')) { 22 $msg = sprintf('Versão mínima do PHP requerida %s. (%s)', $required, $current); 23 trigger_error($msg, E_USER_ERROR); 24 unset($required, $current); 25 } 26 27 if (false === file_exists($autoload = 'vendor/autoload.php')) { 28 trigger_error('Por favor, rode a instale com `make install`.', E_USER_ERROR); 29 } 30
  • 86. 1 <?php 2 ini_set('display_errors', 0); 3 ini_set('log_errors', 1); 4 error_reporting(-1); 5 6 error_log('É nóis na fita!'); 7 error_log('Não me deixa cair no SPAM!', 1, 'a@a.com');
  • 87. 1 <?php 2 ini_set('display_errors', 0); 3 ini_set('log_errors', 1); 4 error_reporting(-1); 5 6 error_log('É nóis na fita!'); 7 error_log('Não me deixa cair no SPAM!', 1, 'a@a.com');
  • 88.
  • 89. Exceptions Erros num paradigma Orientado a Objetos
  • 90. 1 <?php 2 3 namespace Math; 4 5 class Operation 6 { 7 public static function sum() 8 { 9 $args = func_get_args(); 10 $result = 0; 11 foreach ($args as $arg) { 12 if (false == is_int($arg)) { 13 $msg = 'Somente inteiros permitidos'; 14 throw new InvalidArgumentException($msg); 15 } 16 $result += (integer) $arg; 17 } 18 19 return $result; 20 } 21 } 22 23 echo Operation::sum(1,2,3,5.0);
  • 91.
  • 92. 1 <?php 2 3 namespace Math; 4 5 require 'math.php'; // use autoload, por favor! 6 7 use InvalidArgumentException; 8 use Exception; 9 10 class Grades 11 { 12 public static function average($prova1, $prova2, $prova3) 13 { 14 try { 15 $total = Operation::sum($prova1, $prova2, $prova3); 16 } catch (InvalidArgumentException $e) { 17 $msg = 'Alguma nota esta errada.'; 18 throw new InvalidArgumentException($msg, null, $e); 19 } catch (Exception $e) { 20 $msg = 'Calcular media de notas.'; 21 throw new RuntimeException($msg, null, $e); 22 } 23 } 24 } 25 26 echo Grades::average(10, 10, 9.8);
  • 93.
  • 95. Quer saber mais? Acabou de sair do forno.
  • 96. PSR-3 Um padrão de logs para o PHP
  • 98. Falhando miseravelmente com PHP Uma re-interpretação do título.
  • 99. Falhando miseravelmente com PHP Erros e mensagens do sistema DEVEM ser expostos sempre que possível.
  • 100. Falhando miseravelmente com PHP Expostos pra todos os desenvolvedores (e administradores) envolvidos na manutenção do sistema, não para usuários. Muito menos para toda internet.
  • 101. Falhando miseravelmente com PHP PELO MENOS os gerados pelo próprio PHP.
  • 102. Dúvidas? ou críticas, sugestões, declarações, conjecturações, etc...