SlideShare a Scribd company logo
1 of 36
Download to read offline
PHP tips and tricks
  Skien, Norge, June 7th 2007
Agenda

  Tips and Tricks from PHP
     No need for anything else than standard distribution
     All for PHP 5
     ( but lots of it is also valid in PHP 4 )

     The month of PHP functions
Who is speaking?

    Damien Séguy
       Nexen Services, eZ publish silver partner for hosting
       PHP / MySQL services
       Redacteur en chef of www.nexen.net
       Phather of an plush Elephpant
    http://www.nexen.net/english.php
Nod when you know about it
Random stuff


  rand() and mt_rand()
  array_rand() : extract info from an array
    extract keys!

  shuffle() : shuffle an array before deal
  str_shuffle() : shuffle a string
Random stuff

                                Array
 <?php                          (
 $a = range('a','d');               [0]   =>   c
 shuffle($a);                       [1]   =>   d
                                    [2]   =>   b
 print_r($a);                       [3]   =>   a
                                )
 print_r(array_rand($a,3));     Array
                                (
 print str_shuffle('abcdef');       [0]   => 0
 // eabdcf                          [1]   => 1
 ?>                                 [2]   => 3
                                )
Arrays combinaisons

       array_combine() : turn two arrays into one
         Inverse to array_keys() and array_values()
 <?php
 $a = array('green', 'red', 'yellow');
 $b = array('avocado', 'apple', 'banana');
 $c = array_combine($a, $b);
                     Array
 print_r($c);
                     (
 ?>
                         [green] => avocado
                         [red]    => apple
                         [yellow] => banana
                     )
Arrays combinaisons

         array_combine() : turn two arrays into one
         PDO::FETCH_KEY_PAIR :
         combine 2 columns in a hash

 <?php
 $html = file_get_contents(quot;http://www.php.net/quot;);

 //'<a href=quot;http://php.netquot;>PHP</a>';
 if (preg_match_all(
 '#<a href=quot;(http://[^quot;/?]+/).*?>(.*?)</a>#s', $html, $r)) {
     $liste = array_combine($r[2], $r[1]);
 }
 print_r($liste);

 ?>
Arrays as SQL

        array_count_values() : makes easy stats
        Works like a GROUP BY and COUNT()

<?php
   $array = array(1, quot;heiquot;, 1, quot;takkquot;, quot;heiquot;);
   print_r(array_count_values($array));
?>
                                     Array
                                     (
          sort       r   u
                                         [1] => 2
                     r   u
                                         [hei] => 2
           k    k   kr  uk
                                         [takk] => 1
           a    a   ar  ua           )
Arrays as SQL

                                        Array
                                        (
     array_multisort() : sort several       [0]   =>   2
     arrays at once                         [1]   =>   3
                                            [2]   =>   4
     Works like a ORDER BY
                                            [3]   =>   5
<?php                                   )
$ar1 = array(5,4,3,2);                  Array
$ar2 = array('a','b','c','d');          (
array_multisort($ar1, $ar2);                [0]   =>   d
array_multisort($ar1,                       [1]   =>   c
           SORT_ASC,SORT_STRING,            [2]   =>   b
           $ar2);                           [3]   =>   a
?>                                      )
Fast dir scans



   scandir(‘/tmp’, true);
     Include name sorting

     Replace opendir, readdir, closedir and a loop!

   glob(‘*.html’);
   Simply move the loop out of sight
Fast dir scans

Array
(
    [0]   =>   sess_um8rgjj10f6qvuck91rf36srj7
    [1]   =>   sess_u58rgul68305uqfe48ic467276
    [2]   =>   mysql.sock
                           <?php
    [3]   =>   ..
                           print_r(scandir('/tmp/', 1));
    [4]   =>   .
                           print_r(glob('/tmp/sess_*'));
)
                           ?>
Array
(
    [0]   => /tmp/sess_um8rgjj10f6qvuck91rf36srj7
    [1]   => /tmp/sess_u58rgul68305uqfe48ic467276
)
URL operations


  parse_url()
    break down into details

    do not make any check

  parse_str()
    split a query string

    separate and decode, as long as it can

    Fill up an array or globals
URL


<?php
$url = 'http://login:pass@www.site.com/
         path/file.php?a=2+&b%5B%5D=
         %E5%AF%B9%E4%BA%86%EF%BC%81#ee';
$d = parse_url($url);
print_r($d);

parse_str($d[quot;queryquot;]);
var_dump($GLOBALS[quot;bquot;]);
?>
URL

(
    [scheme] => http
    [host] => www.site.com
    [user] => login
    [pass] => pass
    [path] => /path/file.php
    [query] => a=2&b%5B%5D=%E5%AF%B9%E4%BA%86%EF%BC%81
    [fragment] => ee
)
array(1) {
  [0]=>
  string(9) quot;     quot;
}
URL validations


   scheme : list your own
   host : checkdnsrr() to check
   path : realpath() + doc root (beware of mod_rewrite)
   query : parse_str()
     beware of the second argument!

     don’t handle &amp;
URL rebuilding

     http_build_query()
          rebuild your query

          takes into account encoding and arrays

     <?php
     print http_build_query(
           array_merge($_GET ,
           array(' de ' => '                 ')));
     ?>

     +de+=%E5%AF%B9%E4%BA%86%EF%BC%81
URL testing

 <?php
    get_headers('http://localhost/logo.png');
 ?>

     Array
     (
         [0]   =>   HTTP/1.1 200 OK
         [1]   =>   Date: Mon, 12 Feb 2007 02:24:23 GMT
         [2]   =>   Server: Apache/1.3.33 (Darwin) PHP/5.2.1
         [3]   =>   X-Powered-By: eZ publish
         [4]   =>   Last-Modified: Fri, 30 Sep 2005 09:11:28 GMT
         [5]   =>   ETag: quot;f6f2a-dbb-433d0140quot;
         [6]   =>   Accept-Ranges: bytes
         [7]   =>   Content-Length: 3515
         [8]   =>   Connection: close
         [9]   =>   Content-Type: image/png
     )
PHP is dynamic

    Variables variables
    <?php
      $x = 'y';
      $y = 'z';
      $z = 'a';

      echo $x;  // displays y
      echo $$x;  // displays z
      echo $$$x; // displays a
    ?>
Variable constants

      Still one definition
      Dynamic constant value
  <?php
    define (quot;CONSTANTquot;, 'eZ Conference');
    echo CONSTANT;
    echo constant(quot;CONSTANTquot;); 
  ?>


      See the runkit to change constants...
Juggling with variables

     Compact() and extract()
 <?php 
  $x = 'a'; $y = 'b'; 
  $z = compact('x','y');   
 // $z = array('x'=> 'a', 'y' => 'b'); 

   $r = call_user_func_array('func', $z); 
 // calling func($x, $y); 

   extract($r); 
 // $x = 'c'; $y = 'd'; $t = 'e';
   list($x, $y, $t) = array_values($r);
 ?>
Variable functions

 <?php
  $func = 'foo'; $foo = 'bar';   $class = 'bb';

  $func($foo); // calling foo with bar
  call_user_func($func, $foo);// same as above

  call_user_func(array($class, $func), $foo); 
                        // now with objects!
  $class->$func($foo); // same as above
 ?>
Variable functions

 <?php
  $func = 'f';
  // a function
  // beware of langage construct such as empty()

  $func = array('c','m');
  // a static call to class c

  $func = array($o,'m');
  // a call to object o

  call_user_func($func, $foo);
 ?>
Object magic


  __autoload() : load classes JIT
  __sleep() and __wakeup()
    Store object and ressources in sessions
  __toString()   : to turn an object to a string
    __toArray() : get_object_vars($object);
    __toInteger() : may be?
Output buffering


   Avoid ‘already sent’ bug
   Clean it :   tidy
                              <?php
   Compress it : gz
                              ob_start(quot;ob_gzhandlerquot;);
   Cache it                   echo quot;Hellonquot;;
                              setcookie(quot;cquot;, quot;vquot;);
                              ob_end_flush();
                              ?>
Caching

    auto_prepend :
      if ( filemtime($cache)+3600 < time()) {
          include($cachefile);     exit;
      }
      ob_start();
    auto_append :
        $content = ob_get_contents(); 
        file_put_contents('cache', $contents);
        ob_end_flush();

    Auto-caching upon 404 error pages
Connexion handling



  PHP maintains the connexion status
     0 Normal; 1 Aborted; 2 Timeout

  ignore_user_abort() to make a script without interruption
  connexion_status() to check status
Register for shutdown


     Function executed at script shutdown
     Correct closing of resources
     More convenient than ignore_user_abort() a library
     In OOP, better use __destruct()
     Storing calculated variables
Variables export

      var_export() : recreate PHP code for a variable

  <?php
                                              array (
                                                0 => 5,
  $array = array(5,4,3,2);
                                                1 => 4,
                                                2 => 3,
  file_put_contents('file.inc.php',
                                                3 => 2,
     '<?php $x = '.
                                              )
    var_export($array, true).
   '; ?>'
  );
  ?>
Assertions


     Include tests during execution
     Assertion are an option (default is on) :
     Most clever way than removing than echo/var_dump
     Common practice in other languages
       Programmation by contract
Assertions

<?php
assert_options(ASSERT_CALLBACK,'assert_callback');
function assert_callback($script,$line, $message){
   echo 'There is something strange 
         in your script <b>', $script,'</b> : 
         line <b>', $line,'</b> :<br />'; exit;
  }

   assert('is_integer( $x );' );
  assert('($x >= 0) && ($x <= 10); 
           //* $x must be from 0 to 10' );
  echo quot;0 <= $x <= 10quot;;
?>
Debugging



  get_memory_usage()
    memory_limit is now on by default

    Better memory handling

    The fake growth of memory needs

  get_peak_memory_usage()
Debugging


  get_included_files()
  get_defined_constants/functions/vars()
  get_declared_classes()
  get_debug_backtrace()
    function stack and their arguments

    file and line calling
Debugging

   array(2) {
   [0]=>
   array(4) {
       [quot;filequot;] => string(10) quot;/tmp/a.phpquot;
       [quot;linequot;] => int(10)
       [quot;functionquot;] => string(6) quot;a_testquot;
       [quot;argsquot;]=>
         array(1) { [0] => &string(6) quot;friendquot; }
   }
   [1]=>
   array(4) {
       [quot;filequot;] => string(10) quot;/tmp/b.phpquot;
       [quot;linequot;] => int(2)
       [quot;argsquot;] =>
         array(1) { [0] => string(10) quot;/tmp/a.phpquot; }
       [quot;functionquot;] => string(12) quot;include_oncequot;
     }
   }
Slides

  http://www.nexen.net/english.php
  damien.seguy@nexen.net
  http://www.nexenservices.com/
Everyone
  loves
  PHP

More Related Content

What's hot

The Zen of Lithium
The Zen of LithiumThe Zen of Lithium
The Zen of LithiumNate Abele
 
Command Bus To Awesome Town
Command Bus To Awesome TownCommand Bus To Awesome Town
Command Bus To Awesome TownRoss Tuck
 
Models and Service Layers, Hemoglobin and Hobgoblins
Models and Service Layers, Hemoglobin and HobgoblinsModels and Service Layers, Hemoglobin and Hobgoblins
Models and Service Layers, Hemoglobin and HobgoblinsRoss Tuck
 
PHP 5.3 and Lithium: the most rad php framework
PHP 5.3 and Lithium: the most rad php frameworkPHP 5.3 and Lithium: the most rad php framework
PHP 5.3 and Lithium: the most rad php frameworkG Woo
 
Database Design Patterns
Database Design PatternsDatabase Design Patterns
Database Design PatternsHugo Hamon
 
The History of PHPersistence
The History of PHPersistenceThe History of PHPersistence
The History of PHPersistenceHugo Hamon
 
Doctrine 2
Doctrine 2Doctrine 2
Doctrine 2zfconfua
 
Silex meets SOAP & REST
Silex meets SOAP & RESTSilex meets SOAP & REST
Silex meets SOAP & RESTHugo Hamon
 
Dependency injection in PHP 5.3/5.4
Dependency injection in PHP 5.3/5.4Dependency injection in PHP 5.3/5.4
Dependency injection in PHP 5.3/5.4Fabien Potencier
 
Design Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et PimpleDesign Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et PimpleHugo Hamon
 
Things I Believe Now That I'm Old
Things I Believe Now That I'm OldThings I Believe Now That I'm Old
Things I Believe Now That I'm OldRoss Tuck
 
Doctrine MongoDB ODM (PDXPHP)
Doctrine MongoDB ODM (PDXPHP)Doctrine MongoDB ODM (PDXPHP)
Doctrine MongoDB ODM (PDXPHP)Kris Wallsmith
 
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011Masahiro Nagano
 
Lithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate FrameworksLithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate FrameworksNate Abele
 
Caching and Scaling WordPress using Fragment Caching
Caching and Scaling WordPress using Fragment CachingCaching and Scaling WordPress using Fragment Caching
Caching and Scaling WordPress using Fragment CachingErick Hitter
 
Dependency Injection with PHP and PHP 5.3
Dependency Injection with PHP and PHP 5.3Dependency Injection with PHP and PHP 5.3
Dependency Injection with PHP and PHP 5.3Fabien Potencier
 
The Origin of Lithium
The Origin of LithiumThe Origin of Lithium
The Origin of LithiumNate Abele
 
Building Lithium Apps
Building Lithium AppsBuilding Lithium Apps
Building Lithium AppsNate Abele
 

What's hot (19)

The Zen of Lithium
The Zen of LithiumThe Zen of Lithium
The Zen of Lithium
 
Command Bus To Awesome Town
Command Bus To Awesome TownCommand Bus To Awesome Town
Command Bus To Awesome Town
 
Models and Service Layers, Hemoglobin and Hobgoblins
Models and Service Layers, Hemoglobin and HobgoblinsModels and Service Layers, Hemoglobin and Hobgoblins
Models and Service Layers, Hemoglobin and Hobgoblins
 
PHP 5.3 and Lithium: the most rad php framework
PHP 5.3 and Lithium: the most rad php frameworkPHP 5.3 and Lithium: the most rad php framework
PHP 5.3 and Lithium: the most rad php framework
 
Database Design Patterns
Database Design PatternsDatabase Design Patterns
Database Design Patterns
 
The History of PHPersistence
The History of PHPersistenceThe History of PHPersistence
The History of PHPersistence
 
Doctrine 2
Doctrine 2Doctrine 2
Doctrine 2
 
Silex meets SOAP & REST
Silex meets SOAP & RESTSilex meets SOAP & REST
Silex meets SOAP & REST
 
Dependency injection in PHP 5.3/5.4
Dependency injection in PHP 5.3/5.4Dependency injection in PHP 5.3/5.4
Dependency injection in PHP 5.3/5.4
 
Design Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et PimpleDesign Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et Pimple
 
Things I Believe Now That I'm Old
Things I Believe Now That I'm OldThings I Believe Now That I'm Old
Things I Believe Now That I'm Old
 
Doctrine MongoDB ODM (PDXPHP)
Doctrine MongoDB ODM (PDXPHP)Doctrine MongoDB ODM (PDXPHP)
Doctrine MongoDB ODM (PDXPHP)
 
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
 
Lithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate FrameworksLithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate Frameworks
 
Caching and Scaling WordPress using Fragment Caching
Caching and Scaling WordPress using Fragment CachingCaching and Scaling WordPress using Fragment Caching
Caching and Scaling WordPress using Fragment Caching
 
Dependency Injection with PHP and PHP 5.3
Dependency Injection with PHP and PHP 5.3Dependency Injection with PHP and PHP 5.3
Dependency Injection with PHP and PHP 5.3
 
The Origin of Lithium
The Origin of LithiumThe Origin of Lithium
The Origin of Lithium
 
Intoduction to php arrays
Intoduction to php arraysIntoduction to php arrays
Intoduction to php arrays
 
Building Lithium Apps
Building Lithium AppsBuilding Lithium Apps
Building Lithium Apps
 

Viewers also liked

05 The Heart
05 The Heart05 The Heart
05 The Heartgriggans
 
Contra La Violencia
Contra La ViolenciaContra La Violencia
Contra La ViolenciaArabatik
 
Mattsslides
MattsslidesMattsslides
Mattsslidesmgallon
 
op de boerderij van boer Rene
op de boerderij van boer Reneop de boerderij van boer Rene
op de boerderij van boer Renewalter de maeyer
 
Php Reusing Code And Writing Functions
Php Reusing Code And Writing FunctionsPhp Reusing Code And Writing Functions
Php Reusing Code And Writing Functionsmussawir20
 
Class 3 - PHP Functions
Class 3 - PHP FunctionsClass 3 - PHP Functions
Class 3 - PHP FunctionsAhmed Swilam
 

Viewers also liked (10)

Sant Feliu On Line
Sant Feliu On LineSant Feliu On Line
Sant Feliu On Line
 
05 The Heart
05 The Heart05 The Heart
05 The Heart
 
Wet Geurhinder en Veehouderij
Wet Geurhinder en VeehouderijWet Geurhinder en Veehouderij
Wet Geurhinder en Veehouderij
 
Contra La Violencia
Contra La ViolenciaContra La Violencia
Contra La Violencia
 
Mattsslides
MattsslidesMattsslides
Mattsslides
 
op de boerderij van boer Rene
op de boerderij van boer Reneop de boerderij van boer Rene
op de boerderij van boer Rene
 
Functions in php
Functions in phpFunctions in php
Functions in php
 
Php Reusing Code And Writing Functions
Php Reusing Code And Writing FunctionsPhp Reusing Code And Writing Functions
Php Reusing Code And Writing Functions
 
PHP variables
PHP  variablesPHP  variables
PHP variables
 
Class 3 - PHP Functions
Class 3 - PHP FunctionsClass 3 - PHP Functions
Class 3 - PHP Functions
 

Similar to PHP tips and tricks for developers

Php tips-and-tricks4128
Php tips-and-tricks4128Php tips-and-tricks4128
Php tips-and-tricks4128PrinceGuru MS
 
PHP and MySQL Tips and tricks, DC 2007
PHP and MySQL Tips and tricks, DC 2007PHP and MySQL Tips and tricks, DC 2007
PHP and MySQL Tips and tricks, DC 2007Damien Seguy
 
Laravel collections an overview - Laravel SP
Laravel collections an overview - Laravel SPLaravel collections an overview - Laravel SP
Laravel collections an overview - Laravel SPMatheus Marabesi
 
An Elephant of a Different Colour: Hack
An Elephant of a Different Colour: HackAn Elephant of a Different Colour: Hack
An Elephant of a Different Colour: HackVic Metcalfe
 
PHP security audits
PHP security auditsPHP security audits
PHP security auditsDamien Seguy
 
Speed Things Up with Transients
Speed Things Up with TransientsSpeed Things Up with Transients
Speed Things Up with TransientsCliff Seal
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with ClojureDmitry Buzdin
 
Temporary Cache Assistance (Transients API): WordCamp Phoenix 2014
Temporary Cache Assistance (Transients API): WordCamp Phoenix 2014Temporary Cache Assistance (Transients API): WordCamp Phoenix 2014
Temporary Cache Assistance (Transients API): WordCamp Phoenix 2014Cliff Seal
 
From mysql to MongoDB(MongoDB2011北京交流会)
From mysql to MongoDB(MongoDB2011北京交流会)From mysql to MongoDB(MongoDB2011北京交流会)
From mysql to MongoDB(MongoDB2011北京交流会)Night Sailer
 
Crafting Custom Interfaces with Sub::Exporter
Crafting Custom Interfaces with Sub::ExporterCrafting Custom Interfaces with Sub::Exporter
Crafting Custom Interfaces with Sub::ExporterRicardo Signes
 
20 modules i haven't yet talked about
20 modules i haven't yet talked about20 modules i haven't yet talked about
20 modules i haven't yet talked aboutTatsuhiko Miyagawa
 
Hacking ansible
Hacking ansibleHacking ansible
Hacking ansiblebcoca
 
PHP Functions & Arrays
PHP Functions & ArraysPHP Functions & Arrays
PHP Functions & ArraysHenry Osborne
 
関西PHP勉強会 php5.4つまみぐい
関西PHP勉強会 php5.4つまみぐい関西PHP勉強会 php5.4つまみぐい
関西PHP勉強会 php5.4つまみぐいHisateru Tanaka
 
Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011
Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011
Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011camp_drupal_ua
 
Temporary Cache Assistance (Transients API): WordCamp Birmingham 2014
Temporary Cache Assistance (Transients API): WordCamp Birmingham 2014Temporary Cache Assistance (Transients API): WordCamp Birmingham 2014
Temporary Cache Assistance (Transients API): WordCamp Birmingham 2014Cliff Seal
 
Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)Kang-min Liu
 

Similar to PHP tips and tricks for developers (20)

Php tips-and-tricks4128
Php tips-and-tricks4128Php tips-and-tricks4128
Php tips-and-tricks4128
 
PHP and MySQL Tips and tricks, DC 2007
PHP and MySQL Tips and tricks, DC 2007PHP and MySQL Tips and tricks, DC 2007
PHP and MySQL Tips and tricks, DC 2007
 
Laravel collections an overview - Laravel SP
Laravel collections an overview - Laravel SPLaravel collections an overview - Laravel SP
Laravel collections an overview - Laravel SP
 
PHP and MySQL
PHP and MySQLPHP and MySQL
PHP and MySQL
 
An Elephant of a Different Colour: Hack
An Elephant of a Different Colour: HackAn Elephant of a Different Colour: Hack
An Elephant of a Different Colour: Hack
 
PHP security audits
PHP security auditsPHP security audits
PHP security audits
 
Speed Things Up with Transients
Speed Things Up with TransientsSpeed Things Up with Transients
Speed Things Up with Transients
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
 
Temporary Cache Assistance (Transients API): WordCamp Phoenix 2014
Temporary Cache Assistance (Transients API): WordCamp Phoenix 2014Temporary Cache Assistance (Transients API): WordCamp Phoenix 2014
Temporary Cache Assistance (Transients API): WordCamp Phoenix 2014
 
From mysql to MongoDB(MongoDB2011北京交流会)
From mysql to MongoDB(MongoDB2011北京交流会)From mysql to MongoDB(MongoDB2011北京交流会)
From mysql to MongoDB(MongoDB2011北京交流会)
 
PHPSpec BDD for PHP
PHPSpec BDD for PHPPHPSpec BDD for PHP
PHPSpec BDD for PHP
 
Crafting Custom Interfaces with Sub::Exporter
Crafting Custom Interfaces with Sub::ExporterCrafting Custom Interfaces with Sub::Exporter
Crafting Custom Interfaces with Sub::Exporter
 
20 modules i haven't yet talked about
20 modules i haven't yet talked about20 modules i haven't yet talked about
20 modules i haven't yet talked about
 
Hacking ansible
Hacking ansibleHacking ansible
Hacking ansible
 
PHP PPT FILE
PHP PPT FILEPHP PPT FILE
PHP PPT FILE
 
PHP Functions & Arrays
PHP Functions & ArraysPHP Functions & Arrays
PHP Functions & Arrays
 
関西PHP勉強会 php5.4つまみぐい
関西PHP勉強会 php5.4つまみぐい関西PHP勉強会 php5.4つまみぐい
関西PHP勉強会 php5.4つまみぐい
 
Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011
Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011
Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011
 
Temporary Cache Assistance (Transients API): WordCamp Birmingham 2014
Temporary Cache Assistance (Transients API): WordCamp Birmingham 2014Temporary Cache Assistance (Transients API): WordCamp Birmingham 2014
Temporary Cache Assistance (Transients API): WordCamp Birmingham 2014
 
Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)
 

More from Damien Seguy

Strong typing @ php leeds
Strong typing  @ php leedsStrong typing  @ php leeds
Strong typing @ php leedsDamien Seguy
 
Strong typing : adoption, adaptation and organisation
Strong typing : adoption, adaptation and organisationStrong typing : adoption, adaptation and organisation
Strong typing : adoption, adaptation and organisationDamien Seguy
 
Qui a laissé son mot de passe dans le code
Qui a laissé son mot de passe dans le codeQui a laissé son mot de passe dans le code
Qui a laissé son mot de passe dans le codeDamien Seguy
 
Analyse statique et applications
Analyse statique et applicationsAnalyse statique et applications
Analyse statique et applicationsDamien Seguy
 
Top 10 pieges php afup limoges
Top 10 pieges php   afup limogesTop 10 pieges php   afup limoges
Top 10 pieges php afup limogesDamien Seguy
 
Top 10 php classic traps DPC 2020
Top 10 php classic traps DPC 2020Top 10 php classic traps DPC 2020
Top 10 php classic traps DPC 2020Damien Seguy
 
Meilleur du typage fort (AFUP Day, 2020)
Meilleur du typage fort (AFUP Day, 2020)Meilleur du typage fort (AFUP Day, 2020)
Meilleur du typage fort (AFUP Day, 2020)Damien Seguy
 
Top 10 php classic traps confoo
Top 10 php classic traps confooTop 10 php classic traps confoo
Top 10 php classic traps confooDamien Seguy
 
Tout pour se préparer à PHP 7.4
Tout pour se préparer à PHP 7.4Tout pour se préparer à PHP 7.4
Tout pour se préparer à PHP 7.4Damien Seguy
 
Top 10 php classic traps php serbia
Top 10 php classic traps php serbiaTop 10 php classic traps php serbia
Top 10 php classic traps php serbiaDamien Seguy
 
Top 10 php classic traps
Top 10 php classic trapsTop 10 php classic traps
Top 10 php classic trapsDamien Seguy
 
Top 10 chausse trappes
Top 10 chausse trappesTop 10 chausse trappes
Top 10 chausse trappesDamien Seguy
 
Code review workshop
Code review workshopCode review workshop
Code review workshopDamien Seguy
 
Understanding static analysis php amsterdam 2018
Understanding static analysis   php amsterdam 2018Understanding static analysis   php amsterdam 2018
Understanding static analysis php amsterdam 2018Damien Seguy
 
Review unknown code with static analysis php ce 2018
Review unknown code with static analysis   php ce 2018Review unknown code with static analysis   php ce 2018
Review unknown code with static analysis php ce 2018Damien Seguy
 
Everything new with PHP 7.3
Everything new with PHP 7.3Everything new with PHP 7.3
Everything new with PHP 7.3Damien Seguy
 
Php 7.3 et ses RFC (AFUP Toulouse)
Php 7.3 et ses RFC  (AFUP Toulouse)Php 7.3 et ses RFC  (AFUP Toulouse)
Php 7.3 et ses RFC (AFUP Toulouse)Damien Seguy
 
Tout sur PHP 7.3 et ses RFC
Tout sur PHP 7.3 et ses RFCTout sur PHP 7.3 et ses RFC
Tout sur PHP 7.3 et ses RFCDamien Seguy
 
Review unknown code with static analysis php ipc 2018
Review unknown code with static analysis   php ipc 2018Review unknown code with static analysis   php ipc 2018
Review unknown code with static analysis php ipc 2018Damien Seguy
 
Code review for busy people
Code review for busy peopleCode review for busy people
Code review for busy peopleDamien Seguy
 

More from Damien Seguy (20)

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

Recently uploaded

Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
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
 
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
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
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
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
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
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESmohitsingh558521
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 

Recently uploaded (20)

Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
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
 
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
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
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
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
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
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 

PHP tips and tricks for developers

  • 1. PHP tips and tricks Skien, Norge, June 7th 2007
  • 2. Agenda Tips and Tricks from PHP No need for anything else than standard distribution All for PHP 5 ( but lots of it is also valid in PHP 4 ) The month of PHP functions
  • 3. Who is speaking? Damien Séguy Nexen Services, eZ publish silver partner for hosting PHP / MySQL services Redacteur en chef of www.nexen.net Phather of an plush Elephpant http://www.nexen.net/english.php
  • 4. Nod when you know about it
  • 5. Random stuff rand() and mt_rand() array_rand() : extract info from an array extract keys! shuffle() : shuffle an array before deal str_shuffle() : shuffle a string
  • 6. Random stuff Array <?php ( $a = range('a','d'); [0] => c shuffle($a); [1] => d [2] => b print_r($a); [3] => a ) print_r(array_rand($a,3)); Array ( print str_shuffle('abcdef'); [0] => 0 // eabdcf [1] => 1 ?> [2] => 3 )
  • 7. Arrays combinaisons array_combine() : turn two arrays into one Inverse to array_keys() and array_values() <?php $a = array('green', 'red', 'yellow'); $b = array('avocado', 'apple', 'banana'); $c = array_combine($a, $b); Array print_r($c); ( ?> [green] => avocado [red] => apple [yellow] => banana )
  • 8. Arrays combinaisons array_combine() : turn two arrays into one PDO::FETCH_KEY_PAIR : combine 2 columns in a hash <?php $html = file_get_contents(quot;http://www.php.net/quot;); //'<a href=quot;http://php.netquot;>PHP</a>'; if (preg_match_all( '#<a href=quot;(http://[^quot;/?]+/).*?>(.*?)</a>#s', $html, $r)) {     $liste = array_combine($r[2], $r[1]); } print_r($liste); ?>
  • 9. Arrays as SQL array_count_values() : makes easy stats Works like a GROUP BY and COUNT() <?php $array = array(1, quot;heiquot;, 1, quot;takkquot;, quot;heiquot;); print_r(array_count_values($array)); ?> Array ( sort r u [1] => 2 r u [hei] => 2 k k kr uk [takk] => 1 a a ar ua )
  • 10. Arrays as SQL Array ( array_multisort() : sort several [0] => 2 arrays at once [1] => 3 [2] => 4 Works like a ORDER BY [3] => 5 <?php ) $ar1 = array(5,4,3,2); Array $ar2 = array('a','b','c','d'); ( array_multisort($ar1, $ar2); [0] => d array_multisort($ar1, [1] => c SORT_ASC,SORT_STRING, [2] => b $ar2); [3] => a ?> )
  • 11. Fast dir scans scandir(‘/tmp’, true); Include name sorting Replace opendir, readdir, closedir and a loop! glob(‘*.html’); Simply move the loop out of sight
  • 12. Fast dir scans Array ( [0] => sess_um8rgjj10f6qvuck91rf36srj7 [1] => sess_u58rgul68305uqfe48ic467276 [2] => mysql.sock <?php [3] => .. print_r(scandir('/tmp/', 1)); [4] => . print_r(glob('/tmp/sess_*')); ) ?> Array ( [0] => /tmp/sess_um8rgjj10f6qvuck91rf36srj7 [1] => /tmp/sess_u58rgul68305uqfe48ic467276 )
  • 13. URL operations parse_url() break down into details do not make any check parse_str() split a query string separate and decode, as long as it can Fill up an array or globals
  • 14. URL <?php $url = 'http://login:pass@www.site.com/ path/file.php?a=2+&b%5B%5D= %E5%AF%B9%E4%BA%86%EF%BC%81#ee'; $d = parse_url($url); print_r($d); parse_str($d[quot;queryquot;]); var_dump($GLOBALS[quot;bquot;]); ?>
  • 15. URL ( [scheme] => http [host] => www.site.com [user] => login [pass] => pass [path] => /path/file.php [query] => a=2&b%5B%5D=%E5%AF%B9%E4%BA%86%EF%BC%81 [fragment] => ee ) array(1) { [0]=> string(9) quot; quot; }
  • 16. URL validations scheme : list your own host : checkdnsrr() to check path : realpath() + doc root (beware of mod_rewrite) query : parse_str() beware of the second argument! don’t handle &amp;
  • 17. URL rebuilding http_build_query() rebuild your query takes into account encoding and arrays <?php print http_build_query( array_merge($_GET , array(' de ' => ' '))); ?> +de+=%E5%AF%B9%E4%BA%86%EF%BC%81
  • 18. URL testing <?php get_headers('http://localhost/logo.png'); ?> Array ( [0] => HTTP/1.1 200 OK [1] => Date: Mon, 12 Feb 2007 02:24:23 GMT [2] => Server: Apache/1.3.33 (Darwin) PHP/5.2.1 [3] => X-Powered-By: eZ publish [4] => Last-Modified: Fri, 30 Sep 2005 09:11:28 GMT [5] => ETag: quot;f6f2a-dbb-433d0140quot; [6] => Accept-Ranges: bytes [7] => Content-Length: 3515 [8] => Connection: close [9] => Content-Type: image/png )
  • 19. PHP is dynamic Variables variables <?php $x = 'y'; $y = 'z'; $z = 'a'; echo $x;  // displays y echo $$x;  // displays z echo $$$x; // displays a ?>
  • 20. Variable constants Still one definition Dynamic constant value <?php   define (quot;CONSTANTquot;, 'eZ Conference');   echo CONSTANT;   echo constant(quot;CONSTANTquot;);  ?> See the runkit to change constants...
  • 21. Juggling with variables Compact() and extract() <?php   $x = 'a'; $y = 'b';   $z = compact('x','y');    // $z = array('x'=> 'a', 'y' => 'b');  $r = call_user_func_array('func', $z);  // calling func($x, $y);  extract($r);  // $x = 'c'; $y = 'd'; $t = 'e'; list($x, $y, $t) = array_values($r); ?>
  • 22. Variable functions <?php  $func = 'foo'; $foo = 'bar'; $class = 'bb';  $func($foo); // calling foo with bar call_user_func($func, $foo);// same as above  call_user_func(array($class, $func), $foo);  // now with objects! $class->$func($foo); // same as above ?>
  • 23. Variable functions <?php $func = 'f'; // a function // beware of langage construct such as empty() $func = array('c','m'); // a static call to class c $func = array($o,'m'); // a call to object o call_user_func($func, $foo); ?>
  • 24. Object magic __autoload() : load classes JIT __sleep() and __wakeup() Store object and ressources in sessions __toString() : to turn an object to a string __toArray() : get_object_vars($object); __toInteger() : may be?
  • 25. Output buffering Avoid ‘already sent’ bug Clean it : tidy <?php Compress it : gz ob_start(quot;ob_gzhandlerquot;); Cache it echo quot;Hellonquot;; setcookie(quot;cquot;, quot;vquot;); ob_end_flush(); ?>
  • 26. Caching auto_prepend : if ( filemtime($cache)+3600 < time()) {     include($cachefile);     exit; } ob_start(); auto_append :   $content = ob_get_contents();    file_put_contents('cache', $contents);   ob_end_flush(); Auto-caching upon 404 error pages
  • 27. Connexion handling PHP maintains the connexion status 0 Normal; 1 Aborted; 2 Timeout ignore_user_abort() to make a script without interruption connexion_status() to check status
  • 28. Register for shutdown Function executed at script shutdown Correct closing of resources More convenient than ignore_user_abort() a library In OOP, better use __destruct() Storing calculated variables
  • 29. Variables export var_export() : recreate PHP code for a variable <?php array ( 0 => 5, $array = array(5,4,3,2); 1 => 4, 2 => 3, file_put_contents('file.inc.php', 3 => 2, '<?php $x = '. ) var_export($array, true). '; ?>' ); ?>
  • 30. Assertions Include tests during execution Assertion are an option (default is on) : Most clever way than removing than echo/var_dump Common practice in other languages Programmation by contract
  • 31. Assertions <?php assert_options(ASSERT_CALLBACK,'assert_callback'); function assert_callback($script,$line, $message){    echo 'There is something strange  in your script <b>', $script,'</b> :  line <b>', $line,'</b> :<br />'; exit; } assert('is_integer( $x );' );   assert('($x >= 0) && ($x <= 10);  //* $x must be from 0 to 10' );   echo quot;0 <= $x <= 10quot;; ?>
  • 32. Debugging get_memory_usage() memory_limit is now on by default Better memory handling The fake growth of memory needs get_peak_memory_usage()
  • 33. Debugging get_included_files() get_defined_constants/functions/vars() get_declared_classes() get_debug_backtrace() function stack and their arguments file and line calling
  • 34. Debugging array(2) { [0]=> array(4) { [quot;filequot;] => string(10) quot;/tmp/a.phpquot; [quot;linequot;] => int(10) [quot;functionquot;] => string(6) quot;a_testquot; [quot;argsquot;]=> array(1) { [0] => &string(6) quot;friendquot; } } [1]=> array(4) { [quot;filequot;] => string(10) quot;/tmp/b.phpquot; [quot;linequot;] => int(2) [quot;argsquot;] => array(1) { [0] => string(10) quot;/tmp/a.phpquot; } [quot;functionquot;] => string(12) quot;include_oncequot; } }
  • 35. Slides http://www.nexen.net/english.php damien.seguy@nexen.net http://www.nexenservices.com/