SlideShare a Scribd company logo
PHP Static Code Review 
München, Deutschland, October 27th
Definition 
• A kind of code analysis where the code is 
reviewed without running it. 
• Just like we would do ourselves! 
• Where can it help
Who is speaking? 
• Damien Seguy 
• CTO at exakat 
• Phather of the plush toy 
elePHPant 
• Working on automated 
code audit
PHP Static Code Review
PHP tokenizer 
<?php 
function x($a) { 
return $a; 
} 
x(1, 2); 
?> 
( 
[0] => 372 
[1] => <?php 
[2] => 1 
) 
[1] => Array 
( 
[0] => 334 
[1] => function 
[2] => 2 
) 
[2] => Array 
( 
[0] => 375 
[1] => 
[2] => 2 
) 
[3] => Array 
( 
[0] => 307 
[1] => x 
[2] => 2 
) 
function token 
whitespace token 
T_STRING 
Total : 30 tokens
Internals 
Code 
AST 
Analyze Report
PHP Static Code Review
<?php 
function x($a) { 
return $a; 
} 
x(1, 2); 
?>
Found 
• Dead code 
• Undefined structures 
• Unused structures 
• Illogical exp. 
• Slow code 
• Bad practices 
• Unsafe code 
• Maintainability 
• Bug issue 
• Ancient style 
• Uninitialized vars 
• Taint propagation
<?php 
switch ($this->consume()) 
{ 
case "x09": 
case "x0A": 
case "x0B": 
case "x0B": 
case "x0C": 
case "x20": 
case "x3C": 
case "x26": 
case false: 
break; 
case "x23": 
switch ($this->consume()) 
{ 
case "x78": 
case "x58": 
$range = '0123456789ABCDEFabcdef'; 
return $a++; 
break; 
} 
} 
?>
<?php 
class x extends y { 
function array_single_quote($array) { 
return parent::array_map("single_quote", $array); 
} 
} 
/* Calling each other */ 
function debug_dump_backtrace($msg='Calling BackTrace',$die=false) { 
debug_sysmsg($msg); 
error($msg,'note',null,$die,true); 
} 
/* Defined in another file */ 
function debug_sysmsg($msg) { 
system_message(array(‘title'=>_('Debug'),'body'=>$msg,'type'=>'debug')); 
debug_dump_backtrace($msg, true); 
} 
?>
protected function openString($end, &$out=null, $nestingOpen, $rejectStrs = null) { 
$nestingLevel = $count = 0; 
$content = array(); 
while ($this->match($patt, $m, false)) { 
$tok = $m[2]; 
if ($tok == "@{" && $this->interpolation($inter)) { 
$content[] = $inter; 
continue; 
} 
if (!empty($rejectStrs) && in_array($tok, $rejectStrs)) { 
$ount = null; 
break; 
} 
$content[] = $tok; 
$count += strlen($tok); 
} 
$this->eatWhiteDefault = $oldWhite; 
if (count($content) == 0) return false; 
$out = array("string", "", $content); 
return true; 
}
Spot bugs early 
Code Test PreProd Production 
Run it at commit Run it as audit
When does it help 
• Audit external libraries 
• Help port to a new system 
• Search for weak code fragments 
• Hint at refactoring
Report 
• Bugs 
• Useless code 
• Suggestions
Bugs 
<?php 
if($content = file_get_contents($file)) { 
$content = trim($content); 
$content = substr($content, -2) == ‘>’ ? substr($content, 0, 
-2) : $content; 
} 
?>
Useless code 
<?php 
// inside a legit class 
$this->module->xmlRequest; 
$_G['setting']['debug']; 
if (!empty($a) && in_array($tokens, $a)) { 
false; 
} 
?>
Suggestions 
<?php 
// Nested ternary should be turned into if then structures 
$operation == 'ENCODE' ? sprintf('%010d', $expiry ? $expiry + time( ) : 0) . substr(md5 
($string . $egiskeys), 0, 16) . $string : base64_decode(substr($string, $key_length)) 
// Multiply by one is useless 
SetCache($prefix, $key, $row, 60*60*1); 
$xtime *= 1; 
// Backward compatible syntax 
$bits = split('.', $string); 
$y = $bits[0]; 
// Available syntax with recent PHP versions 
$y = split('.', $string)[0]; 
?>
Where it doesn’t help 
• Unit tests 
• Architecture 
• Old traditions that won’t change 
• Semantic errors
Architecture 
• No framework context 
• Conception is done before coding 
• Of course! 
• Static audit will report standards, 
not norms
Old traditions 
<?php 
$pna = explode(')(', $pn); 
while (list($k, $v) = each($pna)) { 
$lst = explode('"', $v); 
if (isset($lst[3])) { 
$pn[$lst[1]] = $lst[3]; 
} else { 
$pn[$lst[1]] = ''; 
} 
} 
?> 
10 % of nowadays applications uses this instead of foreach()
Old traditions 
<?php 
defined('WEB_ROOT') || define('WEB_ROOT', dirname(__FILE_)); 
// also classic usage 
fopen($pFilename, 'w') or die("can't open file"); 
?>
Semantic errors 
<?php 
$babycarriage = new carriage(); 
$wheel1 = new Racingwheel(); 
$wheel2 = new Racingwheel(); 
$wheel3 = new Racingwheel(); 
$wheel4 = new Rhinoceros(); 
$babycarriage->installWheels($wheel1, 
$wheel2, 
$wheel3, 
$wheel4); 
?> 
Undefined classes : Vehicle, Racingwheel, Rhinoceros
Available analyzers 
• PHP code sniffer 
• PHP MD 
• Scrutinizer-ci 
• Fortify 
• insight from Sensio 
• Exakat
damien.seguy@ 
gmail.com 
http://www.slideshare.net/dseguy

More Related Content

PDF
Drush. Secrets come out.
PDF
Security Meetup 22 октября. «Реверс-инжиниринг в Enterprise». Алексей Секрето...
PDF
PHP Object Injection Vulnerability in WordPress: an Analysis
PDF
Rust ⇋ JavaScript
PDF
Обзор фреймворка Twisted
KEY
Php 101: PDO
PDF
Elm: give it a try
PPTX
Nantes Jug - Java 7
Drush. Secrets come out.
Security Meetup 22 октября. «Реверс-инжиниринг в Enterprise». Алексей Секрето...
PHP Object Injection Vulnerability in WordPress: an Analysis
Rust ⇋ JavaScript
Обзор фреймворка Twisted
Php 101: PDO
Elm: give it a try
Nantes Jug - Java 7

What's hot (17)

PDF
Cycle.js: Functional and Reactive
PDF
Coding website
PPT
PHP and MySQL
KEY
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
PDF
Models and Service Layers, Hemoglobin and Hobgoblins
PDF
Command Bus To Awesome Town
PDF
JavaScript and the AST
PDF
R57shell
PDF
Your code is not a string
PDF
PhoneGap: Local Storage
KEY
Object Calisthenics Applied to PHP
PDF
PHP for Adults: Clean Code and Object Calisthenics
PDF
Things I Believe Now That I'm Old
PDF
Practical JavaScript Programming - Session 1/8
PDF
Practical JavaScript Programming - Session 7/8
PPT
Quebec pdo
PDF
JavaOne 2017 | JShell: The Ultimate Missing Tool
Cycle.js: Functional and Reactive
Coding website
PHP and MySQL
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
Models and Service Layers, Hemoglobin and Hobgoblins
Command Bus To Awesome Town
JavaScript and the AST
R57shell
Your code is not a string
PhoneGap: Local Storage
Object Calisthenics Applied to PHP
PHP for Adults: Clean Code and Object Calisthenics
Things I Believe Now That I'm Old
Practical JavaScript Programming - Session 1/8
Practical JavaScript Programming - Session 7/8
Quebec pdo
JavaOne 2017 | JShell: The Ultimate Missing Tool
Ad

Viewers also liked (20)

PDF
Functions - complex first class citizen
DOC
Coding standards php
KEY
Php Code Audits (PHP UK 2010)
PDF
Web UI performance tuning
PDF
Coding Best practices (PHP)
PPTX
Modular & Event driven UI Architecture
PDF
PHP CODING STANDARDS
PPTX
Coding Standard And Code Review
PDF
PHPcon Poland - Static Analysis of PHP Code – How the Heck did I write so man...
PDF
JavaScript and UI Architecture Best Practices
PPTX
Modern Static Code Analysis in PHP
PDF
Refactoring Legacy Code
PDF
Component Based UI Architecture - Alex Moldovan
PDF
Modern UI Architecture_ Trends and Technologies in Web Development
PPTX
UI Architecture & Web Performance
DOCX
Code review guidelines
PPT
Selenium Architecture
PDF
Content Design, UI Architecture and Content-UI-Mapping
PPTX
PHP & JavaScript & CSS Coding style
PDF
AngularJS application architecture
Functions - complex first class citizen
Coding standards php
Php Code Audits (PHP UK 2010)
Web UI performance tuning
Coding Best practices (PHP)
Modular & Event driven UI Architecture
PHP CODING STANDARDS
Coding Standard And Code Review
PHPcon Poland - Static Analysis of PHP Code – How the Heck did I write so man...
JavaScript and UI Architecture Best Practices
Modern Static Code Analysis in PHP
Refactoring Legacy Code
Component Based UI Architecture - Alex Moldovan
Modern UI Architecture_ Trends and Technologies in Web Development
UI Architecture & Web Performance
Code review guidelines
Selenium Architecture
Content Design, UI Architecture and Content-UI-Mapping
PHP & JavaScript & CSS Coding style
AngularJS application architecture
Ad

Similar to PHP Static Code Review (20)

PDF
Automated code audits
KEY
PHP security audits
PDF
From mysql to MongoDB(MongoDB2011北京交流会)
PPTX
ES6 is Nigh
PDF
Php tips-and-tricks4128
PDF
Internationalizing CakePHP Applications
PDF
Building Testable PHP Applications
KEY
PHPSpec BDD for PHP
PDF
PDF
PHP tips and tricks
PPTX
Taming that client side mess with Backbone.js
PPTX
Apache Spark in your likeness - low and high level customization
PDF
Security Meetup 22 октября. «PHP Unserialize Exploiting». Павел Топорков. Лаб...
KEY
Can't Miss Features of PHP 5.3 and 5.4
PDF
Zend Certification PHP 5 Sample Questions
PDF
RubyEnRails2007 - Dr Nic Williams - DIY Syntax
PDF
Unit testing with zend framework tek11
KEY
Workshop quality assurance for php projects tek12
PDF
Metaprogramovanie #1
KEY
CoffeeScript - A Rubyist's Love Affair
Automated code audits
PHP security audits
From mysql to MongoDB(MongoDB2011北京交流会)
ES6 is Nigh
Php tips-and-tricks4128
Internationalizing CakePHP Applications
Building Testable PHP Applications
PHPSpec BDD for PHP
PHP tips and tricks
Taming that client side mess with Backbone.js
Apache Spark in your likeness - low and high level customization
Security Meetup 22 октября. «PHP Unserialize Exploiting». Павел Топорков. Лаб...
Can't Miss Features of PHP 5.3 and 5.4
Zend Certification PHP 5 Sample Questions
RubyEnRails2007 - Dr Nic Williams - DIY Syntax
Unit testing with zend framework tek11
Workshop quality assurance for php projects tek12
Metaprogramovanie #1
CoffeeScript - A Rubyist's Love Affair

More from Damien Seguy (20)

PDF
Strong typing @ php leeds
PPTX
Strong typing : adoption, adaptation and organisation
PDF
Qui a laissé son mot de passe dans le code
PDF
Analyse statique et applications
PDF
Top 10 pieges php afup limoges
PDF
Top 10 php classic traps DPC 2020
PDF
Meilleur du typage fort (AFUP Day, 2020)
PDF
Top 10 php classic traps confoo
PDF
Tout pour se préparer à PHP 7.4
PDF
Top 10 php classic traps php serbia
PDF
Top 10 php classic traps
PDF
Top 10 chausse trappes
PDF
Code review workshop
PDF
Understanding static analysis php amsterdam 2018
PDF
Review unknown code with static analysis php ce 2018
PDF
Everything new with PHP 7.3
PDF
Php 7.3 et ses RFC (AFUP Toulouse)
PDF
Tout sur PHP 7.3 et ses RFC
PDF
Review unknown code with static analysis php ipc 2018
PDF
Code review for busy people
Strong typing @ php leeds
Strong typing : adoption, adaptation and organisation
Qui a laissé son mot de passe dans le code
Analyse statique et applications
Top 10 pieges php afup limoges
Top 10 php classic traps DPC 2020
Meilleur du typage fort (AFUP Day, 2020)
Top 10 php classic traps confoo
Tout pour se préparer à PHP 7.4
Top 10 php classic traps php serbia
Top 10 php classic traps
Top 10 chausse trappes
Code review workshop
Understanding static analysis php amsterdam 2018
Review unknown code with static analysis php ce 2018
Everything new with PHP 7.3
Php 7.3 et ses RFC (AFUP Toulouse)
Tout sur PHP 7.3 et ses RFC
Review unknown code with static analysis php ipc 2018
Code review for busy people

Recently uploaded (20)

PDF
Encapsulation theory and applications.pdf
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
A comparative analysis of optical character recognition models for extracting...
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PPTX
Big Data Technologies - Introduction.pptx
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Empathic Computing: Creating Shared Understanding
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PPTX
sap open course for s4hana steps from ECC to s4
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Spectral efficient network and resource selection model in 5G networks
PPTX
A Presentation on Artificial Intelligence
PPT
Teaching material agriculture food technology
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PPTX
Cloud computing and distributed systems.
Encapsulation theory and applications.pdf
MIND Revenue Release Quarter 2 2025 Press Release
A comparative analysis of optical character recognition models for extracting...
Dropbox Q2 2025 Financial Results & Investor Presentation
Big Data Technologies - Introduction.pptx
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Building Integrated photovoltaic BIPV_UPV.pdf
The AUB Centre for AI in Media Proposal.docx
Encapsulation_ Review paper, used for researhc scholars
Empathic Computing: Creating Shared Understanding
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
sap open course for s4hana steps from ECC to s4
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Spectral efficient network and resource selection model in 5G networks
A Presentation on Artificial Intelligence
Teaching material agriculture food technology
Digital-Transformation-Roadmap-for-Companies.pptx
Cloud computing and distributed systems.

PHP Static Code Review

  • 1. PHP Static Code Review München, Deutschland, October 27th
  • 2. Definition • A kind of code analysis where the code is reviewed without running it. • Just like we would do ourselves! • Where can it help
  • 3. Who is speaking? • Damien Seguy • CTO at exakat • Phather of the plush toy elePHPant • Working on automated code audit
  • 5. PHP tokenizer <?php function x($a) { return $a; } x(1, 2); ?> ( [0] => 372 [1] => <?php [2] => 1 ) [1] => Array ( [0] => 334 [1] => function [2] => 2 ) [2] => Array ( [0] => 375 [1] => [2] => 2 ) [3] => Array ( [0] => 307 [1] => x [2] => 2 ) function token whitespace token T_STRING Total : 30 tokens
  • 6. Internals Code AST Analyze Report
  • 8. <?php function x($a) { return $a; } x(1, 2); ?>
  • 9. Found • Dead code • Undefined structures • Unused structures • Illogical exp. • Slow code • Bad practices • Unsafe code • Maintainability • Bug issue • Ancient style • Uninitialized vars • Taint propagation
  • 10. <?php switch ($this->consume()) { case "x09": case "x0A": case "x0B": case "x0B": case "x0C": case "x20": case "x3C": case "x26": case false: break; case "x23": switch ($this->consume()) { case "x78": case "x58": $range = '0123456789ABCDEFabcdef'; return $a++; break; } } ?>
  • 11. <?php class x extends y { function array_single_quote($array) { return parent::array_map("single_quote", $array); } } /* Calling each other */ function debug_dump_backtrace($msg='Calling BackTrace',$die=false) { debug_sysmsg($msg); error($msg,'note',null,$die,true); } /* Defined in another file */ function debug_sysmsg($msg) { system_message(array(‘title'=>_('Debug'),'body'=>$msg,'type'=>'debug')); debug_dump_backtrace($msg, true); } ?>
  • 12. protected function openString($end, &$out=null, $nestingOpen, $rejectStrs = null) { $nestingLevel = $count = 0; $content = array(); while ($this->match($patt, $m, false)) { $tok = $m[2]; if ($tok == "@{" && $this->interpolation($inter)) { $content[] = $inter; continue; } if (!empty($rejectStrs) && in_array($tok, $rejectStrs)) { $ount = null; break; } $content[] = $tok; $count += strlen($tok); } $this->eatWhiteDefault = $oldWhite; if (count($content) == 0) return false; $out = array("string", "", $content); return true; }
  • 13. Spot bugs early Code Test PreProd Production Run it at commit Run it as audit
  • 14. When does it help • Audit external libraries • Help port to a new system • Search for weak code fragments • Hint at refactoring
  • 15. Report • Bugs • Useless code • Suggestions
  • 16. Bugs <?php if($content = file_get_contents($file)) { $content = trim($content); $content = substr($content, -2) == ‘>’ ? substr($content, 0, -2) : $content; } ?>
  • 17. Useless code <?php // inside a legit class $this->module->xmlRequest; $_G['setting']['debug']; if (!empty($a) && in_array($tokens, $a)) { false; } ?>
  • 18. Suggestions <?php // Nested ternary should be turned into if then structures $operation == 'ENCODE' ? sprintf('%010d', $expiry ? $expiry + time( ) : 0) . substr(md5 ($string . $egiskeys), 0, 16) . $string : base64_decode(substr($string, $key_length)) // Multiply by one is useless SetCache($prefix, $key, $row, 60*60*1); $xtime *= 1; // Backward compatible syntax $bits = split('.', $string); $y = $bits[0]; // Available syntax with recent PHP versions $y = split('.', $string)[0]; ?>
  • 19. Where it doesn’t help • Unit tests • Architecture • Old traditions that won’t change • Semantic errors
  • 20. Architecture • No framework context • Conception is done before coding • Of course! • Static audit will report standards, not norms
  • 21. Old traditions <?php $pna = explode(')(', $pn); while (list($k, $v) = each($pna)) { $lst = explode('"', $v); if (isset($lst[3])) { $pn[$lst[1]] = $lst[3]; } else { $pn[$lst[1]] = ''; } } ?> 10 % of nowadays applications uses this instead of foreach()
  • 22. Old traditions <?php defined('WEB_ROOT') || define('WEB_ROOT', dirname(__FILE_)); // also classic usage fopen($pFilename, 'w') or die("can't open file"); ?>
  • 23. Semantic errors <?php $babycarriage = new carriage(); $wheel1 = new Racingwheel(); $wheel2 = new Racingwheel(); $wheel3 = new Racingwheel(); $wheel4 = new Rhinoceros(); $babycarriage->installWheels($wheel1, $wheel2, $wheel3, $wheel4); ?> Undefined classes : Vehicle, Racingwheel, Rhinoceros
  • 24. Available analyzers • PHP code sniffer • PHP MD • Scrutinizer-ci • Fortify • insight from Sensio • Exakat