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


•...
What causes bugs

First steps

PHP errors

Error reporting

Debugging in PHP

Remote debugging

AJAX and Web Services

Leg...
“Debugging is a methodical process of finding
and reducing the number of bugs, or defects,
in a computer program or a piece...
“Debugging is a methodical process of finding
and reducing the number of bugs, or defects,
in a computer program or a piece...
!

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)

•

Cl...
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 o...
Understand the issue

1. What did you do?

(how to reproduce the issue)

2. What happened?

(what’s wrong)

3. What was su...
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, MyS...
Replicate the issue
•

Replay steps

•

Can you replicate it?

•

If not, what’s different?
•

Is the data the same?

•

A...
PHP errors

studio24.net
PHP errors	
•

Parse errors
•

Identified by T_* parser tokens

•

T_PAAMAYIM_NEKUDOTAYIM 

issues with static operator ::
...
syntax error, unexpected T_SL …
$heredoc = <<<EOD

My long piece

of text on a few lines

there’s a space here

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

My long piece

of text on a few lines
EOD;...
Syntax errors	
Easily fixed with a decent IDE or running lint before you deploy code:

php -l /path/to/file.php
No syntax e...
Warning: session_start() [function.session-start]: Cannot
send session cookie - headers already sent by…
<?php
a space her...
Headers sent twice errors
Easily fixed by separating PHP from your templates 

and don’t include final ?> in files that only ...
Obscure error messages
•

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

•

Exception thrown witho...
Error reporting

studio24.net
Error reporting
// Development

display_errors = On

display_startup_errors = On

error_reporting = -1 // E_ALL works PHP5...
Error reporting	
•

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

•

Default is to ...
Custom error handling
•

set_error_handler() - PHP errors

•

set_exception_handler() - uncaught exceptions

•

Log errors...
Suppressing errors
•

@ operator

•

Don’t do it!

•

Unless you immediately test the result and deal with it

•

Suppress...
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 ...
Displaying errors

Pretty Blue Screen
Developer toolbars
•

Send JavaScript messages to console.log()

•

Use Firebug and FirePHP to send messages from PHP to
t...
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 us...
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. ...
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 mo...
Charles Proxy
•

Records all requests

•

Inspect request and response headers

•

Makes it really easy to debug AJAX

•

...
Dealing with SSL
•

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

•

This is the same as a man-in-the-mid...
“Nothing clears up a case so much as stating it
to another person.”
–Sherlock Holmes, The Memoirs of Sherlock Holmes

stud...
If you’re stuck get a fresh view
•

“Rubber duck” debugging

•

The act of talking through an issue forces 

you to think ...
Debugging Legacy software

studio24.net
Problems debugging Legacy software	
•

“Spaghetti code”

•

No organised class/function system

•

Duplicated code

•

Dea...
Strategies
•

Ensure you have a local development environment

•

Get the codebase into version control

•

Remove dead co...
Refactoring
It Was Like That When I Got Here: Steps
Toward Modernizing a Legacy Codebase

http://paul-m-jones.com/archives...
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 ...
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, Th...
Thanks!
@simonrjones

!

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

http://supportdetails.com/
Browser testing

http://www.browserstack.com/ 

http://docs.selenium...
Php Debugging from the Trenches
Php Debugging from the Trenches
Php Debugging from the Trenches
Upcoming SlideShare
Loading in...5
×

Php Debugging from the Trenches

2,724

Published on

A tour of what makes up a bug, how to replicate issues, PHP specific bugs, and practical techniques on how to tackle them.

Published in: Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
2,724
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
6
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Php Debugging from the Trenches

  1. 1. PHP Debugging from the Trenches PHP Cambridge, 24 Feb 2014 Simon R Jones, Studio 24
  2. 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. 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. 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. 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. 6. ! We want to avoid this! WSOD: White Screen Of Death!
  7. 7. Which makes you feel like this..
  8. 8. While we’d rather be happily solving problems
  9. 9. What causes bugs? studio24.net
  10. 10. Grace Hopper http://www.history.navy.mil/photos/pers-us/uspers-h/ g-hoppr.htm
  11. 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
  12. 12. First steps studio24.net
  13. 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. 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. 15. Know your environment • URL • Web browser • Operating System / Device • JavaScript support? studio24.net
  16. 16. 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
  17. 17. 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
  18. 18. PHP errors studio24.net
  19. 19. 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
  20. 20. 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
  21. 21. 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
  22. 22. 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
  23. 23. 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 ?>
  24. 24. 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!
  25. 25. 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
  26. 26. Error reporting studio24.net
  27. 27. 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
  28. 28. 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
  29. 29. 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
  30. 30. 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);
  31. 31. Debugging in PHP studio24.net
  32. 32. 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
  33. 33. Displaying errors Pretty Blue Screen
  34. 34. 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
  35. 35. Framework debug toolbars • Useful for quickly seeing information • May slow application down studio24.net
  36. 36. Symfony toolbar
  37. 37. 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
  38. 38. Xdebug stack trace
  39. 39. Remote debugging studio24.net
  40. 40. 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
  41. 41. Remote debugging in PHP Storm
  42. 42. Debugging AJAX and Web Services studio24.net
  43. 43. 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
  44. 44. 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
  45. 45. 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
  46. 46. “Nothing clears up a case so much as stating it to another person.” –Sherlock Holmes, The Memoirs of Sherlock Holmes studio24.net
  47. 47. 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
  48. 48. Debugging Legacy software studio24.net
  49. 49. 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
  50. 50. 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
  51. 51. 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
  52. 52. Good practises to help make debugging easier studio24.net
  53. 53. 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
  54. 54. PHPUnit Unit testing
  55. 55. Selenium Browser testing
  56. 56. “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
  57. 57. Thanks! @simonrjones ! http://www.slideshare.net/simonrjones/TODO
  58. 58. 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
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×