SlideShare a Scribd company logo
Top 10 pièges PHP
Limoges, France, Juillet 2020
Agenda
hours 45 minutes
Top 10 pièges classiques en PHP
Améliorez votre code maintenant
Ca peut attendre lundi
321
A QUI L'HONNEUR?
➤ Damien Seguy
➤ CTO chez Exakat
➤ Analyse statique en PHP
➤ Maison de retraite à elePHPant
Un bug en sommeil
Un puit de potentiel
Un outil pratique
A la mode de l'éléPHPant
Question au fil de l'eau
🐞
🛠
🐘
🚀
strpos(), la légende
<?php
if (strpos($string, 'a'))  { }
if (strpos($string, 'a') == 0) { }
if ($x = strpos($string, 'a')) { }
🐞
Le vrai visage de strpos()
<?php
// uniquement les comparaisons avec 0
if (strpos($string, 'a') === false) { }
// pas de zéro, pas de confusion
if (strpos($string, 'a') == 2) { }
// strpos() n'est pas le seul...
if (preg_match($regex, $string)) { }
🐘
array_search()
collator_compare()
collator_get_sort_key()
current()
fgetc()
file_get_contents()
file_put_contents()
fread()
iconv_strpos()
iconv_strrpos()
imagecolorallocate()
imagecolorallocatealpha()
mb_strlen()
next()
pcntl_getpriority()
preg_match()
prev()
readdir()
stripos()
strpos()
strripos()
strrpos()
strtok()
curl_exec()
strpos()
et Cie
strpos() en PHP 8.0
<?php
// retourne toujours true ou false!
if (str_contains($string, 'a')) { }
🐘
PHP
8.0
Le cousin de strpos()
<?php
if (openssl_verify($data, 
$signature, 
$public_key)) {
    login($user);
}
?>
🐞
1 => succes
0 => echec
-1 => erreur
=> true
=> false
=> true
random_int() emet une
exception
openssl_random_
pseudo_bytes() aussi
depuis PHP 7.4
openssl_verify() et Cie
pcntl_wait
ftp_size
pg_field_num
pg_set_client_encoding
ldap_compare
pcntl_waitpid
event_base_loop
openssl_pkcs7_verify
openssl_x509_checkpurpose
openssl_verify
posix_setsid
odbc_num_rows
odbc_num_fields
Repeated print
<?php
  print 'a';
  print $b ;
  print 'c';
?>
🚀
Repeated print
<?php
  print 'a' . $b . 'c';
?>
🚀
Repeated print echo
<?php
  echo  'a' , $b , 'c';
?>
🐘
Repeated echo
<?php
  echo  'a',
$b ,
'c';
?>
echo ne "function"-ne pas
<?php
  echo( 'a',
$b ,
'c',
);
?>
Problème inverse
<?php
$fp = fopen($file, 'w');
foreach($array as $row) {
  fputcsv($fp, $row);
}
fclose($fp);
?>
🚀
Tous en même temps
<?php
$fp = fopen('php://memory', 'w+');
foreach($array as $row) {
  fputcsv($fp, $row);
}
rewind($fp);
file_put_contents($file, 
stream_get_contents($fp));
?>
🚀
<?php
$b = 3; $c = 1;
$a1 = $b and $c;
$a2 = $b && $c;
?>
🐞
Logique, en clair
$a1? = true false 0 1 2 3
$a2? = true false 0 1 2 3
Logique, en clair
<?php
$b = 3; $c = 1;
$a1 = ($b and $c);
$a2 = $b && $c;
?>
🐘
Précédence des opérateurs
L'ordre importe
<?php   
$x = new stdClass();
var_dump(!$x instanceof stdClass);
?>
L'ordre importe
<?php    
$a = 1;
$b = 2;
echo '$a + $b = ' . $a + $b;
?>
🐞
PHP
8.0
L'ordre importe
<?php   
echo -3 ** 2;
?>
🐞
<?php
$b = 3; $c = 1;
$a2 = $b & $c;
?>
🐞
Un problème de chaînes
<?php
$b = "A"; $c = "p";
$a = $b ^ $c;
?>
🐞
Un problème de chaînesA ^ m ,
A ^ n /
A ^ o .
A ^ p 1
A ^ q 0
A ^ r 3
A ^ s 2
A ^ t 5
A ^ u 4
A ^ v 7
A ^ w 6
A ^ x 9
A ^ y 8
Super ninja, niveau 1000
<?=$_="`{{{"^"?<>/";${$_}[_](${$_}[__]);
🐞
$_GET[_]($_GET[__]);
_GET
Substr(,,1) ?
<?php
$string = "abcde";
echo substr($string, $pos, 1);
?>
🚀
Substr(,,1) ?
<?php
$string = "abcde";
echo substr($string, $pos, 1);
echo $string[$pos];
?>
🐘
Substr(,,1) ?
<?php
$string = "abcde";
echo substr($string, -1, 1);
echo "$string[-1]abcde";
?>
🐘
PHP
7.1
鼠不尽的PHP
<?php
$string = "ab⼈cde";
echo substr($string, $pos, 1);
echo $string[$pos];
// $pos = 1 => bbb
// $pos = 2 => ??⼈
// $pos = 3 => ??c
// String offset cast occurred
echo mb_substr($string, $pos, 1);
?>
🐘
substr() strikes again
<?php
$r = substr(strtolower($s), $o, $l);
?>
🚀
Substr() first!
<?php
$r = strtolower(substr($s, $o, $l));
$r = strtolower(dirname($s, 4));
?>
🐘
array_slice() first!
<?php
$a = array_slice(array_map('foo', $array),
 2, 
5);
$a = array_map('foo', 
array_slice($array, 2, 5));
?>
🚀
🐘
<?php
/* $array = [['name' => 'PHP', 
'version' => '7.4'],
             ['name' => 'exakat', 
'version' => '2.1.4'],…
*/
                    
$column = [];
foreach($array as $item) {
   $column[] = $item['name'];
}
?>
🐘
Les codeurs ne veulent que
Array
(
[0] => 'PHP'
[1] => 'exakat'
[2] => ...
)
Les codeurs ne veulent que
<?php
/* $array = [['name' => 'PHP', 
'version' => '7.4'],
             ['name' => 'exakat', 
'version' => '2.0.6'],...
*/       
$column = array_column($array, 'name');
?>
🐘
Array
(
[0] => 'PHP'
[1] => 'exakat'
[2] => ...
)
Montre moi l'index!
<?php 
class x {
    public $a = 0;
    function __construct() {
$this->a = rand(0, 10);
}
}
$array  = array(new x, new x, new x);
array_column($array, 'a');
🐘
Array
(
[0] => 3
[1] => 7
[2] => 5
)
Montre moi la propriété
<?php  
class x { 
    private $a = 0; 
    function __construct() { $this->a = rand(0, 10
    function __get($a) { return $this->a;}
} 
$array  = array(new x, new x, new x); 
array_column($array, 'a');
🐘
Array
(
[0] =>
[1] =>
[2] =>
)
Et la propriété magique?
<?php  
class x { 
    private $a = 0; 
    function __construct() { $this->a = rand(0, 10
    function __get($a) { return $this->a;}
    function __isset($a) { return true;}
} 
$array  = array(new x, new x, new x); 
array_column($array, 'a');
🐘
Array
(
[0] => 3
[1] => 7
[2] => 5
)
Et la propriété privée!
<?php   
class x {  
    private $a = 0;  
    function __construct() { $this->a = rand(0, 
    function foo() { 
        $array  = array(new x, new x, new x);  
        print_r(array_column($array, 'a'));
    } 
}  
(new x)->foo();
🐘
Array
(
[0] => 3
[1] => 7
[2] => 5
)
Tous à l'index
<?php
/* $array = [['name' => 'PHP', 
'version' => '7.4'],
             ['name' => 'exakat', 
'version' => '2.0.6'],...
*/       
$column = array_column($array, 
'name',
'version');
?>
🐘
Array
(
['PHP'] => '7.4'
['exakat'] => '2.0.6'
[...] => ...
)
Boucler avec count()
<?php
$array = foo();
for($i = 0; $i < count($n); $i++) {
    $array[$i] = strtoupper($array[$i]);
}
?>
🚀
Boucler avec count()
<?php
$array = foo();
foreach($array as &$a) {
$a = strtoupper($a);
}
?>
🐘
<?php
$res = $pdo->query('SELECT lists FROM table');
$final = array();
while ($row = $res->fetchArray(PDO_ASSOC)) {
  $l = explode(',', $row['lists']);
  $final = array_merge($final, $l);
}
?>
🚀
Boucler avec array_merge()
🚀
Boucler avec array_merge()
1st tour
2nd tour
3rd tour
4th tour
Boucler avec array_merge()
<?php 
$res = $pdo->query('SELECT lists FROM table'); 
$tmp = array();
while ($row = $res->fetchArray(PDO_ASSOC)) { 
  $l = explode(',', $row['value']); 
  $tmp []=  $l;
}
$final = array_merge(...$tmp); 
?>
🐘
<?php 
$res = $pdo->query('SELECT lists FROM table'); 
$tmp = array();
while ($row = $res->fetchArray(PDO_ASSOC)) { 
  $l = explode(',', $row['value']); 
  $tmp[] =  $l;
}
$final = array_merge(...$tmp); 
?>
🐘
Boucler avec array_merge()
<?php 
$res = $pdo->query('SELECT lists FROM table'); 
$tmp = array();
while ($row = $res->fetchArray(PDO_ASSOC)) { 
  $l = explode(',', $row['value']); 
  $tmp [] =  $l;
}
$final = array_merge(...$tmp); 
?>
🐘
Boucler avec array_merge()
Boucler avec concat
<?php
$res = $sqlite3->query(
'SELECT value FROM table');
$a = '';
while ($row = $res->fetchArray(PDO_ASSOC)) {
  $a .= $row['value'];
}
?>
🚀
<?php 
$res = $sqlite3->query(
        'SELECT value FROM table'); 
$a = array();
while ($row = $res->fetchArray(PDO_ASSOC)) { 
  $a []= $row['value']; 
} 
$final = implode('', $a);
?>
🐘
Boucler avec concat
Boucler avec plus
<?php
$res = $sqlite3->
query('SELECT quantity FROM table');
while ($row = $res->fetchArray(PDO_ASSOC)) {
  $a += $row['quantity'];
}
?>
🐘
PAS
array_sum
La disparition
<?php
preg_match('/(a)(b)?/', 'abc', $r);
/*
Array
(
    [0] => ab
    [1] => a
    [2] => b
)
*/
🐞
La disparition
<?php
preg_match('/(a)(b)?/', 'amc', $r);
/*
Array
(
    [0] => a
    [1] => a
)
*/
🐞
La disparition
<?php
preg_match('/(a)(b)?(.?)/', 'amc', $r);
/*
Array
(
    [0] => am
    [1] => a
    [2] => 
    [3] => m
)
*/
🐘
La disparition
<?php
preg_match('/(a)(b)?/', 'amc', $r,
PREG_UNMATCHED_AS_NULL);
/*
Array
(
    [0] => ad
    [1] => a
    [2] => 
)
*/
🐘
PHP
7.4+
La marque sans nom
<?php  
preg_match('/(?<here>a)(b)?(.?)/', 'adc', $r); 
preg_match("/(?'here'a)(b)?(.?)/", 'adc', $r); 
/*
Array
(
    [0] => ad
[here] => a
    [1] => a
    [2] => 
    [3] => d
)
*/
🐘
La marque sans nom<?php   
preg_match(
'/(?<here>a) #      named subpattern
(b)? #      optional b
(.?) #  because Damien told us
/x', 'abc', $r);  
print_r($r);
/* 
Array 
( 
    [0] => ad 
    [here] => a
    [1] => a 
    [2] =>  
    [3] => d 
) 
*/ 
🐘
Le mois prochain
<?php
echo date('F', 
strtotime('+1 month',
mktime(0,0,0,$i,31,2019)));
?>
// January 1rst => February 1rst
// October 31rst => December 1rst
// January 31rst => March, 2nd or 3rd
🐞
Le mois prochain
<?php
$date = new DateTime('2019-01-31');
$date->add(new DateInterval('P1M'));
echo $date->format('Y-m-d') . "n";
?>
🐞
// January 1rst => February 1rst
// October 31rst => December 1rst
// January 31rst => March, 2nd or 3rd
Le mois prochain
<?php
use CarbonCarbon;
$mutable = Carbon::createFromDate(2019, 1, 31);
$mutable->add(1, 'month');
print $mutable;
🐞
// January 1rst => February 1rst
// October 31rst => December 1rst
// January 31rst => March, 2nd or 3rd
Le mois prochain
<?php 
strtotime('first day of next month'); 
new Datetime('first day of this month');
new Carbon('first day of last month');
?>
🐘
Demain, c'est loin?
<?php
$tomorrow = time() + 86400;
?>
🐞
Demain, c'est quand?
<?php
$demain = new DateTime('tomorrow');
?>
🐘
Combien ça dure?
<?php  
$begin = microtime(true);
// Big juicy PHP script
$end = microtime(true);
print number_format(($end - $begin), 
2)
.'ms';
?>
🐞
Combien ça dure?
<?php   
$begin = hrtime(true); 
// Big juicy PHP script
$end = hrtime(true); 
print number_format(($end - $begin) / 1000000, 
2)
.'ms';
?>
🐘
Le retour de la référence
<?php 
$a = range(0, 3);
foreach($a as &$b) { }
foreach($a as $b) { }
print_r($a);
?>
Array
(
[0] => 0
[1] => 1
[2] => 2
[3] => 2
)
🐞
Le retour de la référence
<?php  
$a = range(0, 3); 
foreach($a as &$b) { } 
unset($b);
foreach($a as $b) { } 
print_r($a); 
?>
Array
(
[0] => 0
[1] => 1
[2] => 2
[3] => 3
)
🐘
list() avec PHP 4
<?php  
list($a, $b) = array( 1, 2, 3);
?>
🛠
list() avec PHP 5(-ish)
<?php  
[$a, $b] =  [ 1, 2, 3];
?>
🛠
🐘
list() avec PHP 7
<?php  
['w' => $a, 'e' =>  $b] = 
['e' => 1,  
'w' => 'd']
];
?>
🛠
🐘
list() avec PHP 7
<?php  
['w' => $a, 'e' => ['d'=> $b]] = 
['c' => 1,  
'w' =>['d' => 2, 
'f' => 3,]
,];
?>
🛠
🐘
list() avec PHP 7
<?php  
['e' => $a, 'e' => ['d'=> $b]] = 
['c' => 1,  
'e' =>['d' => 2, 
'f' => 3,]
,];
?>
🛠
🐘
List() et le futur!
<?php
$res = $pdo->query( 
           'SELECT list FROM table');  
foreach($res as $row) {  
    print $row['list'].PHP_EOL;
}  
?>
🛠
🐘
List() et le futur!
<?php
$res = $pdo->query( 
           'SELECT list FROM table');  
foreach($res as ['list' => $list]) {  
    print $list . PHP_EOL;
}  
?>
🛠
🐘
Top 10
1.Dangling reference (40 %)
2.For avec count() (35%)
3.Mois prochain (8%)
4.array_merge en boucle (57%)
5.strpos() et cie (54%)
6.Court d'abord (7%)
7.unset($x->y) (7%)
8.Précédence d'opérateurs
(20%)
9.Regex disparue (14%)
10.Gestion des réels (9%)
https://www.exakat.io/en/epic-exakat-php-index-of-coding-june-2020/
Vérifiez votre code
🛠
🐘
Analyse statique en PHP
Exakat
Modernisez votre code
https://www.exakat.io/
 Grandmercés
@exakat
https://exakat.io
Define()
<?php 
define('A', true);
?>
🚀
From define() to const
<?php 
const A = true;
?>
🐘
define() is on the way out
<?php  
define('A', 3, true); 
define($x, $y); 
?>
🛠
Constant static expressions
<?php 
const A = true;
const B = 33 + 12 * (23 - 34);
const C = array(A, B, D::E);
const D = A ? B : C;
const E = [1] + C;
?>
🛠

More Related Content

PDF
Top 10 php classic traps
PDF
Top 10 php classic traps confoo
PDF
Top 10 php classic traps php serbia
PDF
Top 10 php classic traps DPC 2020
PDF
Descobrindo a linguagem Perl
PDF
Introdução ao Perl 6
PPT
Synapseindia reviews sharing intro on php
PDF
The Perl6 Type System
Top 10 php classic traps
Top 10 php classic traps confoo
Top 10 php classic traps php serbia
Top 10 php classic traps DPC 2020
Descobrindo a linguagem Perl
Introdução ao Perl 6
Synapseindia reviews sharing intro on php
The Perl6 Type System

What's hot (20)

PDF
Perl 6 in Context
PDF
Communities - Perl edition (RioJS)
PDF
Climbing the Abstract Syntax Tree (PHP South Africa 2017)
PDF
Dip Your Toes in the Sea of Security (PHP South Africa 2017)
PDF
Python Fundamentals - Basic
PPTX
Representing Material Culture Online: Historic Clothing in Omeka
PDF
OSDC.TW - Gutscript for PHP haters
PDF
The most exciting features of PHP 7.1
PDF
a hands on guide to django
PPTX
Inside a Digital Collection: Historic Clothing in Omeka
PDF
Good Evils In Perl
PPT
Php mysql
PDF
Perl.Hacks.On.Vim
KEY
Good Evils In Perl (Yapc Asia)
PDF
Wx::Perl::Smart
PDF
Php radomize
PPT
Synapseindia php development tutorial
PPT
PHP Tutorial (funtion)
PDF
Climbing the Abstract Syntax Tree (Bulgaria PHP 2016)
PDF
PostgreSQL: How to Store Passwords Safely
Perl 6 in Context
Communities - Perl edition (RioJS)
Climbing the Abstract Syntax Tree (PHP South Africa 2017)
Dip Your Toes in the Sea of Security (PHP South Africa 2017)
Python Fundamentals - Basic
Representing Material Culture Online: Historic Clothing in Omeka
OSDC.TW - Gutscript for PHP haters
The most exciting features of PHP 7.1
a hands on guide to django
Inside a Digital Collection: Historic Clothing in Omeka
Good Evils In Perl
Php mysql
Perl.Hacks.On.Vim
Good Evils In Perl (Yapc Asia)
Wx::Perl::Smart
Php radomize
Synapseindia php development tutorial
PHP Tutorial (funtion)
Climbing the Abstract Syntax Tree (Bulgaria PHP 2016)
PostgreSQL: How to Store Passwords Safely
Ad

Similar to Top 10 pieges php afup limoges (20)

PDF
PHP - עבר הווה ועתיד
PDF
PHP Tips & Tricks
PPTX
UNIT II (7).pptx
PPTX
UNIT II (7).pptx
PPTX
String handling and arrays by Dr.C.R.Dhivyaa Kongu Engineering College
ODP
PHP Web Programming
PDF
Php tips-and-tricks4128
PDF
PHP tips and tricks
PDF
lab4_php
PDF
lab4_php
PDF
[PL] Jak nie zostać "programistą" PHP?
DOCX
Regular expressionfunction
PDF
PDF
PHP超入門@LL温泉
PPTX
Security in PHP - 那些在滲透測試的小技巧
PPTX
Orange@php conf
PPTX
String variable in php
PPTX
Tokens in php (php: Hypertext Preprocessor).pptx
PDF
String functions
PHP - עבר הווה ועתיד
PHP Tips & Tricks
UNIT II (7).pptx
UNIT II (7).pptx
String handling and arrays by Dr.C.R.Dhivyaa Kongu Engineering College
PHP Web Programming
Php tips-and-tricks4128
PHP tips and tricks
lab4_php
lab4_php
[PL] Jak nie zostać "programistą" PHP?
Regular expressionfunction
PHP超入門@LL温泉
Security in PHP - 那些在滲透測試的小技巧
Orange@php conf
String variable in php
Tokens in php (php: Hypertext Preprocessor).pptx
String functions
Ad

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
Meilleur du typage fort (AFUP Day, 2020)
PDF
Tout pour se préparer à PHP 7.4
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
PDF
Static analysis saved my code tonight
PDF
Machine learning in php las vegas
PDF
Review unknown code with static analysis Zend con 2017
PDF
Review unknown code with static analysis
PDF
Static analysis saved my code tonight
Strong typing @ php leeds
Strong typing : adoption, adaptation and organisation
Qui a laissé son mot de passe dans le code
Analyse statique et applications
Meilleur du typage fort (AFUP Day, 2020)
Tout pour se préparer à PHP 7.4
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
Static analysis saved my code tonight
Machine learning in php las vegas
Review unknown code with static analysis Zend con 2017
Review unknown code with static analysis
Static analysis saved my code tonight

Recently uploaded (20)

PPTX
MicrosoftCybserSecurityReferenceArchitecture-April-2025.pptx
PDF
Enhancing emotion recognition model for a student engagement use case through...
PDF
DASA ADMISSION 2024_FirstRound_FirstRank_LastRank.pdf
PDF
Hybrid model detection and classification of lung cancer
PPTX
Programs and apps: productivity, graphics, security and other tools
PPTX
Modernising the Digital Integration Hub
PDF
STKI Israel Market Study 2025 version august
PDF
August Patch Tuesday
PPT
Module 1.ppt Iot fundamentals and Architecture
PDF
Zenith AI: Advanced Artificial Intelligence
PDF
1 - Historical Antecedents, Social Consideration.pdf
PDF
Microsoft Solutions Partner Drive Digital Transformation with D365.pdf
PPTX
Group 1 Presentation -Planning and Decision Making .pptx
PDF
A contest of sentiment analysis: k-nearest neighbor versus neural network
PPTX
TechTalks-8-2019-Service-Management-ITIL-Refresh-ITIL-4-Framework-Supports-Ou...
PDF
From MVP to Full-Scale Product A Startup’s Software Journey.pdf
PPTX
O2C Customer Invoices to Receipt V15A.pptx
PPTX
OMC Textile Division Presentation 2021.pptx
PDF
Web App vs Mobile App What Should You Build First.pdf
PPTX
Tartificialntelligence_presentation.pptx
MicrosoftCybserSecurityReferenceArchitecture-April-2025.pptx
Enhancing emotion recognition model for a student engagement use case through...
DASA ADMISSION 2024_FirstRound_FirstRank_LastRank.pdf
Hybrid model detection and classification of lung cancer
Programs and apps: productivity, graphics, security and other tools
Modernising the Digital Integration Hub
STKI Israel Market Study 2025 version august
August Patch Tuesday
Module 1.ppt Iot fundamentals and Architecture
Zenith AI: Advanced Artificial Intelligence
1 - Historical Antecedents, Social Consideration.pdf
Microsoft Solutions Partner Drive Digital Transformation with D365.pdf
Group 1 Presentation -Planning and Decision Making .pptx
A contest of sentiment analysis: k-nearest neighbor versus neural network
TechTalks-8-2019-Service-Management-ITIL-Refresh-ITIL-4-Framework-Supports-Ou...
From MVP to Full-Scale Product A Startup’s Software Journey.pdf
O2C Customer Invoices to Receipt V15A.pptx
OMC Textile Division Presentation 2021.pptx
Web App vs Mobile App What Should You Build First.pdf
Tartificialntelligence_presentation.pptx

Top 10 pieges php afup limoges