SlideShare a Scribd company logo
1 of 39
Download to read offline
PHP/MySQL tips and tricks
  Washington DC, USA, November 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 )

     No petting the elePHPant until the end of the session
Who is speaking?

    Damien Séguy
       Nexen Services, Open Source hosting company
       PHP / MySQL expert services
       Redacteur en chef of www.nexen.net
       PHather of thousands plush Elephpants
    http://www.nexen.net/english.php
Nod when you know about it
PHP 5 : PHP 4 on diet?



PHP 4 : 77 extensions bundled   PHP 5 : 67 extensions bundled
PHP 4 : 2459 functions          PHP 5 : 2144 functions
PHP 4 : 3 classes               PHP 5 : 158 classes....
                                (watch for DateTime)
Random stuff

                               Array
<?php                          (
$a = range('d','a');               [0]   =>   c
shuffle($a);                       [1]   =>   d
                                   [2]   =>   b
print_r($a);                       [3]   =>   a
                               )
print str_shuffle('abcdef');   Array
// eabdcf                      (
                                   [0]   => 0
print_r(array_rand($a,3));         [1]   => 1
?>                                 [2]   => 3
                               )
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
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
                     )
array_combine() applied


<?php
$a = range('e','a');

$shuffled_a = array_combine(
    array_rand($a,5), 
    array_values($a));
// eabdcf

shuffle($a);
?>
Arrays as SQL


     sort       r    u


                r    u


      k     k   kr   uk

                ar
      a     a        ua
Slicing array in chunks : PHP
                                    Array
                                    (
                                        [0] => Array
                                            (
                                                [0] => 1
                                                [1] => 2
                                            )
<?php                                   [1] => Array
  $array = range(1,5);                      (
  print_r(array_chunk($array,2));               [0] => 3
                                                [1] => 4
?>                                          )

                                        [2] => Array
                                            (
                                                [0] => 5
                                            )

                                    )
Slicing array in chunks : SQL

mysql> SET @a := 1;
 
mysql> SELECT @a, GROUP_CONCAT(i) FROM integers
        GROUP BY ROUND((@a := @a + 1) / 4 , 0);
                                                +------+
+------+-----------------+                      |i     |
                                                +------+
| @a    | group_concat(i) |                     |    0|
                                                |    1|
+------+-----------------+                      |    2|
|     2 | 0,1,2,13        |                     |   13 |
                                                |    4|
|     6 | 4,15,6,7        |                     |   15 |
                                                |    6|
|    12 | 11,8,9          |                     |    7|
                                                |    8|
+------+-----------------+                      |    9|
3 rows in set (0.00 sec)                        |   11 |
                                                  +------+
JOIN is faster than LIMIT




mysql> SELECT cols FROM TABLE LIMIT 1000, 10;
JOIN is faster than LIMIT

mysql> CREATE TABLE `table_limit` (
  `row` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `id` int(11) unsigned DEFAULT NULL,
  UNIQUE KEY `id` (`id`) );

mysql> INSERT INTO table_limit
  SELECT 0, id FROM table ORDER BY col;

mysql> SELECT col FROM table_limit JOIN table
    ON bl_content.id = bl_content_nav.id AND
     table_limit.row
          BETWEEN @offset AND @offset + 10
JOIN is faster than LIMIT
Arrays sorted as SQL cols

                                        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
?>                                      )
GROUP BY PHP!


      DISTINCT : array_unique()
      COUNT(*) and GROUP BY : array_count_values()
<?php
   $array = array(1, quot;heiquot;, quot;1quot;, quot;takkquot;, quot;heiquot;);
   print_r(array_count_values($array));
                                                Array
?>
                                                (
                                                      [1] => 2
      Hint : array_count_values() is always faster that
                                                      [hei] => 2
      array_unique()...                               [takk] => 1
                                                )
Hide those loops to me!


<?php
 while(list($key, $val) = each($array)) {
 print quot;$key => $valnquot;;
}

for($i = 0; $i<count($array); $i++) {
 print quot;$i => {$array[$i]}nquot;;
}
?>
Hide those loops to me!



<?php
$array = range(1,3);
foreach($array as $id => &$value) {
   $value++;               Array
}                          (
                               [0] =>         2
?>
                                       [1] => 3
                                       [2] => 4
                                   )

   Declare your objects as Iterators
Hidden loops




  array_map : apply a function to all elements
  array_walk_recursive : same as above, and multi-dimensional
  array_filter : extract all elements using a custom function
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


<?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 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

    Fills up an array or $GLOBALS
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() : PHP 5 only
          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
    ?>
PHP is crazy

    Crazy variables


    <?php
      $    = 'works';
      $êtrânçé = 'works';
      ${'Utter madness?'} = 'works';
      ${''} = 'works';
    ?>
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).
   '; ?>'
  );
  ?>
Fast file exports



   file_put_contents($file_name, $content);
     accept contexts and streams

     Complementary to file_get_contents()

   fputcsv() : create CSV style files
     complementary to fgetcsv()
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

  get_peak_memory_usage()
  sys_getloadavg() : no more need for exec(’uptime’);
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

Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...
Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...
Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...Matt Harrison
 
Groovy collection api
Groovy collection apiGroovy collection api
Groovy collection apitrygvea
 
Coding Horrors
Coding HorrorsCoding Horrors
Coding HorrorsMark Baker
 
SPL: The Undiscovered Library - DataStructures
SPL: The Undiscovered Library -  DataStructuresSPL: The Undiscovered Library -  DataStructures
SPL: The Undiscovered Library - DataStructuresMark Baker
 
How to Become a Tree Hugger: Random Forests and Predictive Modeling for Devel...
How to Become a Tree Hugger: Random Forests and Predictive Modeling for Devel...How to Become a Tree Hugger: Random Forests and Predictive Modeling for Devel...
How to Become a Tree Hugger: Random Forests and Predictive Modeling for Devel...Matt Harrison
 
New SPL Features in PHP 5.3
New SPL Features in PHP 5.3New SPL Features in PHP 5.3
New SPL Features in PHP 5.3Matthew Turland
 
Swift에서 꼬리재귀 사용기 (Tail Recursion)
Swift에서 꼬리재귀 사용기 (Tail Recursion)Swift에서 꼬리재귀 사용기 (Tail Recursion)
Swift에서 꼬리재귀 사용기 (Tail Recursion)진성 오
 
Pre-Bootcamp introduction to Elixir
Pre-Bootcamp introduction to ElixirPre-Bootcamp introduction to Elixir
Pre-Bootcamp introduction to ElixirPaweł Dawczak
 
Ruby Language - A quick tour
Ruby Language - A quick tourRuby Language - A quick tour
Ruby Language - A quick touraztack
 
Hacking JavaFX with Groovy, Clojure, Scala, and Visage
Hacking JavaFX with Groovy, Clojure, Scala, and VisageHacking JavaFX with Groovy, Clojure, Scala, and Visage
Hacking JavaFX with Groovy, Clojure, Scala, and VisageStephen Chin
 
Php reference sheet
Php reference sheetPhp reference sheet
Php reference sheetSilvia Rios
 
JavaFX and Scala - Like Milk and Cookies
JavaFX and Scala - Like Milk and CookiesJavaFX and Scala - Like Milk and Cookies
JavaFX and Scala - Like Milk and CookiesStephen Chin
 
RxSwift 시작하기
RxSwift 시작하기RxSwift 시작하기
RxSwift 시작하기Suyeol Jeon
 
Swift - 혼자 공부하면 분명히 안할테니까 같이 공부하기
Swift - 혼자 공부하면 분명히 안할테니까 같이 공부하기Swift - 혼자 공부하면 분명히 안할테니까 같이 공부하기
Swift - 혼자 공부하면 분명히 안할테니까 같이 공부하기Suyeol Jeon
 
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
 
Functional Pe(a)rls - the Purely Functional Datastructures edition
Functional Pe(a)rls - the Purely Functional Datastructures editionFunctional Pe(a)rls - the Purely Functional Datastructures edition
Functional Pe(a)rls - the Purely Functional Datastructures editionosfameron
 
Introdução ao Perl 6
Introdução ao Perl 6Introdução ao Perl 6
Introdução ao Perl 6garux
 

What's hot (20)

Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...
Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...
Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...
 
Groovy collection api
Groovy collection apiGroovy collection api
Groovy collection api
 
Coding Horrors
Coding HorrorsCoding Horrors
Coding Horrors
 
SPL: The Undiscovered Library - DataStructures
SPL: The Undiscovered Library -  DataStructuresSPL: The Undiscovered Library -  DataStructures
SPL: The Undiscovered Library - DataStructures
 
Chap 3php array part1
Chap 3php array part1Chap 3php array part1
Chap 3php array part1
 
Fp java8
Fp java8Fp java8
Fp java8
 
How to Become a Tree Hugger: Random Forests and Predictive Modeling for Devel...
How to Become a Tree Hugger: Random Forests and Predictive Modeling for Devel...How to Become a Tree Hugger: Random Forests and Predictive Modeling for Devel...
How to Become a Tree Hugger: Random Forests and Predictive Modeling for Devel...
 
New SPL Features in PHP 5.3
New SPL Features in PHP 5.3New SPL Features in PHP 5.3
New SPL Features in PHP 5.3
 
Drupal7 dbtng
Drupal7  dbtngDrupal7  dbtng
Drupal7 dbtng
 
Swift에서 꼬리재귀 사용기 (Tail Recursion)
Swift에서 꼬리재귀 사용기 (Tail Recursion)Swift에서 꼬리재귀 사용기 (Tail Recursion)
Swift에서 꼬리재귀 사용기 (Tail Recursion)
 
Pre-Bootcamp introduction to Elixir
Pre-Bootcamp introduction to ElixirPre-Bootcamp introduction to Elixir
Pre-Bootcamp introduction to Elixir
 
Ruby Language - A quick tour
Ruby Language - A quick tourRuby Language - A quick tour
Ruby Language - A quick tour
 
Hacking JavaFX with Groovy, Clojure, Scala, and Visage
Hacking JavaFX with Groovy, Clojure, Scala, and VisageHacking JavaFX with Groovy, Clojure, Scala, and Visage
Hacking JavaFX with Groovy, Clojure, Scala, and Visage
 
Php reference sheet
Php reference sheetPhp reference sheet
Php reference sheet
 
JavaFX and Scala - Like Milk and Cookies
JavaFX and Scala - Like Milk and CookiesJavaFX and Scala - Like Milk and Cookies
JavaFX and Scala - Like Milk and Cookies
 
RxSwift 시작하기
RxSwift 시작하기RxSwift 시작하기
RxSwift 시작하기
 
Swift - 혼자 공부하면 분명히 안할테니까 같이 공부하기
Swift - 혼자 공부하면 분명히 안할테니까 같이 공부하기Swift - 혼자 공부하면 분명히 안할테니까 같이 공부하기
Swift - 혼자 공부하면 분명히 안할테니까 같이 공부하기
 
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
 
Functional Pe(a)rls - the Purely Functional Datastructures edition
Functional Pe(a)rls - the Purely Functional Datastructures editionFunctional Pe(a)rls - the Purely Functional Datastructures edition
Functional Pe(a)rls - the Purely Functional Datastructures edition
 
Introdução ao Perl 6
Introdução ao Perl 6Introdução ao Perl 6
Introdução ao Perl 6
 

Similar to PHP and MySQL Tips and tricks, DC 2007

Php tips-and-tricks4128
Php tips-and-tricks4128Php tips-and-tricks4128
Php tips-and-tricks4128PrinceGuru MS
 
PHP tips and tricks
PHP tips and tricks PHP tips and tricks
PHP tips and tricks Damien 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
 
Useful javascript
Useful javascriptUseful javascript
Useful javascriptLei Kang
 
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
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with ClojureDmitry Buzdin
 
PHP security audits
PHP security auditsPHP security audits
PHP security auditsDamien Seguy
 
High performance GPU computing with Ruby RubyConf 2017
High performance GPU computing with Ruby  RubyConf 2017High performance GPU computing with Ruby  RubyConf 2017
High performance GPU computing with Ruby RubyConf 2017Prasun Anand
 
Class 4 - PHP Arrays
Class 4 - PHP ArraysClass 4 - PHP Arrays
Class 4 - PHP ArraysAhmed Swilam
 
第49回Php勉強会@関東 Datasource
第49回Php勉強会@関東 Datasource第49回Php勉強会@関東 Datasource
第49回Php勉強会@関東 DatasourceKaz Watanabe
 
Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...
Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...
Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...Dhivyaa C.R
 
Personal Perl 6 compiler
Personal Perl 6 compilerPersonal Perl 6 compiler
Personal Perl 6 compilerAndrew Shitov
 
Evolving with Java - How to remain Relevant and Effective
Evolving with Java - How to remain Relevant and EffectiveEvolving with Java - How to remain Relevant and Effective
Evolving with Java - How to remain Relevant and EffectiveNaresha K
 
Difference between mysql_fetch_array and mysql_fetch_assoc in PHP
Difference between mysql_fetch_array and mysql_fetch_assoc in PHPDifference between mysql_fetch_array and mysql_fetch_assoc in PHP
Difference between mysql_fetch_array and mysql_fetch_assoc in PHPVineet Kumar Saini
 
High Performance GPU computing with Ruby, Rubykaigi 2018
High Performance GPU computing with Ruby, Rubykaigi 2018High Performance GPU computing with Ruby, Rubykaigi 2018
High Performance GPU computing with Ruby, Rubykaigi 2018Prasun Anand
 
Zend Framework Study@Tokyo #2
Zend Framework Study@Tokyo #2Zend Framework Study@Tokyo #2
Zend Framework Study@Tokyo #2Shinya Ohyanagi
 

Similar to PHP and MySQL Tips and tricks, DC 2007 (20)

Php tips-and-tricks4128
Php tips-and-tricks4128Php tips-and-tricks4128
Php tips-and-tricks4128
 
PHP tips and tricks
PHP tips and tricks PHP tips and tricks
PHP tips and tricks
 
Laravel collections an overview - Laravel SP
Laravel collections an overview - Laravel SPLaravel collections an overview - Laravel SP
Laravel collections an overview - Laravel SP
 
Useful javascript
Useful javascriptUseful javascript
Useful javascript
 
Chapter 2 wbp.pptx
Chapter 2 wbp.pptxChapter 2 wbp.pptx
Chapter 2 wbp.pptx
 
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
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
 
PHP security audits
PHP security auditsPHP security audits
PHP security audits
 
High performance GPU computing with Ruby RubyConf 2017
High performance GPU computing with Ruby  RubyConf 2017High performance GPU computing with Ruby  RubyConf 2017
High performance GPU computing with Ruby RubyConf 2017
 
R programming
R programmingR programming
R programming
 
Class 4 - PHP Arrays
Class 4 - PHP ArraysClass 4 - PHP Arrays
Class 4 - PHP Arrays
 
第49回Php勉強会@関東 Datasource
第49回Php勉強会@関東 Datasource第49回Php勉強会@関東 Datasource
第49回Php勉強会@関東 Datasource
 
Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...
Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...
Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...
 
UNIT IV (4).pptx
UNIT IV (4).pptxUNIT IV (4).pptx
UNIT IV (4).pptx
 
Personal Perl 6 compiler
Personal Perl 6 compilerPersonal Perl 6 compiler
Personal Perl 6 compiler
 
Php array
Php arrayPhp array
Php array
 
Evolving with Java - How to remain Relevant and Effective
Evolving with Java - How to remain Relevant and EffectiveEvolving with Java - How to remain Relevant and Effective
Evolving with Java - How to remain Relevant and Effective
 
Difference between mysql_fetch_array and mysql_fetch_assoc in PHP
Difference between mysql_fetch_array and mysql_fetch_assoc in PHPDifference between mysql_fetch_array and mysql_fetch_assoc in PHP
Difference between mysql_fetch_array and mysql_fetch_assoc in PHP
 
High Performance GPU computing with Ruby, Rubykaigi 2018
High Performance GPU computing with Ruby, Rubykaigi 2018High Performance GPU computing with Ruby, Rubykaigi 2018
High Performance GPU computing with Ruby, Rubykaigi 2018
 
Zend Framework Study@Tokyo #2
Zend Framework Study@Tokyo #2Zend Framework Study@Tokyo #2
Zend Framework Study@Tokyo #2
 

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

AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Angeliki Cooney
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontologyjohnbeverley2021
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Bhuvaneswari Subramani
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 

Recently uploaded (20)

AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 

PHP and MySQL Tips and tricks, DC 2007

  • 1. PHP/MySQL tips and tricks Washington DC, USA, November 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 ) No petting the elePHPant until the end of the session
  • 3. Who is speaking? Damien Séguy Nexen Services, Open Source hosting company PHP / MySQL expert services Redacteur en chef of www.nexen.net PHather of thousands plush Elephpants http://www.nexen.net/english.php
  • 4. Nod when you know about it
  • 5. PHP 5 : PHP 4 on diet? PHP 4 : 77 extensions bundled PHP 5 : 67 extensions bundled PHP 4 : 2459 functions PHP 5 : 2144 functions PHP 4 : 3 classes PHP 5 : 158 classes.... (watch for DateTime)
  • 6. Random stuff Array <?php ( $a = range('d','a'); [0] => c shuffle($a); [1] => d [2] => b print_r($a); [3] => a ) print str_shuffle('abcdef'); Array // eabdcf ( [0] => 0 print_r(array_rand($a,3)); [1] => 1 ?> [2] => 3 )
  • 7. 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
  • 8. 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 )
  • 9. array_combine() applied <?php $a = range('e','a'); $shuffled_a = array_combine( array_rand($a,5),  array_values($a)); // eabdcf shuffle($a); ?>
  • 10. Arrays as SQL sort r u r u k k kr uk ar a a ua
  • 11. Slicing array in chunks : PHP Array ( [0] => Array ( [0] => 1 [1] => 2 ) <?php [1] => Array   $array = range(1,5); (   print_r(array_chunk($array,2)); [0] => 3 [1] => 4 ?> ) [2] => Array ( [0] => 5 ) )
  • 12. Slicing array in chunks : SQL mysql> SET @a := 1;   mysql> SELECT @a, GROUP_CONCAT(i) FROM integers GROUP BY ROUND((@a := @a + 1) / 4 , 0);   +------+ +------+-----------------+ |i | +------+ | @a | group_concat(i) | | 0| | 1| +------+-----------------+ | 2| | 2 | 0,1,2,13 | | 13 | | 4| | 6 | 4,15,6,7 | | 15 | | 6| | 12 | 11,8,9 | | 7| | 8| +------+-----------------+ | 9| 3 rows in set (0.00 sec) | 11 | +------+
  • 13. JOIN is faster than LIMIT mysql> SELECT cols FROM TABLE LIMIT 1000, 10;
  • 14. JOIN is faster than LIMIT mysql> CREATE TABLE `table_limit` ( `row` int(10) unsigned NOT NULL AUTO_INCREMENT, `id` int(11) unsigned DEFAULT NULL, UNIQUE KEY `id` (`id`) ); mysql> INSERT INTO table_limit SELECT 0, id FROM table ORDER BY col; mysql> SELECT col FROM table_limit JOIN table ON bl_content.id = bl_content_nav.id AND table_limit.row BETWEEN @offset AND @offset + 10
  • 15. JOIN is faster than LIMIT
  • 16. Arrays sorted as SQL cols 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 ?> )
  • 17. GROUP BY PHP! DISTINCT : array_unique() COUNT(*) and GROUP BY : array_count_values() <?php $array = array(1, quot;heiquot;, quot;1quot;, quot;takkquot;, quot;heiquot;); print_r(array_count_values($array)); Array ?> ( [1] => 2 Hint : array_count_values() is always faster that [hei] => 2 array_unique()... [takk] => 1 )
  • 18. Hide those loops to me! <?php  while(list($key, $val) = each($array)) {  print quot;$key => $valnquot;; } for($i = 0; $i<count($array); $i++) {  print quot;$i => {$array[$i]}nquot;; } ?>
  • 19. Hide those loops to me! <?php $array = range(1,3); foreach($array as $id => &$value) {    $value++; Array } ( [0] => 2 ?> [1] => 3 [2] => 4 ) Declare your objects as Iterators
  • 20. Hidden loops array_map : apply a function to all elements array_walk_recursive : same as above, and multi-dimensional array_filter : extract all elements using a custom function
  • 21. 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
  • 22. 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 )
  • 23. 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;]); ?>
  • 24. 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 Fills up an array or $GLOBALS
  • 25. 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; }
  • 26. 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;
  • 27. URL rebuilding http_build_query() : PHP 5 only 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
  • 28. 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 )
  • 29. PHP is dynamic Variables variables <?php $x = 'y'; $y = 'z'; $z = 'a'; echo $x;  // displays y echo $$x;  // displays z echo $$$x; // displays a ?>
  • 30. PHP is crazy Crazy variables <?php $  = 'works'; $êtrânçé = 'works'; ${'Utter madness?'} = 'works'; ${''} = 'works'; ?>
  • 31. 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). '; ?>' ); ?>
  • 32. Fast file exports file_put_contents($file_name, $content); accept contexts and streams Complementary to file_get_contents() fputcsv() : create CSV style files complementary to fgetcsv()
  • 33. 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
  • 34. 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;; ?>
  • 35. Debugging get_memory_usage() memory_limit is now on by default Better memory handling get_peak_memory_usage() sys_getloadavg() : no more need for exec(’uptime’);
  • 36. Debugging get_included_files() get_defined_constants/functions/vars() get_declared_classes() get_debug_backtrace() function stack and their arguments file and line calling
  • 37. 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; } }
  • 38. Slides http://www.nexen.net/english.php damien.seguy@nexen.net http://www.nexenservices.com/