SlideShare a Scribd company logo
1 of 61
Download to read offline
PHP Debugging from the Trenches
PHP Cambridge, 24 Feb 2014
Simon R Jones, Studio 24
Me
•

Founder & Technical Director of
digital agency Studio 24


•

Programming PHP since 1999


•

Contributor to ZF1


•

Contributor to Web Standards
Project


•

Zend Certified Engineer


•

Organiser of PHP Cambridge
and Refresh Cambridge

studio24.net
What causes bugs

First steps

PHP errors

Error reporting

Debugging in PHP

Remote debugging

AJAX and Web Services

Legacy software

Good practises

studio24.net
“Debugging is a methodical process of finding
and reducing the number of bugs, or defects,
in a computer program or a piece of electronic
hardware, thus making it behave as expected.”
– Wikipedia

studio24.net
“Debugging is a methodical process of finding
and reducing the number of bugs, or defects,
in a computer program or a piece of electronic
hardware, thus making it behave as expected.”
– Wikipedia

studio24.net
!

We want to avoid this!
WSOD:

White Screen 

Of Death!
Which makes you feel
like this..
While we’d rather be
happily solving problems
What causes bugs?

studio24.net
Grace Hopper

http://www.history.navy.mil/photos/pers-us/uspers-h/
g-hoppr.htm
What causes bugs?
•

Human error (typos)

•

Business logic errors

•

Environmental errors (files, web service, DB)

•

Client-side errors (web browsers)

•

External software bug (PHP, Apache, etc)

•

And sometimes it’s just a feature request or
misunderstanding!
studio24.net
First steps

studio24.net
“It is a capital mistake to theorize before one
has data. Insensibly one begins to twist facts to
suit theories, instead of theories to suit facts.”
– Sherlock Holmes, A Scandal in Bohemia

studio24.net
Understand the issue

1. What did you do?

(how to reproduce the issue)

2. What happened?

(what’s wrong)

3. What was supposed to
happen?

(expected behaviour)

studio24.net
Know your environment
•

URL

•

Web browser

•

Operating System / Device

•

JavaScript support?

studio24.net
Gather data
•

Logs
•
•

Application logs

•
•

Webserver access / error logs (Nginx, Apache)

Software logs (Varnish, MySQL)

File system
•

Permissions

•

File space, check with df -h
studio24.net
Replicate the issue
•

Replay steps

•

Can you replicate it?

•

If not, what’s different?
•

Is the data the same?

•

Are there time-based business rules?

•

Are you using the same web browser/OS?
studio24.net
PHP errors

studio24.net
PHP errors	
•

Parse errors
•

Identified by T_* parser tokens

•

T_PAAMAYIM_NEKUDOTAYIM 

issues with static operator ::

•

Sending headers more than once

•

Segmentation faults

•

Exception thrown without a stack frame in
Unknown on line 0. Yay!
studio24.net
syntax error, unexpected T_SL …
$heredoc = <<<EOD

My long piece

of text on a few lines

there’s a space here

EOD;
<<<<<<< HEAD

$title = "My updated code";

=======

$title = "My old code";

>>>>>>> master
syntax error, unexpected $end in /path/to/file.php on line 27
$heredoc = <<<EOD

My long piece

of text on a few lines
EOD;

there’s a space here

// More code here

for ($x=0; $x<10; $x++) {

// Do stuff

}
echo $something;

but the error reports here
Syntax errors	
Easily fixed with a decent IDE or running lint before you deploy code:

php -l /path/to/file.php
No syntax errors detected in file.php
Warning: session_start() [function.session-start]: Cannot
send session cookie - headers already sent by…
<?php
a space here

$title = "My title";
// More code here

for ($x=0; $x<10; $x++) {

// Do stuff

}
or here will flush the headers

?>
Headers sent twice errors
Easily fixed by separating PHP from your templates 

and don’t include final ?> in files that only contain PHP

<?php

// Some code

$title = "Lots of code here!";
// Look Ma, no closing ?> here!
Obscure error messages
•

Segmentation fault - issue writing to memory, usually an
internal bug

•

Exception thrown without a stack frame - exception
thrown in destructors / exception handlers

studio24.net
Error reporting

studio24.net
Error reporting
// Development

display_errors = On

display_startup_errors = On

error_reporting = -1 // E_ALL works PHP5.4+

log_errors = On
// Production

display_errors = Off

display_startup_errors = Off

error_reporting = E_ALL

log_errors = On
Error reporting	
•

Any syntax errors in the file that defines error reporting
will ignore these settings

•

Default is to log errors to Apache ErrorLog location,
overrides php.ini error_log setting

studio24.net
Custom error handling
•

set_error_handler() - PHP errors

•

set_exception_handler() - uncaught exceptions

•

Log errors

•

Log stack traces

•

Display friendly page to users

•

Use monitoring for alerts
studio24.net
Suppressing errors
•

@ operator

•

Don’t do it!

•

Unless you immediately test the result and deal with it

•

Suppressed errors still sent to custom error handler

•

Scream to disable!
ini_set('scream.enabled', 1);
Debugging in PHP

studio24.net
Quick and dirty
•

var_dump() and print_r()

•

Very basic, and not that useful

•

Needs formatting if complex data
echo "<pre>";var_dump($stuff);exit;

•

Xdebug formats var_dump()

studio24.net
Displaying errors

Pretty Blue Screen
Developer toolbars
•

Send JavaScript messages to console.log()

•

Use Firebug and FirePHP to send messages from PHP to
the console

•

Can profile DB queries via
Zend_Db_Profiler_Firebug
Framework debug toolbars
•

Useful for quickly seeing information

•

May slow application down

studio24.net
Symfony toolbar
Xdebug
•

Stack traces for errors

•

Profiling

•

Remote debugging

•

Enabled via zend_extension in php.ini

•

Don’t use in production!

•

XHProf is designed for profiling on production servers
studio24.net
Xdebug stack trace
Remote debugging

studio24.net
Xdebug remote debugging
•

Enable in PHP.ini via
xdebug.remote_enable=1

xdebug.remote_port="9000"

1. Set breakpoints
2. Run in browser via session, or browser extension
3. Step through code in IDE
studio24.net
Remote debugging in PHP Storm
Debugging AJAX and Web Services

studio24.net
CURL
•

Great for quickly inspecting headers

curl --HEAD http://domain.com/url
•

Redirects are aggressively cached in most browsers, CURL isn't

•

Use it to debug web services

•

Use Python’s json.tool to format returned JSON

curl -s -H 'X-Auth-Token: AUTH_TOKEN’ 

-H 'Accept: application/json' 

'http://domain.com/url' | python -m json.tool
studio24.net
Charles Proxy
•

Records all requests

•

Inspect request and response headers

•

Makes it really easy to debug AJAX

•

You can include just your test domain to reduce amount
of data captured

studio24.net
Dealing with SSL
•

Charles acts as a proxy to allow you to inspect SSL requests.

•

This is the same as a man-in-the-middle attack

•

You need to authorise your web browser to allow this

•

Access third-party URLs directly to do this

studio24.net
“Nothing clears up a case so much as stating it
to another person.”
–Sherlock Holmes, The Memoirs of Sherlock Holmes

studio24.net
If you’re stuck get a fresh view
•

“Rubber duck” debugging

•

The act of talking through an issue forces 

you to think logically

studio24.net
Debugging Legacy software

studio24.net
Problems debugging Legacy software	
•

“Spaghetti code”

•

No organised class/function system

•

Duplicated code

•

Dead code

•

Global variables

•

Unescaped SQL (and other security woes)

•

Suppressed errors
studio24.net
Strategies
•

Ensure you have a local development environment

•

Get the codebase into version control

•

Remove dead code

•

Review error logs

•

Debug with Xdebug to understand code flow

•

Refactor by making small, incremental changes
studio24.net
Refactoring
It Was Like That When I Got Here: Steps
Toward Modernizing a Legacy Codebase

http://paul-m-jones.com/archives/2667

!
Modernizing Legacy Applications In PHP

https://leanpub.com/mlaphp

studio24.net
Good practises 

to help make debugging easier

studio24.net
Good practises
•

Use a good IDE (PHPStorm, Zend Studio, NetBeans)

•

Coding standards

•

Document your code

•

Filter In / Escape Out

•

Defensive coding (test all return values)

•

Automated testing
studio24.net
PHPUnit

Unit testing
Selenium

Browser testing
“Chance has put in our way a most singular
and whimsical problem, and its solution is its
own reward”
–Sherlock Holmes, The Adventures of Sherlock Holmes

studio24.net
Thanks!
@simonrjones

!

http://www.slideshare.net/simonrjones/TODO
Useful links	
Environment

http://supportdetails.com/
Browser testing

http://www.browserstack.com/ 

http://docs.seleniumhq.org/
PHP parser errors

http://php.net/manual/en/tokens.php
Debug toolbars

http://www.sitepoint.com/prettyblue-screen/ 

https://github.com/zendframework/
ZendDeveloperTools 

http://www.firephp.org/

Debugging and Profiling

http://xdebug.org/

https://github.com/facebook/xhprof

https://github.com/perftools/xhgui
Charles Proxy

http://www.charlesproxy.com/ 

http://techportal.inviqa.com/
2013/03/05/manipulating-http-withcharles-proxy/
PHP Standards

http://www.php-fig.org/ 

http://www.phptherightway.com/
Refactoring

http://paul-m-jones.com/archives/
2667

More Related Content

What's hot

The Professional Programmer
The Professional ProgrammerThe Professional Programmer
The Professional ProgrammerDave Cross
 
Jest: Frontend Testing leicht gemacht @EnterJS2018
Jest: Frontend Testing leicht gemacht @EnterJS2018Jest: Frontend Testing leicht gemacht @EnterJS2018
Jest: Frontend Testing leicht gemacht @EnterJS2018Holger Grosse-Plankermann
 
NDC London 2014: Thinking Like an Erlanger
NDC London 2014: Thinking Like an ErlangerNDC London 2014: Thinking Like an Erlanger
NDC London 2014: Thinking Like an ErlangerTorben Hoffmann
 
HTML5: It goes to ELEVEN
HTML5: It goes to ELEVENHTML5: It goes to ELEVEN
HTML5: It goes to ELEVENMathias Bynens
 
Monitoring CF What are my options? Why Should I?
Monitoring CF What are my options? Why Should I?Monitoring CF What are my options? Why Should I?
Monitoring CF What are my options? Why Should I?ColdFusionConference
 
Improving The Quality of Existing Software
Improving The Quality of Existing SoftwareImproving The Quality of Existing Software
Improving The Quality of Existing SoftwareSteven Smith
 
Pragmatic Parallels: Java and JavaScript
Pragmatic Parallels: Java and JavaScriptPragmatic Parallels: Java and JavaScript
Pragmatic Parallels: Java and JavaScriptdavejohnson
 
EuroPython 2011 - How to build complex web applications having fun?
EuroPython 2011 - How to build complex web applications having fun?EuroPython 2011 - How to build complex web applications having fun?
EuroPython 2011 - How to build complex web applications having fun?Andrew Mleczko
 
Managing Modules Without Going Crazy (NPW 2007)
Managing Modules Without Going Crazy (NPW 2007)Managing Modules Without Going Crazy (NPW 2007)
Managing Modules Without Going Crazy (NPW 2007)brian d foy
 
Frozen rails 2012 - Fighting Code Smells
Frozen rails 2012 - Fighting Code SmellsFrozen rails 2012 - Fighting Code Smells
Frozen rails 2012 - Fighting Code SmellsDennis Ushakov
 
[CB19] API-induced SSRF: How Apple Pay Scattered Vulnerabilities Across the W...
[CB19] API-induced SSRF: How Apple Pay Scattered Vulnerabilities Across the W...[CB19] API-induced SSRF: How Apple Pay Scattered Vulnerabilities Across the W...
[CB19] API-induced SSRF: How Apple Pay Scattered Vulnerabilities Across the W...CODE BLUE
 
Breaking Dependencies to Allow Unit Testing - DevIntersection Spring 2016
Breaking Dependencies to Allow Unit Testing - DevIntersection Spring 2016Breaking Dependencies to Allow Unit Testing - DevIntersection Spring 2016
Breaking Dependencies to Allow Unit Testing - DevIntersection Spring 2016Steven Smith
 
Fix me if you can - DrupalCon prague
Fix me if you can - DrupalCon pragueFix me if you can - DrupalCon prague
Fix me if you can - DrupalCon praguehernanibf
 
DEF CON 27 - JOSHUA MADDUX - api induced ssrf
DEF CON 27 - JOSHUA MADDUX - api induced ssrfDEF CON 27 - JOSHUA MADDUX - api induced ssrf
DEF CON 27 - JOSHUA MADDUX - api induced ssrfFelipe Prado
 
Improving the Quality of Existing Software
Improving the Quality of Existing SoftwareImproving the Quality of Existing Software
Improving the Quality of Existing SoftwareSteven Smith
 
Is it time to start using HTML 5
Is it time to start using HTML 5Is it time to start using HTML 5
Is it time to start using HTML 5Ravi Raj
 
Old code doesn't stink - Detroit
Old code doesn't stink - DetroitOld code doesn't stink - Detroit
Old code doesn't stink - DetroitMartin Gutenbrunner
 

What's hot (20)

The Professional Programmer
The Professional ProgrammerThe Professional Programmer
The Professional Programmer
 
Jest: Frontend Testing leicht gemacht @EnterJS2018
Jest: Frontend Testing leicht gemacht @EnterJS2018Jest: Frontend Testing leicht gemacht @EnterJS2018
Jest: Frontend Testing leicht gemacht @EnterJS2018
 
Erlang White Label
Erlang White LabelErlang White Label
Erlang White Label
 
NDC London 2014: Thinking Like an Erlanger
NDC London 2014: Thinking Like an ErlangerNDC London 2014: Thinking Like an Erlanger
NDC London 2014: Thinking Like an Erlanger
 
HTML5: It goes to ELEVEN
HTML5: It goes to ELEVENHTML5: It goes to ELEVEN
HTML5: It goes to ELEVEN
 
Monitoring CF What are my options? Why Should I?
Monitoring CF What are my options? Why Should I?Monitoring CF What are my options? Why Should I?
Monitoring CF What are my options? Why Should I?
 
Improving The Quality of Existing Software
Improving The Quality of Existing SoftwareImproving The Quality of Existing Software
Improving The Quality of Existing Software
 
Pragmatic Parallels: Java and JavaScript
Pragmatic Parallels: Java and JavaScriptPragmatic Parallels: Java and JavaScript
Pragmatic Parallels: Java and JavaScript
 
EuroPython 2011 - How to build complex web applications having fun?
EuroPython 2011 - How to build complex web applications having fun?EuroPython 2011 - How to build complex web applications having fun?
EuroPython 2011 - How to build complex web applications having fun?
 
Managing Modules Without Going Crazy (NPW 2007)
Managing Modules Without Going Crazy (NPW 2007)Managing Modules Without Going Crazy (NPW 2007)
Managing Modules Without Going Crazy (NPW 2007)
 
Frozen rails 2012 - Fighting Code Smells
Frozen rails 2012 - Fighting Code SmellsFrozen rails 2012 - Fighting Code Smells
Frozen rails 2012 - Fighting Code Smells
 
[CB19] API-induced SSRF: How Apple Pay Scattered Vulnerabilities Across the W...
[CB19] API-induced SSRF: How Apple Pay Scattered Vulnerabilities Across the W...[CB19] API-induced SSRF: How Apple Pay Scattered Vulnerabilities Across the W...
[CB19] API-induced SSRF: How Apple Pay Scattered Vulnerabilities Across the W...
 
Breaking Dependencies to Allow Unit Testing - DevIntersection Spring 2016
Breaking Dependencies to Allow Unit Testing - DevIntersection Spring 2016Breaking Dependencies to Allow Unit Testing - DevIntersection Spring 2016
Breaking Dependencies to Allow Unit Testing - DevIntersection Spring 2016
 
Fix me if you can - DrupalCon prague
Fix me if you can - DrupalCon pragueFix me if you can - DrupalCon prague
Fix me if you can - DrupalCon prague
 
DEF CON 27 - JOSHUA MADDUX - api induced ssrf
DEF CON 27 - JOSHUA MADDUX - api induced ssrfDEF CON 27 - JOSHUA MADDUX - api induced ssrf
DEF CON 27 - JOSHUA MADDUX - api induced ssrf
 
Improving the Quality of Existing Software
Improving the Quality of Existing SoftwareImproving the Quality of Existing Software
Improving the Quality of Existing Software
 
Is it time to start using HTML 5
Is it time to start using HTML 5Is it time to start using HTML 5
Is it time to start using HTML 5
 
[In Control 2010] HTML5
[In Control 2010] HTML5[In Control 2010] HTML5
[In Control 2010] HTML5
 
Old code doesn't stink - Detroit
Old code doesn't stink - DetroitOld code doesn't stink - Detroit
Old code doesn't stink - Detroit
 
php_tizag_tutorial
php_tizag_tutorialphp_tizag_tutorial
php_tizag_tutorial
 

Viewers also liked

Evolució Web
Evolució WebEvolució Web
Evolució Webcrizos
 
Internet awareness educators ISPAB
Internet awareness educators  ISPABInternet awareness educators  ISPAB
Internet awareness educators ISPABsmt.islam
 
Ispab presentation for journalist : 2013-14
Ispab presentation for journalist : 2013-14Ispab presentation for journalist : 2013-14
Ispab presentation for journalist : 2013-14smt.islam
 
How to Create a Cycle
How to Create a CycleHow to Create a Cycle
How to Create a Cyclejillyshaw
 
Why Consider A Real Estate Investment In The Current Market July 2009
Why Consider A Real Estate Investment In The Current Market July 2009Why Consider A Real Estate Investment In The Current Market July 2009
Why Consider A Real Estate Investment In The Current Market July 2009RichardZimmerman
 
Cpa Cpe Why Consider A Real Estate Investment In The Current Market July 2009
Cpa Cpe   Why Consider A Real Estate Investment In The Current Market July 2009Cpa Cpe   Why Consider A Real Estate Investment In The Current Market July 2009
Cpa Cpe Why Consider A Real Estate Investment In The Current Market July 2009RichardZimmerman
 
How to Verify a Cycle
How to Verify a CycleHow to Verify a Cycle
How to Verify a Cyclejillyshaw
 
Taller de contes
Taller de contesTaller de contes
Taller de contescrizos
 
CHI 2012 - EIST workshop
CHI 2012 - EIST workshopCHI 2012 - EIST workshop
CHI 2012 - EIST workshopPedro Santana
 
El Caimà i el seu amic
El Caimà i el seu amicEl Caimà i el seu amic
El Caimà i el seu amiccrizos
 
What we look for 
in people when recruiting
What we look for 
in people when recruitingWhat we look for 
in people when recruiting
What we look for 
in people when recruitingSimon Jones
 
Why Consider A Real Estate Investment In The Current Market July 2009
Why Consider A Real Estate Investment In The Current Market July 2009Why Consider A Real Estate Investment In The Current Market July 2009
Why Consider A Real Estate Investment In The Current Market July 2009RichardZimmerman
 
Responsive Web Design: A Case Study with Crossrail
Responsive Web Design: A Case Study with CrossrailResponsive Web Design: A Case Study with Crossrail
Responsive Web Design: A Case Study with CrossrailSimon Jones
 
Powerpoint from Student Teaching
Powerpoint from Student TeachingPowerpoint from Student Teaching
Powerpoint from Student Teachingbridgetaward
 
Brain Games, BBC and Facebook Fun
Brain Games, BBC and Facebook FunBrain Games, BBC and Facebook Fun
Brain Games, BBC and Facebook FunSimon Jones
 
Povestea Pipei Micuta Padureanca
Povestea Pipei   Micuta PadureancaPovestea Pipei   Micuta Padureanca
Povestea Pipei Micuta PadureancaNerLol
 

Viewers also liked (17)

Evolució Web
Evolució WebEvolució Web
Evolució Web
 
Internet awareness educators ISPAB
Internet awareness educators  ISPABInternet awareness educators  ISPAB
Internet awareness educators ISPAB
 
Ispab presentation for journalist : 2013-14
Ispab presentation for journalist : 2013-14Ispab presentation for journalist : 2013-14
Ispab presentation for journalist : 2013-14
 
How to Create a Cycle
How to Create a CycleHow to Create a Cycle
How to Create a Cycle
 
Why Consider A Real Estate Investment In The Current Market July 2009
Why Consider A Real Estate Investment In The Current Market July 2009Why Consider A Real Estate Investment In The Current Market July 2009
Why Consider A Real Estate Investment In The Current Market July 2009
 
Cpa Cpe Why Consider A Real Estate Investment In The Current Market July 2009
Cpa Cpe   Why Consider A Real Estate Investment In The Current Market July 2009Cpa Cpe   Why Consider A Real Estate Investment In The Current Market July 2009
Cpa Cpe Why Consider A Real Estate Investment In The Current Market July 2009
 
How to Verify a Cycle
How to Verify a CycleHow to Verify a Cycle
How to Verify a Cycle
 
Taller de contes
Taller de contesTaller de contes
Taller de contes
 
CHI 2012 - EIST workshop
CHI 2012 - EIST workshopCHI 2012 - EIST workshop
CHI 2012 - EIST workshop
 
El Caimà i el seu amic
El Caimà i el seu amicEl Caimà i el seu amic
El Caimà i el seu amic
 
What we look for 
in people when recruiting
What we look for 
in people when recruitingWhat we look for 
in people when recruiting
What we look for 
in people when recruiting
 
Modern PHP
Modern PHPModern PHP
Modern PHP
 
Why Consider A Real Estate Investment In The Current Market July 2009
Why Consider A Real Estate Investment In The Current Market July 2009Why Consider A Real Estate Investment In The Current Market July 2009
Why Consider A Real Estate Investment In The Current Market July 2009
 
Responsive Web Design: A Case Study with Crossrail
Responsive Web Design: A Case Study with CrossrailResponsive Web Design: A Case Study with Crossrail
Responsive Web Design: A Case Study with Crossrail
 
Powerpoint from Student Teaching
Powerpoint from Student TeachingPowerpoint from Student Teaching
Powerpoint from Student Teaching
 
Brain Games, BBC and Facebook Fun
Brain Games, BBC and Facebook FunBrain Games, BBC and Facebook Fun
Brain Games, BBC and Facebook Fun
 
Povestea Pipei Micuta Padureanca
Povestea Pipei   Micuta PadureancaPovestea Pipei   Micuta Padureanca
Povestea Pipei Micuta Padureanca
 

Similar to PHP Debugging from the Trenches: Methods for Finding and Fixing Bugs

Here Be Dragons – Advanced JavaScript Debugging
Here Be Dragons – Advanced JavaScript DebuggingHere Be Dragons – Advanced JavaScript Debugging
Here Be Dragons – Advanced JavaScript DebuggingFITC
 
Northeast PHP - High Performance PHP
Northeast PHP - High Performance PHPNortheast PHP - High Performance PHP
Northeast PHP - High Performance PHPJonathan Klein
 
BTV PHP - Building Fast Websites
BTV PHP - Building Fast WebsitesBTV PHP - Building Fast Websites
BTV PHP - Building Fast WebsitesJonathan Klein
 
ExpressionEngine - Simple Steps to Performance and Security (EECI 2014)
ExpressionEngine - Simple Steps to Performance and Security (EECI 2014)ExpressionEngine - Simple Steps to Performance and Security (EECI 2014)
ExpressionEngine - Simple Steps to Performance and Security (EECI 2014)Nexcess.net LLC
 
Leveling Up at JavaScript
Leveling Up at JavaScriptLeveling Up at JavaScript
Leveling Up at JavaScriptRaymond Camden
 
Chelberg ptcuser 2010
Chelberg ptcuser 2010Chelberg ptcuser 2010
Chelberg ptcuser 2010Clay Helberg
 
Behat bdd training (php) course slides pdf
Behat bdd training (php) course slides pdfBehat bdd training (php) course slides pdf
Behat bdd training (php) course slides pdfseleniumbootcamp
 
Static Code Analysis PHP[tek] 2023
Static Code Analysis PHP[tek] 2023Static Code Analysis PHP[tek] 2023
Static Code Analysis PHP[tek] 2023Scott Keck-Warren
 
Dutch php conference_2010_opm
Dutch php conference_2010_opmDutch php conference_2010_opm
Dutch php conference_2010_opmisnull
 
Php training100%placement-in-mumbai
Php training100%placement-in-mumbaiPhp training100%placement-in-mumbai
Php training100%placement-in-mumbaivibrantuser
 
Drupal Auckland Meetup; Debug like a pro
Drupal Auckland Meetup; Debug like a proDrupal Auckland Meetup; Debug like a pro
Drupal Auckland Meetup; Debug like a proGareth Hall
 
We Make Debugging Sucks Less
We Make Debugging Sucks LessWe Make Debugging Sucks Less
We Make Debugging Sucks LessAlon Fliess
 
Continuous Delivery - Automate & Build Better Software with Travis CI
Continuous Delivery - Automate & Build Better Software with Travis CIContinuous Delivery - Automate & Build Better Software with Travis CI
Continuous Delivery - Automate & Build Better Software with Travis CIwajrcs
 
Joomla Code Quality Control and Automation Testing
Joomla Code Quality Control and Automation TestingJoomla Code Quality Control and Automation Testing
Joomla Code Quality Control and Automation TestingShyam Sunder Verma
 
doing_it_right() with WordPress
doing_it_right() with WordPressdoing_it_right() with WordPress
doing_it_right() with WordPressryanduff
 
Oracle WebLogic Diagnostics & Perfomance tuning
Oracle WebLogic Diagnostics & Perfomance tuningOracle WebLogic Diagnostics & Perfomance tuning
Oracle WebLogic Diagnostics & Perfomance tuningMichel Schildmeijer
 
DevOps with elmah.io on Umbraco Cloud
DevOps with elmah.io on Umbraco CloudDevOps with elmah.io on Umbraco Cloud
DevOps with elmah.io on Umbraco CloudThomas Ardal
 

Similar to PHP Debugging from the Trenches: Methods for Finding and Fixing Bugs (20)

Here Be Dragons – Advanced JavaScript Debugging
Here Be Dragons – Advanced JavaScript DebuggingHere Be Dragons – Advanced JavaScript Debugging
Here Be Dragons – Advanced JavaScript Debugging
 
Northeast PHP - High Performance PHP
Northeast PHP - High Performance PHPNortheast PHP - High Performance PHP
Northeast PHP - High Performance PHP
 
BTV PHP - Building Fast Websites
BTV PHP - Building Fast WebsitesBTV PHP - Building Fast Websites
BTV PHP - Building Fast Websites
 
ExpressionEngine - Simple Steps to Performance and Security (EECI 2014)
ExpressionEngine - Simple Steps to Performance and Security (EECI 2014)ExpressionEngine - Simple Steps to Performance and Security (EECI 2014)
ExpressionEngine - Simple Steps to Performance and Security (EECI 2014)
 
Tool up your lamp stack
Tool up your lamp stackTool up your lamp stack
Tool up your lamp stack
 
Leveling Up at JavaScript
Leveling Up at JavaScriptLeveling Up at JavaScript
Leveling Up at JavaScript
 
Chelberg ptcuser 2010
Chelberg ptcuser 2010Chelberg ptcuser 2010
Chelberg ptcuser 2010
 
Behat bdd training (php) course slides pdf
Behat bdd training (php) course slides pdfBehat bdd training (php) course slides pdf
Behat bdd training (php) course slides pdf
 
Rails tools
Rails toolsRails tools
Rails tools
 
Static Code Analysis PHP[tek] 2023
Static Code Analysis PHP[tek] 2023Static Code Analysis PHP[tek] 2023
Static Code Analysis PHP[tek] 2023
 
Dutch php conference_2010_opm
Dutch php conference_2010_opmDutch php conference_2010_opm
Dutch php conference_2010_opm
 
Php training100%placement-in-mumbai
Php training100%placement-in-mumbaiPhp training100%placement-in-mumbai
Php training100%placement-in-mumbai
 
PHP MySQL Workshop - facehook
PHP MySQL Workshop - facehookPHP MySQL Workshop - facehook
PHP MySQL Workshop - facehook
 
Drupal Auckland Meetup; Debug like a pro
Drupal Auckland Meetup; Debug like a proDrupal Auckland Meetup; Debug like a pro
Drupal Auckland Meetup; Debug like a pro
 
We Make Debugging Sucks Less
We Make Debugging Sucks LessWe Make Debugging Sucks Less
We Make Debugging Sucks Less
 
Continuous Delivery - Automate & Build Better Software with Travis CI
Continuous Delivery - Automate & Build Better Software with Travis CIContinuous Delivery - Automate & Build Better Software with Travis CI
Continuous Delivery - Automate & Build Better Software with Travis CI
 
Joomla Code Quality Control and Automation Testing
Joomla Code Quality Control and Automation TestingJoomla Code Quality Control and Automation Testing
Joomla Code Quality Control and Automation Testing
 
doing_it_right() with WordPress
doing_it_right() with WordPressdoing_it_right() with WordPress
doing_it_right() with WordPress
 
Oracle WebLogic Diagnostics & Perfomance tuning
Oracle WebLogic Diagnostics & Perfomance tuningOracle WebLogic Diagnostics & Perfomance tuning
Oracle WebLogic Diagnostics & Perfomance tuning
 
DevOps with elmah.io on Umbraco Cloud
DevOps with elmah.io on Umbraco CloudDevOps with elmah.io on Umbraco Cloud
DevOps with elmah.io on Umbraco Cloud
 

Recently uploaded

SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterMydbops
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rick Flair
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...AliaaTarek5
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 

Recently uploaded (20)

SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL Router
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 

PHP Debugging from the Trenches: Methods for Finding and Fixing Bugs

  • 1. PHP Debugging from the Trenches PHP Cambridge, 24 Feb 2014 Simon R Jones, Studio 24
  • 2. Me • Founder & Technical Director of digital agency Studio 24 • Programming PHP since 1999 • Contributor to ZF1 • Contributor to Web Standards Project • Zend Certified Engineer • Organiser of PHP Cambridge and Refresh Cambridge studio24.net
  • 3. What causes bugs
 First steps
 PHP errors
 Error reporting
 Debugging in PHP
 Remote debugging
 AJAX and Web Services
 Legacy software
 Good practises studio24.net
  • 4. “Debugging is a methodical process of finding and reducing the number of bugs, or defects, in a computer program or a piece of electronic hardware, thus making it behave as expected.” – Wikipedia studio24.net
  • 5. “Debugging is a methodical process of finding and reducing the number of bugs, or defects, in a computer program or a piece of electronic hardware, thus making it behave as expected.” – Wikipedia studio24.net
  • 6. ! We want to avoid this! WSOD: White Screen Of Death!
  • 7. Which makes you feel like this..
  • 8. While we’d rather be happily solving problems
  • 11. What causes bugs? • Human error (typos) • Business logic errors • Environmental errors (files, web service, DB) • Client-side errors (web browsers) • External software bug (PHP, Apache, etc) • And sometimes it’s just a feature request or misunderstanding! studio24.net
  • 13. “It is a capital mistake to theorize before one has data. Insensibly one begins to twist facts to suit theories, instead of theories to suit facts.” – Sherlock Holmes, A Scandal in Bohemia studio24.net
  • 14. Understand the issue 1. What did you do? (how to reproduce the issue) 2. What happened? (what’s wrong) 3. What was supposed to happen? (expected behaviour) studio24.net
  • 15. Know your environment • URL • Web browser • Operating System / Device • JavaScript support? studio24.net
  • 16.
  • 17. Gather data • Logs • • Application logs • • Webserver access / error logs (Nginx, Apache) Software logs (Varnish, MySQL) File system • Permissions • File space, check with df -h studio24.net
  • 18. Replicate the issue • Replay steps • Can you replicate it? • If not, what’s different? • Is the data the same? • Are there time-based business rules? • Are you using the same web browser/OS? studio24.net
  • 20. PHP errors • Parse errors • Identified by T_* parser tokens • T_PAAMAYIM_NEKUDOTAYIM 
 issues with static operator :: • Sending headers more than once • Segmentation faults • Exception thrown without a stack frame in Unknown on line 0. Yay! studio24.net
  • 21. syntax error, unexpected T_SL … $heredoc = <<<EOD
 My long piece
 of text on a few lines there’s a space here EOD; <<<<<<< HEAD
 $title = "My updated code";
 =======
 $title = "My old code";
 >>>>>>> master
  • 22. syntax error, unexpected $end in /path/to/file.php on line 27 $heredoc = <<<EOD
 My long piece
 of text on a few lines EOD; there’s a space here // More code here
 for ($x=0; $x<10; $x++) {
 // Do stuff
 } echo $something; but the error reports here
  • 23. Syntax errors Easily fixed with a decent IDE or running lint before you deploy code: php -l /path/to/file.php No syntax errors detected in file.php
  • 24. Warning: session_start() [function.session-start]: Cannot send session cookie - headers already sent by… <?php a space here $title = "My title"; // More code here
 for ($x=0; $x<10; $x++) {
 // Do stuff
 } or here will flush the headers ?>
  • 25. Headers sent twice errors Easily fixed by separating PHP from your templates and don’t include final ?> in files that only contain PHP <?php
 // Some code
 $title = "Lots of code here!"; // Look Ma, no closing ?> here!
  • 26. Obscure error messages • Segmentation fault - issue writing to memory, usually an internal bug • Exception thrown without a stack frame - exception thrown in destructors / exception handlers studio24.net
  • 28. Error reporting // Development
 display_errors = On
 display_startup_errors = On
 error_reporting = -1 // E_ALL works PHP5.4+
 log_errors = On // Production
 display_errors = Off
 display_startup_errors = Off
 error_reporting = E_ALL
 log_errors = On
  • 29. Error reporting • Any syntax errors in the file that defines error reporting will ignore these settings • Default is to log errors to Apache ErrorLog location, overrides php.ini error_log setting studio24.net
  • 30. Custom error handling • set_error_handler() - PHP errors • set_exception_handler() - uncaught exceptions • Log errors • Log stack traces • Display friendly page to users • Use monitoring for alerts studio24.net
  • 31. Suppressing errors • @ operator • Don’t do it! • Unless you immediately test the result and deal with it • Suppressed errors still sent to custom error handler • Scream to disable! ini_set('scream.enabled', 1);
  • 33. Quick and dirty • var_dump() and print_r() • Very basic, and not that useful • Needs formatting if complex data echo "<pre>";var_dump($stuff);exit; • Xdebug formats var_dump() studio24.net
  • 35. Developer toolbars • Send JavaScript messages to console.log() • Use Firebug and FirePHP to send messages from PHP to the console • Can profile DB queries via Zend_Db_Profiler_Firebug
  • 36. Framework debug toolbars • Useful for quickly seeing information • May slow application down studio24.net
  • 38. Xdebug • Stack traces for errors • Profiling • Remote debugging • Enabled via zend_extension in php.ini • Don’t use in production! • XHProf is designed for profiling on production servers studio24.net
  • 41. Xdebug remote debugging • Enable in PHP.ini via xdebug.remote_enable=1
 xdebug.remote_port="9000" 1. Set breakpoints 2. Run in browser via session, or browser extension 3. Step through code in IDE studio24.net
  • 42. Remote debugging in PHP Storm
  • 43.
  • 44. Debugging AJAX and Web Services studio24.net
  • 45. CURL • Great for quickly inspecting headers curl --HEAD http://domain.com/url • Redirects are aggressively cached in most browsers, CURL isn't • Use it to debug web services • Use Python’s json.tool to format returned JSON curl -s -H 'X-Auth-Token: AUTH_TOKEN’ 
 -H 'Accept: application/json' 
 'http://domain.com/url' | python -m json.tool studio24.net
  • 46. Charles Proxy • Records all requests • Inspect request and response headers • Makes it really easy to debug AJAX • You can include just your test domain to reduce amount of data captured studio24.net
  • 47.
  • 48. Dealing with SSL • Charles acts as a proxy to allow you to inspect SSL requests. • This is the same as a man-in-the-middle attack • You need to authorise your web browser to allow this • Access third-party URLs directly to do this studio24.net
  • 49. “Nothing clears up a case so much as stating it to another person.” –Sherlock Holmes, The Memoirs of Sherlock Holmes studio24.net
  • 50. If you’re stuck get a fresh view • “Rubber duck” debugging • The act of talking through an issue forces 
 you to think logically studio24.net
  • 52. Problems debugging Legacy software • “Spaghetti code” • No organised class/function system • Duplicated code • Dead code • Global variables • Unescaped SQL (and other security woes) • Suppressed errors studio24.net
  • 53. Strategies • Ensure you have a local development environment • Get the codebase into version control • Remove dead code • Review error logs • Debug with Xdebug to understand code flow • Refactor by making small, incremental changes studio24.net
  • 54. Refactoring It Was Like That When I Got Here: Steps Toward Modernizing a Legacy Codebase http://paul-m-jones.com/archives/2667 ! Modernizing Legacy Applications In PHP https://leanpub.com/mlaphp studio24.net
  • 55. Good practises to help make debugging easier studio24.net
  • 56. Good practises • Use a good IDE (PHPStorm, Zend Studio, NetBeans) • Coding standards • Document your code • Filter In / Escape Out • Defensive coding (test all return values) • Automated testing studio24.net
  • 59. “Chance has put in our way a most singular and whimsical problem, and its solution is its own reward” –Sherlock Holmes, The Adventures of Sherlock Holmes studio24.net
  • 61. Useful links Environment
 http://supportdetails.com/ Browser testing
 http://www.browserstack.com/ 
 http://docs.seleniumhq.org/ PHP parser errors
 http://php.net/manual/en/tokens.php Debug toolbars
 http://www.sitepoint.com/prettyblue-screen/ 
 https://github.com/zendframework/ ZendDeveloperTools 
 http://www.firephp.org/ Debugging and Profiling
 http://xdebug.org/
 https://github.com/facebook/xhprof
 https://github.com/perftools/xhgui Charles Proxy
 http://www.charlesproxy.com/ 
 http://techportal.inviqa.com/ 2013/03/05/manipulating-http-withcharles-proxy/ PHP Standards
 http://www.php-fig.org/ 
 http://www.phptherightway.com/ Refactoring
 http://paul-m-jones.com/archives/ 2667