SlideShare una empresa de Scribd logo
1 de 44
Descargar para leer sin conexión
Trucs et astuces
   PHP & MySQL
Toute cette puissance au bout des doigts
       Montréal, Québec, Canada
Agenda
 Trucs et astuces PHP et MySQL

 Issus des distributions

 Rien de spécial

 Encore valide en PHP 4 (mais passez en 5!)

 Le mois de la fonction PHP
Questions?
Qui parle?

  Damien Séguy

    PHP Québec, AFUP

    Expert PHP et MySQL :
    sécurité, audit

    Auteur des documentations
    rédacteur en chef

  http://www.nexen.net/
Au hasard
rand() et mt_rand()

array_rand() : extrait des lignes d'un tableau

 Extrait les clés!

shuffle() : mélange un jeu de cartes

str_shuffle : Mélange une chaîne
Au hasard
                               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
                               )
Tableaux SQL?

 Array_unique : DISTINCT

 array_count_values : GROUP BY

  Bien plus rapide que la précédente
Tableaux SQL?
 <?php
 $array = array("1", "MySQL", 1, "PHP", "PHP");
 $array = array_count_values($array);
 asort($array);
 print_r($array);
 ?>

 Array
                          sort     r      u
 (
     [1] => 2
     [PHP] => 2          ksort    kr     uk
     [MySQL] => 1
 )
                         asort    ar     ua
Tableaux SQL
                                      Array
                                      (
      array_multisort() : tri sur
                                          [0]   =>   2
      plusieurs tableaux en même
                                          [1]   =>   3
      temps
                                          [2]   =>   4
                                          [3]   =>   5
      Fonctionne comme ORDER BY       )
                                      Array
<?php                                 (
$ar1 = array(5,4,3,2);                    [0]   =>   d
$ar2 = array('a','b','c','d');            [1]   =>   c
array_multisort($ar1, $ar2);              [2]   =>   b
array_multisort($ar1, SORT_ASC, SORT_INT, [3]   =>   a
                $ar2);                )

?>
Étranges tris?

  Est ce que ça cloche?
 mysql> SELECT id, ordre FROM table
        ORDER BY ordre ASC;
 +----+------------+
 | id | ordre      |
 +----+------------+
 | 1 | premier     |
 | 2 | deuxième    |
 | 3 | troisième |
 | 4 | quatrième |
 +----+------------+
Étranges tris
 mysql> CREATE TABLE `test` (
        `id` tinyint unsigned,
        `ordre` enum(‘premier’,’deuxième’,
                  ’troisième’,’quatrième’),
 ) ENGINE=MYISAM;


  Enum est une chaîne et un nombre

  Utilisé en interne comme entier

  Affiché par défaut comme une chaîne
Variables MySQL
Disponibles depuis la pré-histoire

Gérée au niveau des connexions

 Détruites à la déconnexion

 Pas de concurrence

Stockage local de scalaires

Permet de se passer de PHP
Variables MySQL
<?php
$requete = "SELECT sum(nombre) FROM statsPHP";
$res = mysqli_query($mid, $requete);
$ligne = mysqli_fetch_row($res);
mysqli_free_result($res);

$requete = "UPDATE statsPHP 
            SET pourcentage = nombre / ".$ligne." * 100;";
mysqli_query($mid, $requete);
?>



mysql> SELECT @total := sum(nombre)
       FROM statsPHP ;
mysql> UPDATE statsPHP
       SET pourcentage =
             nombre / @total * 100;
Sécurité SQL
<?php
$requete = "SELECT droits FROM utilisateurs 
            WHERE login = '".
    mysqli_real_escape_string($mid, $_POST["login"])."'";
$res = mysqli_query($mid, $requete);
$droits = mysqli_fetch_row($res);
?>


<?php
$requete = "SET @login := 
        '".mysqli_real_escape_string($mid, $_POST["login"])."'";
$res = mysqli_query($mid, $requete);

$requete = "SELECT droits FROM utilisateurs WHERE login = @login";
$res = mysqli_query($mid, $requete);
$droits = mysqli_fetch_row($res);
?>
Classements
mysql> SET @rank := 0;
mysql> SELECT @rank := @rank + 1 AS rank,
       country, php FROM statsPHP ORDER BY php;
+------+---------------+-----+
| rank | country       | php |
+------+---------------+-----+
|     1| F. Polynesia | 67 |
|     2| Turk&Caicos   | 55 |
|     3| France        | 41 |
|     4| USA           | 31 |
|     5| Canada        | 31 |
|     7| Greenland     | 17 |
|     8| Israel        | 17 |
+------+---------------+-----+
8 rows in set (0.00 sec)
Ex-aequo
mysql> SET @num := 0, @rank := 0, @prev := NULL;
mysql> SELECT @num := @num + 1 AS row,
  @rank := if(@prev != php, @num, @rank) AS rank,
  country, @prev := php AS php
  FROM statsPHP ORDER BY php;
+------+------+---------------+-----+
| row | rank | country         | php |
+------+------+---------------+-----+
|     1|     1| Polynésie Fr. | 67 |
|     2|     2| Turk & Caicos | 55 |
|     3|     3| France         | 41 |
|     4|     4| USA            | 31 |
|     5|     4| Canada         | 31 |
|     6|     6| Groënland      | 17 |
|     7|     6| Israel         | 17 |
+------+------+---------------+-----+
Variables en masse
    Compact() et extract()
<?php
$requete = "SELECT *  FROM table 
            WHERE login = @login";
$res = mysqli_query($mid, $requete);
$resultat = mysqli_fetch_row($res);

extract($resultat);
// $colonne1 = 'valeur'; $colonne2 = 'valeur'

extract($_GET);          // ne l'utilisez pas
import_request_variables(); // non plus
?>
PHP est dynamique

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

    echo $x;  // affiche y
    echo $$x;  // affiche z
    echo $$$x; // affiche a
  ?>
constantes variables

    Une seule définition

    Accès dynamique à une valeur constante

<?php
  define ("CONSTANTE", 'PHP Québec');
  echo CONSTANTE;
  echo constant("CONSTANTE"); 
   print_r(get_defined_constants());
?>
Fonctions variables
<?php
 $fonc = 'foo'; $foo = 'bar'; $classe = 'bb';

 $fonc($foo);            // vaut foo('bar');
 call_user_func($fonc, $foo);// idem

 call_user_func(array($classe, $fonc), $foo); 
                        // $bb->fonc('bar');
                        // bb::fonc('bar');
 $classe->$fonc($foo);   // idem
?>
Variables en masse
    Compact() et extract()

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

$r = call_user_func_array('fonc', $z); 
// vaut fonc($x, $y) ou fonc('a', 'b');

extract($r); 
// $x = 'c'; $y = 'd'; $t = 'e';
list($x, $y, $t) = array_values($r);
?>
Toute cette dynamite..
 Métamoteur

   Gabarits

 Gestion de structures dynamiques

   SOAP

 Personnalisation de bibliothèques
Magie de l'objet

  __autoload() : Juste à temps
  <?php
  // php.ini auto_prepend
  function __autoload($classe) {
     include 'classes/' . $classe . '.php';
  }

  $objet  = new MaClasse();
  $objet2 = new MaClasse2();
  ?>
Magie de l'objet
           __toString() :

            transforme un objet en chaîne

            toArray(), __toInteger()?
<?php
class db {
  function __toString() {
   return "La connexion à ".$this->hote." est ".
          (is_null($this->mid ? 'active' : 'inactive' )."";
  }
}

$db = new db();
                   PHP Catchable fatal error: Object of class mysqli
echo $db;
                   could not be converted to string
?>
Magie de l'objet
      __sleep() et __wakeup()

          Stocke un objet en session

          Avant serialize()

class db {
// .....
 function __sleep() {
  unset($this->mid);
}
 function __wakeup() {
  $this->mid = new mysqli("host", "user", "secret", "base");
}
// .....
}
Buffer de sortie
 Intercepte le contenu

   Evite le bogue 'already sent'

   Nettoyez : tidy
                      <?php
                      ob_start("ob_gzhandler");
   Compressez : gz    echo "Hello
";
                      setcookie("c", "v");
   Cachez : ce sein que
                      ob_end_flush();
                      ?>
Caches simples

  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();
Connexions HTTP

 PHP Enregistre l'état de la connexion

   0 Normal; 1 Annulé; 2 expiré

 ignore_user_abort() évite les interruptions

 connexion_status() surveille l'état
Register_shutdown

  Semblable au __destruct()

  Fonction exécutée à l'extinction du script

  Fermeture des ressources

  Plus pratique que ignore_user_abort
  pour une bibliothèque
Variables
 var_export : Crée le code pour une variable

 Pratique pour les tableaux de configuration

      Optimise ces tableaux

 <?php
                                   array (
                                     0 => 5,
 $array = array(5,4,3,2);
                                     1 => 4,
                                     2 => 3,
 print var_export($array, true);
                                     3 => 2,
                                   )
 ?>
Assertions
 tests dans les scripts

 assertion sont gérées par directive

  Par défaut, activé

  Facile à supprimer echo/var_dump

Développement par contrat
Assertions

<?php 
  assert_options(ASSERT_CALLBACK,'assert_callback');
  function carre_naturel($x) {
   assert('is_integer( $x );' ); 
    assert('$x < 0');
   assert('$x > sqrt(PHP_INT_MAX)  
            //* $x doit être plus petit' ); 

   return $x * $x;
  }
?>
Assertions

<?php

   function assert_callback($script,$line, $message){
    echo 'Un problème est survenu dans le script
     <b>', $script,'</b>,
     à la ligne <b>', $line, '</b> : <br />'
     . $message;
     exit;
   }
?>
Déboguage
phpinfo()

get_defined_funcs()

 get_extension_funcs()

get_defined_classes()
                     <?php
                     Reflection::export(
 get_object_vars()      new ReflectionClass('Exception'));
                     ?>
                     Class [ <internal> class Exception ] {
 get_class_var()        - Constants [0] {}
                        - Static properties [0] { }
                        - Static methods [0] {
                        }
Débogage

get_defined_vars()

get_included_files()

__FILE__, __LINE__

__FUNCTION__, __CLASS__, __METHOD__
Débogage             array(2) {
                     [0]=>
                     array(4) {
                         ["file"] => string(10) "/tmp/a.php"
                         ["line"] => int(10)
                         ["function"] => string(6) "a_test"
                         ["args"]=>
                         array(1) {
debug_backtrace()          [0] => &string(6) "friend"
                         }
                     }
Affiche la pile PHP   [1]=>
                     array(4) {
                         ["file"] => string(10) "/tmp/b.php"
Inclus les               ["line"] => int(2)
                         ["args"] =>
arguments utilisés       array(1) {
                           [0] => string(10) "/tmp/a.php"
                         }
                         ["function"] => string(12)
                     "include_once"
                       }
                     }
Listes rapides

 scandir(‘/tmp’, true);

   Permet le tri sur les noms

   Remplace opendir(), readdir(), closedir() et
   une boucle!

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


parse_url() : Détaille une URL

parse_string() : Découpe les paramètres

http_build_query() : Reconstruit une URL
URL
                                Array
                                (
                                     [scheme] => htp
<?php
                                     [host] => www.site.com
$url =
                                     [user] => login
'htp://login:pass@www.site.com/
                                     [pass] => pass
      path/file.php?a=2 &b[]=3#ee';
                                     [path] => /path/file.php
$d = parse_url($url);
                                     [query] => a=2 &b[]=3
print_r($d);
                                     [fragment] => ee
parse_str($d["query"]);         )
var_dump($GLOBALS["b"]);
                                array(1) {
                                   [0]=>
print http_build_query(
       array_merge($_GET ,         string(1) "3"
      array(' de ' => '     ')));
                                }
?>
                                +de+=%E5%AF%B9%E4%BA%86%EF%
                                BC%81
URL
<?php
   get_headers('http://localhost/logo.png', false);
?>
     Array
     (
         [0] => HTTP/1.1 200 OK
         [Date] => Fri, 09 Mar 2007 21:09:52 GMT
         [Server] => Apache/1.3.33 (Darwin) PHP/5.2.1
         [X-Powered-By] => PHP/5.2.1
         [En_plus] => non
         [Set-Cookie] => Array
             (
                 [0] => a=a
                 [1] => a=b
             )

        [Connection] => close
        [Content-Type] => text/html
    )
Cette conférence


  http://www.nexen.net/conferences.php
Tableaux

   array_combine :
   combine deux tableaux en un seul
<?php
$a = array('vert', 'rouge', 'jaune');
$b = array('avocat', 'pomme', 'banane');
$c = array_combine($a, $b);
               Array
print_r($c);   (
?>                 [vert] => avocat
                   [rouge] => pomme
                   [jaune] => banane
               )

Más contenido relacionado

La actualidad más candente

Mabangis na kamay ... Maamong Kamay
Mabangis na kamay ... Maamong KamayMabangis na kamay ... Maamong Kamay
Mabangis na kamay ... Maamong KamayHanna Elise
 
FINAL-COPY-MODYUL-2-PANITIKAN-NG-KANLURAN-new.docx
FINAL-COPY-MODYUL-2-PANITIKAN-NG-KANLURAN-new.docxFINAL-COPY-MODYUL-2-PANITIKAN-NG-KANLURAN-new.docx
FINAL-COPY-MODYUL-2-PANITIKAN-NG-KANLURAN-new.docxAprilNonay4
 
Noli me tangere kabanata 26
Noli me tangere kabanata 26Noli me tangere kabanata 26
Noli me tangere kabanata 26Sir Pogs
 
Ang Puno't Dulo ng Kulturang Popular
Ang Puno't Dulo ng Kulturang PopularAng Puno't Dulo ng Kulturang Popular
Ang Puno't Dulo ng Kulturang Popularmreiafrica
 
Mga Kwentong Bayan at Tula - Grade 7
Mga Kwentong Bayan at Tula - Grade 7Mga Kwentong Bayan at Tula - Grade 7
Mga Kwentong Bayan at Tula - Grade 7Rich Elle
 
Liberalisasyon at Nasyonalisasyon
Liberalisasyon at NasyonalisasyonLiberalisasyon at Nasyonalisasyon
Liberalisasyon at NasyonalisasyonGesa Tuzon
 
Kalakalang Panloob at Panlabas
Kalakalang Panloob at Panlabas Kalakalang Panloob at Panlabas
Kalakalang Panloob at Panlabas Mygie Janamike
 
Kaligirang kasaysayan ng noli me tangere
Kaligirang kasaysayan ng noli me tangereKaligirang kasaysayan ng noli me tangere
Kaligirang kasaysayan ng noli me tangerefidelbasbas
 
EL_FILIBUSTERISMO.pptx
EL_FILIBUSTERISMO.pptxEL_FILIBUSTERISMO.pptx
EL_FILIBUSTERISMO.pptxJovyTuting1
 
Makapaghihintay Ang Amerika
Makapaghihintay Ang AmerikaMakapaghihintay Ang Amerika
Makapaghihintay Ang AmerikaMerland Mabait
 
Intrinsik at Ekstrinsik: Pagganyak sa Mag-aaral Tungo sa Pagbuo ng Planong Ga...
Intrinsik at Ekstrinsik: Pagganyak sa Mag-aaral Tungo sa Pagbuo ng Planong Ga...Intrinsik at Ekstrinsik: Pagganyak sa Mag-aaral Tungo sa Pagbuo ng Planong Ga...
Intrinsik at Ekstrinsik: Pagganyak sa Mag-aaral Tungo sa Pagbuo ng Planong Ga...karenclarissalat
 
Kabanata 34 Ang kasal ni Paulita ng El Fili
Kabanata 34 Ang kasal ni Paulita ng El FiliKabanata 34 Ang kasal ni Paulita ng El Fili
Kabanata 34 Ang kasal ni Paulita ng El Filijuliusmirador1
 
Filipino Teachers Guide_1
Filipino Teachers Guide_1Filipino Teachers Guide_1
Filipino Teachers Guide_1Mher Walked
 
Mga halimbawa ng parabula
Mga halimbawa ng parabulaMga halimbawa ng parabula
Mga halimbawa ng parabulaLani Requizo
 
Ang Pagkaunlad ng Nobelang Tagalog
Ang Pagkaunlad ng Nobelang TagalogAng Pagkaunlad ng Nobelang Tagalog
Ang Pagkaunlad ng Nobelang Tagalognica casareno
 
Sa Aking Mga Magulang
Sa Aking Mga MagulangSa Aking Mga Magulang
Sa Aking Mga MagulangCris Gamit
 
Filipino isang suring pelikula
Filipino isang suring  pelikulaFilipino isang suring  pelikula
Filipino isang suring pelikulaEemlliuq Agalalan
 
Mga hakbang sa Pagsasalin
Mga hakbang sa PagsasalinMga hakbang sa Pagsasalin
Mga hakbang sa PagsasalinBeLenDa3
 

La actualidad más candente (20)

Mabangis na kamay ... Maamong Kamay
Mabangis na kamay ... Maamong KamayMabangis na kamay ... Maamong Kamay
Mabangis na kamay ... Maamong Kamay
 
FINAL-COPY-MODYUL-2-PANITIKAN-NG-KANLURAN-new.docx
FINAL-COPY-MODYUL-2-PANITIKAN-NG-KANLURAN-new.docxFINAL-COPY-MODYUL-2-PANITIKAN-NG-KANLURAN-new.docx
FINAL-COPY-MODYUL-2-PANITIKAN-NG-KANLURAN-new.docx
 
Noli me tangere kabanata 26
Noli me tangere kabanata 26Noli me tangere kabanata 26
Noli me tangere kabanata 26
 
Ang Puno't Dulo ng Kulturang Popular
Ang Puno't Dulo ng Kulturang PopularAng Puno't Dulo ng Kulturang Popular
Ang Puno't Dulo ng Kulturang Popular
 
Mga Kwentong Bayan at Tula - Grade 7
Mga Kwentong Bayan at Tula - Grade 7Mga Kwentong Bayan at Tula - Grade 7
Mga Kwentong Bayan at Tula - Grade 7
 
Liberalisasyon at Nasyonalisasyon
Liberalisasyon at NasyonalisasyonLiberalisasyon at Nasyonalisasyon
Liberalisasyon at Nasyonalisasyon
 
Talambuhay ni Jose Rizal
Talambuhay ni Jose RizalTalambuhay ni Jose Rizal
Talambuhay ni Jose Rizal
 
Dulang pilipino
Dulang pilipinoDulang pilipino
Dulang pilipino
 
Kalakalang Panloob at Panlabas
Kalakalang Panloob at Panlabas Kalakalang Panloob at Panlabas
Kalakalang Panloob at Panlabas
 
Kaligirang kasaysayan ng noli me tangere
Kaligirang kasaysayan ng noli me tangereKaligirang kasaysayan ng noli me tangere
Kaligirang kasaysayan ng noli me tangere
 
EL_FILIBUSTERISMO.pptx
EL_FILIBUSTERISMO.pptxEL_FILIBUSTERISMO.pptx
EL_FILIBUSTERISMO.pptx
 
Makapaghihintay Ang Amerika
Makapaghihintay Ang AmerikaMakapaghihintay Ang Amerika
Makapaghihintay Ang Amerika
 
Intrinsik at Ekstrinsik: Pagganyak sa Mag-aaral Tungo sa Pagbuo ng Planong Ga...
Intrinsik at Ekstrinsik: Pagganyak sa Mag-aaral Tungo sa Pagbuo ng Planong Ga...Intrinsik at Ekstrinsik: Pagganyak sa Mag-aaral Tungo sa Pagbuo ng Planong Ga...
Intrinsik at Ekstrinsik: Pagganyak sa Mag-aaral Tungo sa Pagbuo ng Planong Ga...
 
Kabanata 34 Ang kasal ni Paulita ng El Fili
Kabanata 34 Ang kasal ni Paulita ng El FiliKabanata 34 Ang kasal ni Paulita ng El Fili
Kabanata 34 Ang kasal ni Paulita ng El Fili
 
Filipino Teachers Guide_1
Filipino Teachers Guide_1Filipino Teachers Guide_1
Filipino Teachers Guide_1
 
Mga halimbawa ng parabula
Mga halimbawa ng parabulaMga halimbawa ng parabula
Mga halimbawa ng parabula
 
Ang Pagkaunlad ng Nobelang Tagalog
Ang Pagkaunlad ng Nobelang TagalogAng Pagkaunlad ng Nobelang Tagalog
Ang Pagkaunlad ng Nobelang Tagalog
 
Sa Aking Mga Magulang
Sa Aking Mga MagulangSa Aking Mga Magulang
Sa Aking Mga Magulang
 
Filipino isang suring pelikula
Filipino isang suring  pelikulaFilipino isang suring  pelikula
Filipino isang suring pelikula
 
Mga hakbang sa Pagsasalin
Mga hakbang sa PagsasalinMga hakbang sa Pagsasalin
Mga hakbang sa Pagsasalin
 

Destacado

Mini projet individuel php
Mini projet individuel phpMini projet individuel php
Mini projet individuel phpKhadim Mbacké
 
PHP (Partie II) Par Mahdi Ben Alaya
PHP (Partie II) Par Mahdi Ben AlayaPHP (Partie II) Par Mahdi Ben Alaya
PHP (Partie II) Par Mahdi Ben AlayaMahdi Ben Alaya
 
Cours php & Mysql - 3éme partie
Cours php & Mysql - 3éme partieCours php & Mysql - 3éme partie
Cours php & Mysql - 3éme partiekadzaki
 
Cours php & Mysql - 2éme partie
Cours php & Mysql - 2éme partieCours php & Mysql - 2éme partie
Cours php & Mysql - 2éme partiekadzaki
 
Examen principal- php - correction
Examen principal- php - correctionExamen principal- php - correction
Examen principal- php - correctionInes Ouaz
 
Javascript in a continuous integration environment
Javascript in a continuous integration environmentJavascript in a continuous integration environment
Javascript in a continuous integration environmentFrederic Dewinne
 
Bases de PHP - Partie 1
Bases de PHP - Partie 1Bases de PHP - Partie 1
Bases de PHP - Partie 1Régis Lutter
 
CReVote: un système de vote électronique résistant à la coercition basé sur l...
CReVote: un système de vote électronique résistant à la coercition basé sur l...CReVote: un système de vote électronique résistant à la coercition basé sur l...
CReVote: un système de vote électronique résistant à la coercition basé sur l...pacomeambassa
 
LESS, Le CSS avancé
LESS, Le CSS avancéLESS, Le CSS avancé
LESS, Le CSS avancéMahmoud Nbet
 
Examen principal - PHP
Examen principal - PHPExamen principal - PHP
Examen principal - PHPInes Ouaz
 
PHP (Partie I) Par Mahdi Ben Alaya
PHP (Partie I) Par Mahdi Ben AlayaPHP (Partie I) Par Mahdi Ben Alaya
PHP (Partie I) Par Mahdi Ben AlayaMahdi Ben Alaya
 
Examen Principal - Fondement Multimedia Janvier 2015
Examen Principal - Fondement Multimedia Janvier 2015Examen Principal - Fondement Multimedia Janvier 2015
Examen Principal - Fondement Multimedia Janvier 2015Ines Ouaz
 
Examen principal - Algorithme & Structures de données
Examen principal - Algorithme & Structures de donnéesExamen principal - Algorithme & Structures de données
Examen principal - Algorithme & Structures de donnéesInes Ouaz
 
Overview of c++ language
Overview of c++ language   Overview of c++ language
Overview of c++ language samt7
 
Cours php & Mysql - 4éme partie
Cours php & Mysql - 4éme partieCours php & Mysql - 4éme partie
Cours php & Mysql - 4éme partiekadzaki
 
JavaScript pour le développeur Java
JavaScript pour le développeur JavaJavaScript pour le développeur Java
JavaScript pour le développeur Javajollivetc
 
Examen principal - Fondement Multimedia - correction
Examen principal - Fondement Multimedia - correctionExamen principal - Fondement Multimedia - correction
Examen principal - Fondement Multimedia - correctionInes Ouaz
 
Cours php & Mysql - 5éme partie
Cours php & Mysql - 5éme partieCours php & Mysql - 5éme partie
Cours php & Mysql - 5éme partiekadzaki
 
Conception et Réalisation d’un Système de Vote Electronique (Blondel Seumo)
Conception et Réalisation d’un Système de Vote Electronique (Blondel Seumo)Conception et Réalisation d’un Système de Vote Electronique (Blondel Seumo)
Conception et Réalisation d’un Système de Vote Electronique (Blondel Seumo)Gantner Technologies
 

Destacado (20)

Mini projet individuel php
Mini projet individuel phpMini projet individuel php
Mini projet individuel php
 
PHP (Partie II) Par Mahdi Ben Alaya
PHP (Partie II) Par Mahdi Ben AlayaPHP (Partie II) Par Mahdi Ben Alaya
PHP (Partie II) Par Mahdi Ben Alaya
 
Cours php & Mysql - 3éme partie
Cours php & Mysql - 3éme partieCours php & Mysql - 3éme partie
Cours php & Mysql - 3éme partie
 
Cours php & Mysql - 2éme partie
Cours php & Mysql - 2éme partieCours php & Mysql - 2éme partie
Cours php & Mysql - 2éme partie
 
Examen principal- php - correction
Examen principal- php - correctionExamen principal- php - correction
Examen principal- php - correction
 
Javascript in a continuous integration environment
Javascript in a continuous integration environmentJavascript in a continuous integration environment
Javascript in a continuous integration environment
 
Bases de PHP - Partie 1
Bases de PHP - Partie 1Bases de PHP - Partie 1
Bases de PHP - Partie 1
 
CReVote: un système de vote électronique résistant à la coercition basé sur l...
CReVote: un système de vote électronique résistant à la coercition basé sur l...CReVote: un système de vote électronique résistant à la coercition basé sur l...
CReVote: un système de vote électronique résistant à la coercition basé sur l...
 
LESS, Le CSS avancé
LESS, Le CSS avancéLESS, Le CSS avancé
LESS, Le CSS avancé
 
Examen principal - PHP
Examen principal - PHPExamen principal - PHP
Examen principal - PHP
 
PHP (Partie I) Par Mahdi Ben Alaya
PHP (Partie I) Par Mahdi Ben AlayaPHP (Partie I) Par Mahdi Ben Alaya
PHP (Partie I) Par Mahdi Ben Alaya
 
Examen Principal - Fondement Multimedia Janvier 2015
Examen Principal - Fondement Multimedia Janvier 2015Examen Principal - Fondement Multimedia Janvier 2015
Examen Principal - Fondement Multimedia Janvier 2015
 
Examen principal - Algorithme & Structures de données
Examen principal - Algorithme & Structures de donnéesExamen principal - Algorithme & Structures de données
Examen principal - Algorithme & Structures de données
 
Overview of c++ language
Overview of c++ language   Overview of c++ language
Overview of c++ language
 
Cours php & Mysql - 4éme partie
Cours php & Mysql - 4éme partieCours php & Mysql - 4éme partie
Cours php & Mysql - 4éme partie
 
JavaScript pour le développeur Java
JavaScript pour le développeur JavaJavaScript pour le développeur Java
JavaScript pour le développeur Java
 
Examen principal - Fondement Multimedia - correction
Examen principal - Fondement Multimedia - correctionExamen principal - Fondement Multimedia - correction
Examen principal - Fondement Multimedia - correction
 
Php & My Sql
Php & My SqlPhp & My Sql
Php & My Sql
 
Cours php & Mysql - 5éme partie
Cours php & Mysql - 5éme partieCours php & Mysql - 5éme partie
Cours php & Mysql - 5éme partie
 
Conception et Réalisation d’un Système de Vote Electronique (Blondel Seumo)
Conception et Réalisation d’un Système de Vote Electronique (Blondel Seumo)Conception et Réalisation d’un Système de Vote Electronique (Blondel Seumo)
Conception et Réalisation d’un Système de Vote Electronique (Blondel Seumo)
 

Similar a Trucs et astuces PHP et MySQL

Similar a Trucs et astuces PHP et MySQL (20)

La référence Clear php
La référence Clear phpLa référence Clear php
La référence Clear php
 
Les principes de base de PHP
 Les principes de base de PHP  Les principes de base de PHP
Les principes de base de PHP
 
Php cours
Php coursPhp cours
Php cours
 
Audits php
Audits phpAudits php
Audits php
 
Analyse statique et applications
Analyse statique et applicationsAnalyse statique et applications
Analyse statique et applications
 
Solution Linux 2009 - JavaScript
Solution Linux 2009 - JavaScriptSolution Linux 2009 - JavaScript
Solution Linux 2009 - JavaScript
 
PHP &amp; MySQL
PHP &amp; MySQLPHP &amp; MySQL
PHP &amp; MySQL
 
Exploiter php 5
Exploiter php 5Exploiter php 5
Exploiter php 5
 
Php1
Php1Php1
Php1
 
Php 2 - Approfondissement MySQL, PDO et MVC
Php 2 - Approfondissement MySQL, PDO et MVCPhp 2 - Approfondissement MySQL, PDO et MVC
Php 2 - Approfondissement MySQL, PDO et MVC
 
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)
 
Sécurité MySQL
Sécurité MySQLSécurité MySQL
Sécurité MySQL
 
La sécurite pour les developpeurs - OWF
La sécurite pour les developpeurs - OWFLa sécurite pour les developpeurs - OWF
La sécurite pour les developpeurs - OWF
 
Les structures de données PHP5
Les structures de données PHP5Les structures de données PHP5
Les structures de données PHP5
 
test doc
test doctest doc
test doc
 
Programmation orientée objet en PHP 5
Programmation orientée objet en PHP 5Programmation orientée objet en PHP 5
Programmation orientée objet en PHP 5
 
Introduction à Ruby
Introduction à RubyIntroduction à Ruby
Introduction à Ruby
 
Meet-Up SQLI Lyon 09-2015 - Varnish
Meet-Up SQLI Lyon 09-2015 - VarnishMeet-Up SQLI Lyon 09-2015 - Varnish
Meet-Up SQLI Lyon 09-2015 - Varnish
 
Ruby STAR
Ruby STARRuby STAR
Ruby STAR
 
PHP.pptx
PHP.pptxPHP.pptx
PHP.pptx
 

Más de 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
 
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
 
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
 
Static analysis saved my code tonight
Static analysis saved my code tonightStatic analysis saved my code tonight
Static analysis saved my code tonightDamien Seguy
 
Machine learning in php las vegas
Machine learning in php   las vegasMachine learning in php   las vegas
Machine learning in php las vegasDamien Seguy
 

Más de 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
 
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
 
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
 
Static analysis saved my code tonight
Static analysis saved my code tonightStatic analysis saved my code tonight
Static analysis saved my code tonight
 
Machine learning in php las vegas
Machine learning in php   las vegasMachine learning in php   las vegas
Machine learning in php las vegas
 

Trucs et astuces PHP et MySQL

  • 1. Trucs et astuces PHP & MySQL Toute cette puissance au bout des doigts Montréal, Québec, Canada
  • 2. Agenda Trucs et astuces PHP et MySQL Issus des distributions Rien de spécial Encore valide en PHP 4 (mais passez en 5!) Le mois de la fonction PHP
  • 4. Qui parle? Damien Séguy PHP Québec, AFUP Expert PHP et MySQL : sécurité, audit Auteur des documentations rédacteur en chef http://www.nexen.net/
  • 5. Au hasard rand() et mt_rand() array_rand() : extrait des lignes d'un tableau Extrait les clés! shuffle() : mélange un jeu de cartes str_shuffle : Mélange une chaîne
  • 6. Au hasard 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. Tableaux SQL? Array_unique : DISTINCT array_count_values : GROUP BY Bien plus rapide que la précédente
  • 8. Tableaux SQL? <?php $array = array("1", "MySQL", 1, "PHP", "PHP"); $array = array_count_values($array); asort($array); print_r($array); ?> Array sort r u ( [1] => 2 [PHP] => 2 ksort kr uk [MySQL] => 1 ) asort ar ua
  • 9. Tableaux SQL Array ( array_multisort() : tri sur [0] => 2 plusieurs tableaux en même [1] => 3 temps [2] => 4 [3] => 5 Fonctionne comme ORDER BY ) Array <?php ( $ar1 = array(5,4,3,2); [0] => d $ar2 = array('a','b','c','d'); [1] => c array_multisort($ar1, $ar2); [2] => b array_multisort($ar1, SORT_ASC, SORT_INT, [3] => a $ar2); ) ?>
  • 10. Étranges tris? Est ce que ça cloche? mysql> SELECT id, ordre FROM table ORDER BY ordre ASC; +----+------------+ | id | ordre | +----+------------+ | 1 | premier | | 2 | deuxième | | 3 | troisième | | 4 | quatrième | +----+------------+
  • 11. Étranges tris mysql> CREATE TABLE `test` ( `id` tinyint unsigned, `ordre` enum(‘premier’,’deuxième’, ’troisième’,’quatrième’), ) ENGINE=MYISAM; Enum est une chaîne et un nombre Utilisé en interne comme entier Affiché par défaut comme une chaîne
  • 12. Variables MySQL Disponibles depuis la pré-histoire Gérée au niveau des connexions Détruites à la déconnexion Pas de concurrence Stockage local de scalaires Permet de se passer de PHP
  • 13. Variables MySQL <?php $requete = "SELECT sum(nombre) FROM statsPHP"; $res = mysqli_query($mid, $requete); $ligne = mysqli_fetch_row($res); mysqli_free_result($res); $requete = "UPDATE statsPHP  SET pourcentage = nombre / ".$ligne." * 100;"; mysqli_query($mid, $requete); ?> mysql> SELECT @total := sum(nombre) FROM statsPHP ; mysql> UPDATE statsPHP SET pourcentage = nombre / @total * 100;
  • 14. Sécurité SQL <?php $requete = "SELECT droits FROM utilisateurs  WHERE login = '". mysqli_real_escape_string($mid, $_POST["login"])."'"; $res = mysqli_query($mid, $requete); $droits = mysqli_fetch_row($res); ?> <?php $requete = "SET @login :=  '".mysqli_real_escape_string($mid, $_POST["login"])."'"; $res = mysqli_query($mid, $requete); $requete = "SELECT droits FROM utilisateurs WHERE login = @login"; $res = mysqli_query($mid, $requete); $droits = mysqli_fetch_row($res); ?>
  • 15. Classements mysql> SET @rank := 0; mysql> SELECT @rank := @rank + 1 AS rank, country, php FROM statsPHP ORDER BY php; +------+---------------+-----+ | rank | country | php | +------+---------------+-----+ | 1| F. Polynesia | 67 | | 2| Turk&Caicos | 55 | | 3| France | 41 | | 4| USA | 31 | | 5| Canada | 31 | | 7| Greenland | 17 | | 8| Israel | 17 | +------+---------------+-----+ 8 rows in set (0.00 sec)
  • 16. Ex-aequo mysql> SET @num := 0, @rank := 0, @prev := NULL; mysql> SELECT @num := @num + 1 AS row, @rank := if(@prev != php, @num, @rank) AS rank, country, @prev := php AS php FROM statsPHP ORDER BY php; +------+------+---------------+-----+ | row | rank | country | php | +------+------+---------------+-----+ | 1| 1| Polynésie Fr. | 67 | | 2| 2| Turk & Caicos | 55 | | 3| 3| France | 41 | | 4| 4| USA | 31 | | 5| 4| Canada | 31 | | 6| 6| Groënland | 17 | | 7| 6| Israel | 17 | +------+------+---------------+-----+
  • 17. Variables en masse Compact() et extract() <?php $requete = "SELECT *  FROM table  WHERE login = @login"; $res = mysqli_query($mid, $requete); $resultat = mysqli_fetch_row($res); extract($resultat); // $colonne1 = 'valeur'; $colonne2 = 'valeur' extract($_GET); // ne l'utilisez pas import_request_variables(); // non plus ?>
  • 18. PHP est dynamique Variables variables <?php $x = 'y'; $y = 'z'; $z = 'a'; echo $x;  // affiche y echo $$x;  // affiche z echo $$$x; // affiche a ?>
  • 19. constantes variables Une seule définition Accès dynamique à une valeur constante <?php   define ("CONSTANTE", 'PHP Québec');   echo CONSTANTE;   echo constant("CONSTANTE");  print_r(get_defined_constants()); ?>
  • 20. Fonctions variables <?php  $fonc = 'foo'; $foo = 'bar'; $classe = 'bb';  $fonc($foo);  // vaut foo('bar'); call_user_func($fonc, $foo);// idem  call_user_func(array($classe, $fonc), $foo);  // $bb->fonc('bar'); // bb::fonc('bar'); $classe->$fonc($foo); // idem ?>
  • 21. Variables en masse Compact() et extract() <?php   $x = 'a'; $y = 'b';   $z = compact('x','y');    // $z = array('x'=> 'a', 'y' => 'b');  $r = call_user_func_array('fonc', $z);  // vaut fonc($x, $y) ou fonc('a', 'b'); extract($r);  // $x = 'c'; $y = 'd'; $t = 'e'; list($x, $y, $t) = array_values($r); ?>
  • 22. Toute cette dynamite.. Métamoteur Gabarits Gestion de structures dynamiques SOAP Personnalisation de bibliothèques
  • 23. Magie de l'objet __autoload() : Juste à temps <?php // php.ini auto_prepend function __autoload($classe) {    include 'classes/' . $classe . '.php'; } $objet  = new MaClasse(); $objet2 = new MaClasse2(); ?>
  • 24. Magie de l'objet __toString() : transforme un objet en chaîne toArray(), __toInteger()? <?php class db {   function __toString() {    return "La connexion à ".$this->hote." est ". (is_null($this->mid ? 'active' : 'inactive' ).""; } } $db = new db(); PHP Catchable fatal error: Object of class mysqli echo $db; could not be converted to string ?>
  • 25. Magie de l'objet __sleep() et __wakeup() Stocke un objet en session Avant serialize() class db { // .....  function __sleep() {   unset($this->mid); }  function __wakeup() {   $this->mid = new mysqli("host", "user", "secret", "base"); } // ..... }
  • 26. Buffer de sortie Intercepte le contenu Evite le bogue 'already sent' Nettoyez : tidy <?php ob_start("ob_gzhandler"); Compressez : gz echo "Hello "; setcookie("c", "v"); Cachez : ce sein que ob_end_flush(); ?>
  • 27. Caches simples 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();
  • 28. Connexions HTTP PHP Enregistre l'état de la connexion 0 Normal; 1 Annulé; 2 expiré ignore_user_abort() évite les interruptions connexion_status() surveille l'état
  • 29. Register_shutdown Semblable au __destruct() Fonction exécutée à l'extinction du script Fermeture des ressources Plus pratique que ignore_user_abort pour une bibliothèque
  • 30. Variables var_export : Crée le code pour une variable Pratique pour les tableaux de configuration Optimise ces tableaux <?php array ( 0 => 5, $array = array(5,4,3,2); 1 => 4, 2 => 3, print var_export($array, true); 3 => 2, ) ?>
  • 31. Assertions tests dans les scripts assertion sont gérées par directive Par défaut, activé Facile à supprimer echo/var_dump Développement par contrat
  • 32. Assertions <?php  assert_options(ASSERT_CALLBACK,'assert_callback'); function carre_naturel($x) {    assert('is_integer( $x );' );    assert('$x < 0');    assert('$x > sqrt(PHP_INT_MAX)   //* $x doit être plus petit' );   return $x * $x; } ?>
  • 33. Assertions <?php function assert_callback($script,$line, $message){     echo 'Un problème est survenu dans le script   <b>', $script,'</b>, à la ligne <b>', $line, '</b> : <br />' . $message; exit; } ?>
  • 34. Déboguage phpinfo() get_defined_funcs() get_extension_funcs() get_defined_classes() <?php Reflection::export( get_object_vars() new ReflectionClass('Exception')); ?> Class [ <internal> class Exception ] { get_class_var() - Constants [0] {} - Static properties [0] { } - Static methods [0] { }
  • 36. Débogage array(2) { [0]=> array(4) { ["file"] => string(10) "/tmp/a.php" ["line"] => int(10) ["function"] => string(6) "a_test" ["args"]=> array(1) { debug_backtrace() [0] => &string(6) "friend" } } Affiche la pile PHP [1]=> array(4) { ["file"] => string(10) "/tmp/b.php" Inclus les ["line"] => int(2) ["args"] => arguments utilisés array(1) { [0] => string(10) "/tmp/a.php" } ["function"] => string(12) "include_once" } }
  • 37. Listes rapides scandir(‘/tmp’, true); Permet le tri sur les noms Remplace opendir(), readdir(), closedir() et une boucle! Glob(‘*.html’);
  • 38. Listes rapides Array ( [0] => sess_um8rgjj10f6qvuck91rf36srj7 [1] => sess_u58rgul68305uqfe48ic467276 [2] => mysql.sock [3] => .. <?php [4] => . print_r(scandir('/tmp/', 1)); ) print_r(glob('/tmp/sess_*')); Array ?> ( [0] => /tmp/sess_um8rgjj10f6qvuck91rf36srj7 [1] => /tmp/sess_u58rgul68305uqfe48ic467276 )
  • 39. URL parse_url() : Détaille une URL parse_string() : Découpe les paramètres http_build_query() : Reconstruit une URL
  • 40. URL Array ( [scheme] => htp <?php [host] => www.site.com $url = [user] => login 'htp://login:pass@www.site.com/ [pass] => pass path/file.php?a=2 &b[]=3#ee'; [path] => /path/file.php $d = parse_url($url); [query] => a=2 &b[]=3 print_r($d); [fragment] => ee parse_str($d["query"]); ) var_dump($GLOBALS["b"]); array(1) { [0]=> print http_build_query( array_merge($_GET , string(1) "3" array(' de ' => ' '))); } ?> +de+=%E5%AF%B9%E4%BA%86%EF% BC%81
  • 41. URL <?php get_headers('http://localhost/logo.png', false); ?> Array ( [0] => HTTP/1.1 200 OK [Date] => Fri, 09 Mar 2007 21:09:52 GMT [Server] => Apache/1.3.33 (Darwin) PHP/5.2.1 [X-Powered-By] => PHP/5.2.1 [En_plus] => non [Set-Cookie] => Array ( [0] => a=a [1] => a=b ) [Connection] => close [Content-Type] => text/html )
  • 42. Cette conférence http://www.nexen.net/conferences.php
  • 43.
  • 44. Tableaux array_combine : combine deux tableaux en un seul <?php $a = array('vert', 'rouge', 'jaune'); $b = array('avocat', 'pomme', 'banane'); $c = array_combine($a, $b); Array print_r($c); ( ?> [vert] => avocat [rouge] => pomme [jaune] => banane )