Listing 3.2 : Combinaison de code PHP et HTML
1: <html>
2: <head>
3: <title>Listing 3.2 : combinaison de code PHP et HTML</title>
4: </head>
5: <body>
6: <b>
7: <?php
8: print "Bonjour monde";
9: ?>
</b>
</body>
</html>
Listing 4.1 : Définir et accéder dynamiquement aux variables
1: <html>
2: <head>
3: <title>Listing 4.1 : définir et accéder dynamiquement
aux variables</title>
4: </head>
5: <body>
6: <?php
7: $holder = "user";
8: $$holder = "bob";
9:
// aurait pu être :
// $user = "bob";
// ${"user"} = "bob";
print "$user<br>"; // affiche "bob"
print $$holder; // affiche "bob"
print "<br>";
print "${$holder}<br>"; // affiche "bob"
print "${'user'}<br>"; // affiche "bob"
?>
</body>
</html>
Listing 4.2 : Les variables sont affectées par valeurs
1: <html>
2: <head>
3: <title>Listing 4.2 : les variables sont affectées par valeur
</title>
4: </head>
5: <body>
6: <?php
7: $aVariable = 42;
8: $anotherVariable = $aVariable;
9: // une copie du contenu de $aVariable est placée dans $anotherVariable
$aVariable = 325;
print $anotherVariable; // affiche 42
?>
</body>
</html>
Listing 4.3 : Affecter une variable par référence
1: <html>
2: <head>
3: <title>Listing 4.3 : affecter une variable par référence
</title>
4: </head>
5: <body>
6: <?php
7: $aVariable = 42;
8: $anotherVariable = &$aVariable;
9: // une copie du contenu de $aVariable est placée dans $anotherVariable
$aVariable= 325;
print $anotherVariable; // affiche 325
?>
</body>
</html>
Listing 4.4 : Tester le type d'une variable
1: <html>
2: <head>
3: <title>Listing 4.3 : tester le type d'une variable</title>
4: </head>
5: <body>
6: <?php
7: $testing = 5;
8: print gettype( $testing ); // entier
9: print "<br>";
$testing = "five";
print gettype( $testing ); // chaîne
print("<br>");
$testing = 5.0;
print gettype( $testing ); // double
print("<br>");
$testing = true;
print gettype( $testing ); // booléen
print "<br>";
?>
</body>
</html>
Listing 4.5 : Changer le type d'une variable à l'aide de settype()
1: <html>
2: <head>
3: <title>Listing 4.5 : changer le type d'une variable à l'aide
de settype()</title>
4: </head>
5: <body>
6: <?php
7: $undecided = 3.14;
8: print gettype( $undecided ); // double
9: print " [dbhy] $undecided<br>"; // 3.14
settype( $undecided, string );
print gettype( $undecided ); // chaîne
print " [dbhy] $undecided<br>"; // 3.14
settype( $undecided, integer );
print gettype( $undecided ); // entier
print " [dbhy] $undecided<br>"; // 3
settype( $undecided, double );
print gettype( $undecided ); // double
print " [dbhy] $undecided<br>"; // 3.0
settype( $undecided, boolean );
print gettype( $undecided ); // booléen
print " [dbhy] $undecided<br>"; // 1
?>
</body>
</html>
Listing 4.6 : Convertir une variable
1: <html>
2: <head>
3: <title>Listing 4.6: convertir une variable</title>
4: </head>
5: <body>
6: <?php
7: $undecided = 3.14;
8: $holder = ( double ) $undecided;
9: print gettype( $holder ) ; // double
print " [dbhy] $holder<br>"; // 3.14
$holder = ( string ) $undecided;
print gettype( $holder ); // chaîne
print " [dbhy] $holder<br>"; // 3.14
$holder = ( integer ) $undecided;
print gettype( $holder ); // entier
print " [dbhy] $holder<br>"; // 3
$holder = ( double ) $undecided;
print gettype( $holder ); // double
print " [dbhy] $holder<br>"; // 3.14
$holder = ( boolean ) $undecided;
print gettype( $holder ); // booléen
print " [dbhy] $holder<br>"; // 1
?>
</body>
</html>
Listing 4.7 : Définir une constante
1: <html>
2: <head>
3: <title>Listing 4.7: définir une constante</title>
4: </head>
5: <body>
6: <?php
7: define ( "USER", "Gerald" );
8: print "Bienvenue ".USER;
9: ?>
</body>
</html>
Listing 5.1 : Une instruction if
1: <html>
2: <head>
3: <title>Listing 5.1</title>
4: </head>
5: <body>
6: <?php
7: $mood = "heureux";
8: if ( $mood == "heureux" )
9: {
print "Hourra, je suis de bonne humeur";
}
?>
</body>
</html>
Listing 5.2 : Une instruction if qui utilise else
1: <html>
2: <head>
3: <title>Listing 5.2</title>
4: </head>
5: <body>
6: <?php
7: $mood = "triste";
8: if ( $mood == "heureux" )
9: {
print "Hourra, je suis de bonne humeur";
}
else
{
print "Pas heureux, mais $mood";
}
?>
</body>
</html>
Listing 5.3 : Une instruction if qui utilise else et elseif
1: <html>
2: <head>
3: <title>Listing 5.3</title>
4: </head>
5: <body>
6: <?php
7: $mood = "triste";
8: if ( $mood == "heureux" )
9: {
print "Hourra, je suis de bonne humeur";
}
elseif ( $mood == "triste" )
{
print "Non. Ne te décourage pas !";
}
else
{
print "Ni heureux ni triste, mais $mood";
}
?>
</body>
</html>
Listing 5.4 : Une instruction switch
1: <html>
2: <head>
3: <title>Listing 5.4</title>
4: </head>
5: <body>
6: <?php
7: $mood = "triste";
8: switch ( $mood )
9: {
case "heureux":
print "Hourra, je suis de bonne humeur";
break;
case "triste":
print "Non. Ne te décourage pas !";
break;
default:
print "Ni heureux ni triste, mais $mood";
}
?>
</body>
</html>
Listing 5.5 : Utilisation de l'opérateur ?
1: <html>
2: <head>
3: <title>Listing 5.5</title>
4: </head>
5: <body>
6: <?php
7: $mood = "triste";
8: $text = ( $mood=="heureux" )?"Hourra, je suis de bonne humeur":"Pas
heureux, mais $mood";
9: print "$text";
?>
</body>
</html>
Listing 5.6 : Une instruction while
1: <html>
2: <head>
3: <title>Listing 5.6</title>
4: </head>
5: <body>
6: <?php
7: $counter = 1;
8: while ( $counter <= 12 )
9: {
print "$counter fois 2 donne ".($counter*2)."<br>";
$counter++;
}
?>
</body>
</html>
Listing 5.7 : L'instruction do...while
1: <html>
2: <head>
3: <title>Listing 5.7</title>
4: </head>
5: <body>
6: <?php
7: $num = 1;
8: do
9: {
print "Nombre d'exécution : $num<br>\n";
$num++;
}
while ( $num > 200 && $num < 400 );
?>
</body>
</html>
Listing 5.8 : Utilisation d'une instruction for
1: <html>
2: <head>
3: <title>Listing 5.8</title>
4: </head>
5: <body>
6: <?php
7: for ( $counter=1; $counter<=12; $counter++ )
8: {
9: print "$counter fois 2 donne ".($counter*2)."<br>";
}
?>
</body>
</html>
Listing 5.9 : Une boucle for qui divise 4000 par dix nombres incrémentés
1: <html>
2: <head>
3: <title>Listing 5.9</title>
4: </head>
5: <body>
6: <?php
7: for ( $counter=1; $counter <= 10, $counter++ )
8: {
9: $temp = 4000/$counter;
print "4000 divisé par $counter donne... $temp<br>";
}
?>
</body>
</html>
Listing 5.10 : Utilisation d'une instruction break
1: <html>
2: <head>
3: <title>Listing 5.10</title>
4: </head>
5: <body>
6: <?php
7: $counter = -4;
8: for ( ; $counter <= 10; $counter++ )
9: {
if ( $counter == 0 )
break;
$temp = 4000/$counter;
print "4000 divisé par $counter donne... $temp<br>";
}
?>
</body>
</html>
Listing 5.11 : L'instruction continue
1: <html>
2: <head>
3: <title>Listing 5.11</title>
4: </head>
5: <body>
6: <?php
7: $counter = -4;
8: for ( ; $counter <= 10; $counter++ )
9: {
if ( $counter == 0 )
continue;
$temp = 4000/$counter;
print "4000 divisé par $counter donne... $temp<br>";
}
?>
</body>
</html>
Listing 5.12 : Imbrication de deux boucles for
1: <html>
2: <head>
3: <title>Listing 5.12</title>
4: </head>
5: <body>
6: <?php
7: print "<table border="1">\n";
8: for ( $y=1; $y<=12; $y++ )
9: {
print "<tr>\n";
for ( $x=1; $x<=12; $x++ )
{
print "\t<td>";
print ($x*$y);
print "</td>\n";
}
print "</tr>\n";
}
print "</table>";
?>
</body>
</html>
Listing 6.1 : Appel de la fonction abs() intégrée
1: <html>
2: <head>
3: <title>Listing 6.1</title>
4: </head>
5: <body>
6: <?php
7: $num = -321;
8: $newnum = abs( $num );
9: print $newnum;
// affiche "321"
?>
</body>
</html>
Listing 6.2 : Déclaration d'une fonction
1: <html>
2: <head>
3: <title>Listing 6.2</title>
4: </head>
5: <body>
6: <?php
7: function bighello()
8: {
9: print "<h1>BONJOUR !</h1>";
}
bighello();
?>
</body>
</html>
Listing 6.3 : Déclaration d'une fonction qui nécessite un argument
1: <html>
2: <head>
3: <title>Listing 6.3</title>
4: </head>
5: <body>
6: <?php
7: function printBR( $txt )
8: {
9: print ("$txt<br>\n");
}
printBR("Voici une ligne");
printBR("Voici une nouvelle ligne");
printBR("Voici encore une autre ligne");
?>
</body>
</html>
Listing 6.4 : Une fonction qui renvoie une valeur
1: <html>
2: <head>
3: <title>Listing 6.4</title>
4: </head>
5: <body>
6: <?php
7: function addNums( $firstnum, $secondnum )
8: {
9: $result = $firstnum + $secondnum;
return $result;
}
print addNums(3,5);
// affichera "8"
?>
</body>
</html>
Listing 6.5 : Appel dynamique d'une fonction
1: <html>
2: <head>
3: <title>Listing 6.5</title>
4: </head>
5: <body>
6: <?php
7: function sayHello()
8: {
9: print "bonjour<br>";
}
$function_holder = "sayHello";
$function_holder();
?>
</body>
</html>
Listing 6.6 : La portée des variables
1: <html>
2: <head>
3: <title>Listing 6.6</title>
4: </head>
5: <body>
6: <?php
7: function test()
8: {
9: $testvariable = "voici une variable test";
}
print "variable test : $testvariable<br>";
?>
</body>
</html>
Listing 6.7 : Les variables définies en dehors d'une fonction ne sont
pas accessibles dans cette dernière
1: <html>
2: <head>
3: <title>Listing 6.7</title>
4: </head>
5: <body>
6: <?php
7: $life = 42;
8: function meaningOfLife()
9: {
print "Le sens de la vie est $life<br>";
}
meaningOfLife();
?>
</body>
</html>
Listing 6.8 : Accès aux variables globales à l'aide de l'instruction
global
1: <html>
2: <head>
3: <title>Listing 6.8</title>
4: </head>
5: <body>
6: <?php
7: $life=42;
8: function meaningOfLife()
9: {
global $life;
print "Le sens de la vie est $life<br>";
}
meaningOfLife();
?>
</body>
</html>
Listing 6.9 : Utilisation de l'instruction global pour garder une trace de
la valeur d'une variable entre deux appels de fonction
1: <html>
2: <head>
3: <title>Listing 6.9</title>
4: </head>
5: <body>
6: <?php
7: $num_of_calls = 0;
8: function andAnotherThing( $txt )
9: {
global $num_of_calls;
$num_of_calls++;
print "<h1>$num_of_calls. $txt</h1>";
}
andAnotherThing("Ustensiles");
print("Nous vous offrons un large éventail d'ustensiles<p>");
andAnotherThing("Outils");
print("Les meilleurs du monde<p>");
?>
</body>
</html>
Listing 6.10 : Utilisation de l'instruction static pour garder une trace de
la valeur d'une variable entre deux appels de fonction
1: <html>
2: <head>
3: <title>Listing 6.10</title>
4: </head>
5: <body>
6: <?php
7: function andAnotherThing( $txt )
8: {
9: static $num_of_calls = 0;
$num_of_calls++;
print "<h1>$num_of_calls. $txt</h1>";
}
andAnotherThing("Ustensiles");
print("Nous vous offrons un large éventail d'ustensiles<p>");
andAnotherThing("Outils");
print("Les meilleurs du monde<p>");
?>
</body>
</html>
Listing 6.11 : Une fonction nécessitant deux arguments
1: <html>
2: <head>
3: <title>Listing 6.11</title>
4: </head>
5: <body>
6: <?php
7: function fontWrap( $txt, $size )
8: {
9: print "<font size=\"$size\" face=\"Helvetica,Arial,Sans-Serif\">$txt</font>";
}
fontWrap("Un en-tête<br>",5);
fontWrap("Texte du corps du document<br>",3);
fontWrap("Texte supplémentaire<BR>",3);
fontWrap("Encore plus de texte<BR>",3);
?>
</body>
</html>
Listing 6.12 : Une fonction avec un argument optionnel
1: <html>
2: <head>
3: <title>Listing 6.12</title>
4: </head>
5: <body>
6: <?php
7: function fontWrap( $txt, $size=3 )
8: {
9: print "<font size=\"$size\"face=\"Helvetica,Arial,Sans-Serif\">$txt</font>";
}
fontWrap("Un en-tête<br>",5);
fontWrap("Texte du corps du document<br>");
fontWrap("Texte supplémentaire<br>");
fontWrap("Encore plus de texte<br>");
?>
</body>
</html>
Listing 6.13 : Transmission d'un argument à une fonction par valeur
1: <html>
2: <head>
3: <title>Listing 6.13</title>
4: </head>
5: <body>
6: <?php
7: function addFive( $num )
8: {
9: $num += 5;
}
$orignum = 10;
addFive( $orignum );
print( $orignum );
?>
</body>
</html>
Listing 6.14 : Utilisation d'un appel de fonction pour transmettre un argument
à une fonction par référence
1: <html>
2: <head>
3: <title>Listing 6.14</title>
4: </head>
5: <body>
6: <?php
7: function addFive( $num )
8: {
9: $num += 5;
}
$orignum = 10;
addFive( &$orignum );
print( $orignum );
?>
</body>
</html>
Listing 6.15 : Utilisation d'une définition de fonction pour transmettre
un argument à une fonction par référence
1: <html>
2: <head>
3: <title>Listing 6.15</title>
4: </head>
5: <body>
6: <?php
7: function addFive( &$num )
8: {
9: $num += 5;
}
$orignum = 10;
addFive( $orignum );
print( $orignum );
?>
</body>
</html>
Listing 7.1 : Définir un tableau multidimensionnel
1: <html>
2: <head>
3: <title>Listing 7.1</title>
4: </head>
5: <body>
6: <?php
7: $characters = array (
8: array ( nom=>"Bob",
9: profession=>"super héro",
âge=>30,
spécialité=>"vision sous forme de rayons X" ),
array ( nom=>"Sally",
profession=>"super héro",
âge=>24,
spécialité=>"force surnaturelle" ),
array ( nom=>"Mary",
profession=>"voyou espiègle",
âge=>63,
spécialité=>"technologie microscopique" )
);
print $characters[0][profession];
// affiche "super héro"
?>
</body>
</html>
Listing 7.2 : Parcourir en boucle un tableau associatif à l'aide de
foreach
1: <html>
2: <head>
3: <title>Listing 7.2</title>
4: </head>
5: <body>
6: <?php
7: $character = array (
8: nom=>"Bob",
9: profession=>"super héro",
âge=>30,
"spécialité"=>"vision sous forme de rayons X"
);
foreach ( $character as $key=>$val )
{
print "$key = $val<br>";
}
?>
</body>
</html>
Listing 7.3 : Parcourir en boucle un tableau multidimensionnel
1: <html>
2: <head>
3: <title>Listing 7.3</title>
4: </head>
5: <body>
6: <?php
7: $characters = array (
8: array ( nom=>"Bob",
9: profession=>"super héro",
âge=>30,
spécialité=>"vision sous forme de rayons X" ),
array ( nom=>"Sally",
profession=>"super héro",
âge=>24,
spécialité=>"force surnaturelle" ),
array ( nom=>"Mary",
profession=>"voyou espiègle",
âge=>63,
spécialité=>"technologie microscopique" )
);
foreach ( $characters as $val )
{
foreach ( $val as $key=>$final_val )
{
print "$key: $final_val<br>";
}
print "<br>";
}
?>
</body>
</html>
Listing 8.1 : Une classe avec une méthode
1: <html>
2: <head>
3: <title>Listing 8.1</title>
4: <body>
5: <?php
6: class first_class
7: {
8: var $name;
9: function sayHello()
{
print "hello";
}
}
$obj1 = new first_class();
$obj1->sayHello();
// affiche "hello"
?>
</body>
</html>
Listing 8.2 : Accès à une propriété depuis une
méthode
1: <html>
2: <head>
3: <title>Listing 8.2</title>
4: <body>
5: <?php
6: class first_class
7: {
8: var $name="harry";
9: function sayHello()
{
print "hello, mon nom est $this->name<BR>";
}
}
$obj1 = new first_class();
$obj1->sayHello();
// affiche "hello, mon nom est harry"
?>
</body>
</html>
Listing 8.3 : Modification de la valeur d'une propriété depuis
une méthode
1: <html>
2: <head>
3: <title>Listing 8.3</title>
4: </head>
5: <body>
6: <?php
7: class first_class
8: {
9: var $name="harry";
function setName( $n )
{
$this->name = $n;
}
function sayHello()
{
print "hello, mon nom est $this->name<BR>";
}
}
$obj1 = new first_class();
$obj1->setName("william");
$obj1->sayHello();
// affiche "hello, mon nom est william"
?>
</body>
</html>
Listing 8.4 : Une classe avec un constructeur
1: <html>
2: <head>
3: <title>Listing 8.4</title>
4: </head>
5: <body>
6: <?php
7: class first_class
8: {
9: var $name;
function first_class( $n="anon" )
{
$this->name = $n;
}
function sayHello()
{
print "hello, mon nom est $this->name<BR>";
}
}
$obj1 = new first_class("bob");
$obj2 = new first_class("harry");
$obj1->sayHello();
// affiche "hello, mon nom est bob"
$obj2->sayHello();
// affiche "hello, mon nom est harry"
?>
</body>
</html>
Listing 8.5 : La classe Table
1: <html>
2: <head>
3: <title>Listing 8.5</title>
4: </head>
5: <body>
6: <?php
7: class Table
8: {
9: var $table_array = array();
var $headers = array();
var $cols;
function Table( $headers )
{
$this->headers = $headers;
$this->cols = count ( $headers );
}
function addRow( $row )
{
if ( count ($row) != $this->cols )
return false;
array_push($this->table_array, $row);
return true;
}
function addRowAssocArray( $row_assoc )
{
$row = array();
foreach ( $this->headers as $header )
{
if ( ! isset( $row_assoc[$header] ))
$row_assoc[$header] = "";
$row[] = $row_assoc[$header];
}
array_push($this->table_array, $row);
return true;
}
function output()
{
print "<pre>";
foreach ( $this->headers as $header )
print "<B>$header</B> ";
print "\n";
foreach ( $this->table_array as $y )
{
foreach ( $y as $xcell )
print "$xcell ";
print "\n";
}
print "</pre>";
}
}
$test = new table( array("a","b","c") );
$test->addRow( array(1,2,3) );
$test->addRow( array(4,5,6) );
$test->addRowAssocArray( array ( b=>0, a=>6, c=>3 ) );
$test->output();
?>
</body>
</html>
Listing 8.6 : Création d'une classe qui hérite d'une autre
1: <html>
2: <head>
3: <title>Listing 8.6</title>
4: </head>
5: <body>
6: <?php
7: class first_class
8: {
9: var $name = "harry";
function first_class( $n )
{
$this->name = $n;
}
function sayHello()
{
print "Hello, mon nom est $this->name<br>";
}
}
class second_class extends first_class
{
}
$test = new second_class("fils de harry");
$test->sayHello();
// affiche "Hello, mon nom est fils de harry"
?>
</body>
</html>
Listing 8.7 : La méthode d'une classe enfant est prioritaire sur celle
de la classe parent
1: <html>
2: <head>
3: <title>Listing 8.7</title>
4: </head>
5: <body>
6: <?php
7: class first_class
8: {
9: var $name = "harry";
function first_class( $n )
{
$this->name = $n;
}
function sayHello()
{
print "Hello, mon nom est $this->name<br>";
}
}
class second_class extends first_class
{
function sayHello()
{
print "Je ne vous révélerai pas mon nom<br>";
}
}
$test = new second_class("fils de harry");
$test->sayHello();
// affiche "Je ne vous révélerai pas mon nom"
?>
</body>
</html>
Listing 8.8 : Appel d'une méthode non prioritaire
1: <html>
2: <head>
3: <title>Listing 8.8</title>
4: </head>
5: <body>
6: <?php
7: class first_class
8: {
9: var $name = "harry";
function first_class( $n )
{
$this->name = $n;
}
function sayHello()
{
print "Hello, mon nom est $this->name<br>";
}
}
class second_class extends first_class
{
function sayHello()
{
print "Je ne vous révélerai pas mon nom -- ";
first_class::sayHello();
}
}
$test = new second_class("fils de harry");
$test->sayHello();
// affiche "je ne vous révèlerai pas mon nom -- Hello, mon
nom est fils de harry"
?>
</body>
</html>
Listing 8.9 : Les classes Table et HTMLTable
1: <html>
2: <head>
3: <title>Tester les objets</title>
4: </head>
5: <body>
6: <?php
7: class Table
8: {
9: var $table_array = array();
var $headers = array();
var $cols;
function Table( $headers )
{
$this->headers = $headers;
$this->cols = count ( $headers );
}
function addRow( $row )
{
if ( count ($row) != $this->cols )
return false;
array_push($this->table_array, $row);
return true;
}
function addRowAssocArray( $row_assoc )
{
if ( count ($row_assoc) != $this->cols )
return false;
$row = array();
foreach ( $this->headers as $header )
{
if ( ! isset( $row_assoc[$header] ))
$row_assoc[$header] = " ";
$row[] = $row_assoc[$header];
}
array_push($this->table_array, $row);
}
function output()
{
print "<pre>";
foreach ( $this->headers as $header )
print "<B>$header</B> ";
print "\n";
foreach ( $this->table_array as $y )
{
foreach ( $y as $xcell )
print "$xcell ";
print "\n";
}
print "</pre>";
}
}
class HTMLTable extends Table
{
var $bgcolor;
var $cellpadding = "2";
function HTMLTable( $headers, $bg="#ffffff" )
{
Table::Table($headers);
$this->bgcolor=$bg;
}
function setCellpadding( $padding )
{
$this->cellpadding = $padding;
}
function output()
{
print "<table cellpadding=\"$this->cellpadding\" border=1>";
foreach ( $this->headers as $header )
print "<td bgcolor=\"$this->bgcolor\"><b>$header</b></td>";
foreach ( $this->table_array as $row=>$cells )
{
print "<tr>";
foreach ( $cells as $cell )
print "<td bgcolor=\"$this->bgcolor\">$cell</td>";
print "</tr>";
}
print "</table>";
}
}
$test = new HTMLTable( array("a","b","c"), "#00FF00");
$test->setCellpadding( 7 );
$test->addRow( array(1,2,3));
$test->addRow( array(4,5,6));
$test->addRowAssocArray( array ( b=>0, a=>6, c=>3 ));
$test->output();
?>
</body>
</html>
Listing 9.1 : Parcourir le tableau $GLOBALS
1: <html>
2: <head>
3: <title>Listing 9.1 : parcourir le tableau $GLOBALS</title>
4: </head>
5: <body>
6: <?php
7: $user1 = "Bob";
8: $user2 = "Harry";
9: $user3 = "Mary";
foreach ( $GLOBALS as $key=>$value )
{
print "\$GLOBALS[\"$key\"] == $value<br>";
}
?>
</body>
</html>
Listing 9.2 : Un formulaire HTML simple
1: <html>
2: <head>
3: <title>Listing 9.2 : un formulaire HTML simple</title>
4: </head>
5: <body>
6: <form action="eg9.3.php" method="GET">
7: <input type="text" name="user">
8: <br>
9: <textarea name="address" rows="5" cols="40">
</textarea>
<br>
<input type="submit" value="hit it!">
</form>
</body>
</html>
Listing 9.3 : Lire l'entrée provenant du formulaire du Listing 9.2
1: <html>
2: <head>
3: <title>Listing 9.3 : lire l'entrée provenant du formulaire du
Listing 9.2</title>
4: </head>
5: <body>
6: <?php
7: print "Bienvenue <b>$user</b><P>\n\n";
8: print "Votre adresse est :<P>\n\n<b>$address</b>";
9: ?>
</body>
</html>
Listing 9.4 : Un formulaire HTML incluant un élément SELECT
1: <html>
2: <head>
3: <title>Listing 9.4 : un formulaire HTML incluant un élément
SELECT</title>
4: </head>
5: <body>
6: <form action="eg9.5.php" method="POST">
7: <input type="text" name="user">
8: <br>
9: <textarea name="address" rows="5" cols="40">
</textarea>
<br>
<select name="products[]" multiple>
<option>Tournevis sonique
<option>Tricorde
<option>ORAC AI
<option>HAL 2000
</select>
<br>
<input type="submit" value="Soumettre !">
</form>
</body>
</html>
Listing 9.5 : Lire l'entrée depuis le formulaire du Listing 9.4
1: <html>
2: <head>
3: <title>Listing 9.5 : lire l'entrée depuis le formulaire du Listing
9.4</title>
4: </head>
5: <body>
6: <?php
7: print "Bienvenue <b>$user</b><p>\n\n";
8: print "Votre adresse est :<p>\n\n<b>$address</b><p>\n\n";
9: print "Votre choix de produits est :<p>\n\n";
print "<ul>\n\n";
foreach ( $products as $value )
{
print "<li>$value<br>\n";
}
print "</ul>";
?>
</body>
</html>
Listing 9.6 : Lire une entrée depuis tout formulaire utilisant le tableau
$HTTP_GET_VARS
1: <html>
2: <head>
3: <title>Listing 9.6 : lecture d'une entrée depuis tout formulaire
utilisant le tableau $HTTP_GET_VARS</title>
4: </head>
5: <body>
6: <?php
7: foreach ( $HTTP_GET_VARS as $key=>$value )
8: {
9: print "$key == $value<BR>\n";
}
?>
</body>
</html>
Listing 9.7 : Lire une entrée depuis tout formulaire utilisant le tableau
$HTTP_GET_VARS
1: <html>
2: <head>
3: <title>Listing 9.7 : lecture d'une entrée depuis tout formulaire
utilisant le tableau $HTTP_GET_VARS</title>
4: </head>
5: <body>
6: <?php
7: foreach ( $HTTP_GET_VARS as $key=>$value )
8: {
9: if ( gettype( $value ) == "array" )
{
print "$key == <br>\n";
foreach ( $value as $two_dim_value )
print ".........$two_dim_value<br>";
}
else
{
print "$key == $value<br>\n";
}
}
?>
</body>
</html>
Listing 9.8 : Extraire des paramètres soit depuis une requête
GET, soit depuis une requête POST
1: <html>
2: <head>
3: <title>Listing 9.8 : extraire des paramètres soit depuis une
requête
4: GET, soit depuis une requête POST</title>
5: </head>
6: <body>
7: <?php
8: $PARAMS = ( isset( $HTTP_POST_VARS ) )
9: ? $HTTP_POST_VARS : $HTTP_GET_VARS;
foreach ( $PARAMS as $key=>$value )
{
if ( gettype( $value ) == "array" )
{
print "$key == <br>\n";
foreach ( $value as $two_dim_value )
print ".........$two_dim_value<br>";
}
else
{
print "$key == $value<br>\n";
}
}
?>
</body>
</html>
Listing 9.9 : Un formulaire HTML qui s'appelle lui-même
1: <html>
2: <head>
3: <title>Listing 9.9 : un formulaire HTML qui s'appelle lui-même</title>
4: </head>
5: <body>
6: <form action="<?php print $PHP_SELF?>" method="POST">
7: Entre ta réponse ici : <input type="text" name="guess">
8: </form>
9: </body>
</html>
Listing 9.10 : Un script PHP proposant de deviner un nombre
1: <?php
2: $num_to_guess = 42;
3: $message = "";
4: if ( ! isset( $guess ) )
5: {
6: $message = "Bienvenue dans la machine d'essai !";
7: }
8: elseif ( $guess > $num_to_guess )
9: {
$message = "$guess est trop élevé ! Essaie un nombre plus
petit";
}
elseif ( $guess < $num_to_guess )
{
$message = "$guess est trop petit ! Essaie un nombre plus élevé";
}
else // doit être équivalent
{
$message = "Tu as trouvé !";
}
?>
<html>
<head>
<title>Listing 9.10 : un script PHP devinant un nombre</title>
</head>
<body>
<h1>
<?php print $message ?>
</h1>
<form action="<?php print $PHP_SELF?>" method="POST">
Réalise une tentative ici : <input type="text" name="guess">
</form>
</body>
</html>
Listing 9.11 : Sauvegarder l'état avec un champ masqué
1: <?php
2: $num_to_guess = 42;
3: $message = "";
4: $num_tries = ( isset( $num_tries ) ) ? ++$num_tries : 0;
5: if ( ! isset( $guess ) )
6: {
7: $message = "Bienvenue dans la machine d'essai !";
8: }
9: elseif ( $guess > $num_to_guess )
{
$message = "$guess est trop élevé ! Essaie un nombre plus
petit";
}
elseif ( $guess < $num_to_guess )
{
$message = "$guess est trop petit ! Essaie un nombre plus élevé";
}
else // doit être équivalent
{
$message = "Tu as trouvé !";
}
$guess = (int) $guess;
?>
<html>
<head>
<title>Listing 9.11 : sauvegarder l'état avec un champ masqué</title>
</head>
<body>
<h1>
<?php print $message ?>
</h1>
Guess number: <?php print $num_tries?>
<form action="<?php print $PHP_SELF?>" method="POST">
Réalise une tentative ici :
<input type="text" name="guess" value="<?php
print $guess?>">
<input type="hidden" name="num_tries" value="<?php
print $num_tries?>">
</form>
</body>
</html>
Listing 9.12 : En-têtes typiques expédiés depuis un script
PHP
HEAD /matt/php-book/forms/eg9.1.php HTTP/1.0
HTTP/1.1 200 OK
Date: Sun, 09 Jan 2000 18:37:45 GMT
Server: Apache/1.3.9 (Unix) PHP/4.0
Connection: close
Content-Type: text/html
Listing 9.13 : Utiliser header() pour envoyer des en-têtes bruts
1: <?php
2: $num_to_guess = 42;
3: $message = "";
4: $num_tries = ( isset( $num_tries ) ) ? ++$num_tries : 0;
5: if ( ! isset( $guess ) )
6: {
7: $message = "Bienvenue dans la machine d'essai !";
8: }
9: elseif ( $guess > $num_to_guess )
{
$message = "$num est trop élevé ! Essaie un nombre plus petit";
}
elseif ( $guess < $num_to_guess )
{
$message = "$num est trop petit ! Essaie un nombre plus élevé";
}
else // doit être équivalent
{
header( "Location: congrats.html" );
exit;
}
$guess = (int) $guess;
?>
<html>
<head>
<title>Listing 9.13 : utiliser header() pour envoyer des en-têtes
bruts</title>
</head>
<body>
<h1>
<?php print $message ?>
</h1>
Guess number: <?php print $num_tries?>
<form action="<?php print $PHP_SELF?>" method="POST">
Réalise une tentative ici :
<input type="text" name="guess" value="<?php
print $guess?>">
<input type="hidden" name="num_tries"
value="<?php print $num_tries ?>">
</form>
</body>
</html>
Listing 9.14 : Un formulaire de téléchargement de fichier simple
1: <html>
2: <head>
3: <title>Listing 9.14 : un formulaire de téléchargement
de fichier simple</title>
4: </head>
5: <body>
6: <form enctype="multipart/form-data" action="<?print
$PHP_SELF?>" method="POST">
7: <input type="hidden" name="MAX_FILE_SIZE" value="51200">
8: <input type="file" name="fupload"><br>
9: <input type="submit" value="Téléchargez !">
</form>
</body>
</html>
Listing 9.15 : Un script de téléchargement de fichier
1: <html>
2: <head>
3: <title>Listing 9.15 : un script de téléchargement de
fichier</title>
4: </head>
5: <?php
6: $file_dir = "/home/matt/htdocs/uploads";
7: $file_url = "http://www.corrosive.co.uk/matt/uploads";
8: if ( isset( $fupload ) )
9: {
print "path: $fupload<br>\n";
print "name: $fupload_name<br>\n";
print "size: $fupload_size bytes<br>\n";
print "type: $fupload_type<p>\n\n";
if ( $fupload_type == "image/gif" )
{
copy ( $fupload, "$file_dir/$fupload_name") or die ("Couldn't
copy");
print "<img src=\"$file_url/$fupload_name\"><p>\n\n";
}
}
?>
<body>
<form enctype="multipart/form-data" action="<?php print
$PHP_SELF?>" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="51200">
<input type="file" name="fupload"><br>
<input type="submit" value="Envoyez le fichier !">
</form>
</body>
</html>
Listing 10.1 : Utilisation de include()
1: <html>
2: <head>
3: <title>Listing 10.1 : utilisation de include()</title>
4: </head>
5: <body>
6: <?php
7: include("eg10.2.php");
8: ?>
9: </body>
</html>
Listing 10.2 : Le fichier inclus du Listing 10.1
J'ai été inclus !!
Listing 10.3 : Utilisation de la fonction include() pour exécuter du
code PHP dans un autre fichier
1: <html>
2: <head>
3: <title>Listing 10.3 : utilisation de la fonction include() pour exécuter
du code PHP dans un autre fichier</title>
4: </head>
5: <body>
6: <?php
7: include("eg10.4.php");
8: ?>
9: </body>
</html>
Listing 10.4 : Un fichier inclus contenant du code PHP
<?php
print "J'ai été inclus !!<BR>";
print "Mais maintenant je peux ajouter... 4 + 4 = ".(4 + 4);
?>
Listing 10.5 : Utilisation de include() pour exécuter du code PHP et
affecter la valeur de retour
1: <html>
2: <head>
3: <title>Listing 10.5 : utilisation de include() pour exécuter
du code PHP et affecter la valeur de retour</title>
4: </head>
5: <body>
6: <?php
7: $addResult = include("eg10.6.php");
8: print "Le fichier inclus renvoyé est $addResult";
9: ?>
</body>
</html>
Listing 10.6 : Un fichier inclus qui retourne une valeur
<?php
$retval = ( 4 + 4 );
return $retval;
?>
Ce code HTML ne devrait jamais être affiché, car il est situé
après une instruction de retour !
Listing 10.7 : Utilisation de include() dans une boucle
1: <html>
2: <head>
3: <title>Listing 10.7 : utilisation de include() dans une boucle</title>
4: </head>
5: <body>
6: <?php
7: for ( $x = 1; $x<=3; $x++ )
8: {
9: $incfile = "incfile$x".".txt";
print "Essai d'inclusion de $incfile<br>";
include( "$incfile" );
print "<p>";
}
?>
</body>
</html>
Listing 10.8 : Une fonction affichant les résultats de multiples tests
sur un fichier
1: <html>
2: <head>
3: <title>Listing 10.8 : une fonction affichant les résultats de
multiples tests sur un fichier</title>
4: </head>
5: <body>
6: <?php
7: $file = "test.txt";
8: outputFileTestInfo( $file );
9: function outputFileTestInfo( $f )
{
if ( ! file_exists( $f ) )
{
print "$f n'existe pas<BR>";
return;
}
print "$f est ".(is_file( $f )?"":"pas ")."un
fichier<br>";
print "$f est ".(is_dir( $f )?"":"pas ")."un
répertoire<br>";
print "$f est ".(is_readable( $f )?"":"pas ")."lisible<br>";
print "$f est ".(is_writable( $f )?"":"pas ")."inscriptible<br>";
print "$f est ".(is_executable( $f )?"":"pas ")."exécutable<br>";
print "$f fait ".(filesize($f))." octets<br>";
print "$f a été accédé le ".date( "D
d M Y g:i A", fileatime( $f ) )."<br>";
print "$f a été modifié le ".date( "D d
M Y g:i A", filemtime( $f ) )."<br>";
print "$f a été changé le ".date( "D d M
Y g:i A", filectime( $f ) )."<br>";
}
?>
</body>
</html>
Listing 10.9 : Ouvrir et lire un fichier ligne par ligne
1: <html>
2: <head>
3: <title>Listing 10.9 : ouvrir et lire un fichier ligne par ligne</title>
4: </head>
5: <body>
6: <?php
7: $filename = "test.txt";
8: $fp = fopen( $filename, "r" ) or die("Impossible d'ouvrir
$filename");
9: while ( ! feof( $fp ) )
{
$line = fgets( $fp, 1024 );
print "$line<br>";
}
?>
</body>
</html>
Listing 10.10 : Lecture d'un fichier avec fread()
1: <html>
2: <head>
3: <title>Listing 10.10 : lire un fichier avec fread()</title>
4: </head>
5: <body>
6: <?php
7: $filename = "test.txt";
8: $fp = fopen( $filename, "r" ) or die("Impossible d'ouvrir
$filename");
9: while ( ! feof( $fp ) )
{
$chunk = fread( $fp, 16 );
print "$chunk<br>";
}
?>
</body>
</html>
Listing 10.11 : Se déplacer dans un fichier avec fseek()
1: <html>
2: <head>
3: <title>Listing 10.11 : se déplacer dans un fichier avec fseek()</title>
4: </head>
5: <body>
6: <?php
7: $filename = "test.txt";
8: $fp = fopen( $filename, "r" ) or die("Impossible d'ouvrir
$filename");
9: $fsize = filesize($filename);
$halfway = (int)( $fsize / 2 );
print "Point central : $halfway <BR>\n";
fseek( $fp, $halfway );
$chunk = fread( $fp, ($fsize - $halfway) );
print $chunk;
?>
</body>
</html>
Listing 10.12 : Se déplacer dans un fichier avec fseek()
1: <html>
2: <head>
3: <title>Listing 10.12 : se déplacer dans un fichier avec fseek()</title>
4: </head>
5: <body>
6: <?php
7: $filename = "test.txt";
8: $fp = fopen( $filename, "r" ) or die("Impossible d'ouvrir
$filename");
9: while ( ! feof( $fp ) )
{
$char = fgetc( $fp );
print "$char<BR>";
}
?>
</body>
</html>
Listing 10.13 : Ecrire et réaliser des ajouts dans un fichier
1: <html>
2: <head>
3: <title>Listing 10.13 : écrire et réaliser des ajouts
dans un fichier</title>
4: </head>
5: <body>
6: <?php
7: $filename = "test.txt";
8: print "Ecrire dans $filename<br>";
9: $fp = fopen( $filename, "w" ) or die("Impossible d'ouvrir
$filename");
fwrite( $fp, "Bonjour monde\n" );
fclose( $fp );
print "Réaliser un ajout dans $filename<br>";
$fp = fopen( $filename, "a" ) or die("Impossible d'ouvrir $filename");
fputs( $fp, "Une autre chaîne\n" );
fclose( $fp );
?>
</body>
</html>
Listing 10.14 : Etablir le contenu d'un répertoire avec readdir()
1: <html>
2: <head>
3: <title>Listing 10.14 : établir le contenu
4: d'un répertoire avec readdir()</title>
5: </head>
6: <body>
7: <?php
8: $dirname = "testdir";
9: $dh = opendir( $dirname );
while ( gettype( $file = readdir( $dh )) != boolean )
{
if ( is_dir( "$dirname/$file" ) )
print " ";
print "$file<br>";
}
closedir( $dh );
?>
</body>
</html>
Listing 11.1 : Ajout d'éléments dans une base de données
DBM
1: <html>
2: <head>
3: <title>Listing 11.1 : ajout d'éléments dans une base
de données DBM</title>
4: </head>
5: <body>
6: Ajout des produits ici...
7:
8: <?php
9: $dbh = dbmopen( "./data/products", "c" ) or die( "Impossible
d'ouvrir DBM" );
dbminsert( $dbh, "Tournevis sonique", "23,20F" );
dbminsert( $dbh, "Tricorde", "55,50F" );
dbminsert( $dbh, "ORAC AI", "2200,50F" );
dbminsert( $dbh, "HAL 2000", "4500,50F" );
dbmclose( $dbh );
?>
</body>
</html>
Listing 11.2 : Ajouter ou modifier des éléments dans une base
de données DBM
<html>
<head>
<title>Listing 11.2 : ajouter ou modifier des éléments dans
une base de données DBM</title>
</head>
<body>
Ajout des produits ici...
<?php
$dbh = dbmopen( "./data/products", "c" )
or die( "Impossible d'ouvrir DBM" );
dbmreplace( $dbh, "Tournevis sonique", "25,20F" );
dbmreplace( $dbh, "Tricorde", "56,50F" );
dbmreplace( $dbh, "ORAC AI", "2209,50F" );
dbmreplace( $dbh, "HAL 2000", "4535,50F" );
dbmclose( $dbh );
?>
</body>
</html>
Listing 11.3 : Lecture de tous les enregistrements d'une base de données
DBM
1: <html>
2: <head>
3: <title>Listing 11.3 : Lire tous les
4: enregistrements depuis une base de données DBM </title>
5: </head>
6: <body>
7: Dans notre magasin de gadgets impossibles,
8: nous vous offrons les produits intéressants
9: suivants :
<p>
<table border=1 cellpadding ="5">
<tr>
<td align="center"> <b>Produit</b></td>
<td align="center"> <b>Prix</b> </td>
</tr>
<?php
$dbh = dbmopen( "./data/products", "c" )
or die( "Impossible d'ouvrir DBM" );
$key = dbmfirstkey( $dbh );
while ( $key != "" )
{
$value = dbmfetch( $dbh, $key );
print "<tr><td align = \"left\"> $key </td>";
print "<td align = \"right\"> \$$value </td></tr>";
$key = dbmnextkey( $dbh, $key );
}
dbmclose( $dbh );
?>
</table>
</body>
</html>
Listing 11.4 : Ajout de données complexes à une base DBM
1: <html>
2: <head>
3: <title>Listing 11.4 : ajout de données complexes à une
base DBM</title>
4: </head>
5: <body>
6: Ajout de données complexes à une base de données
7: <?php
8: $products = array(
9: "Tournevis sonique" => array( Prix=>"22,50F",
Livraison=>"12,50F",
Couleur=>"vert" ),
"Tricorde" => array( Prix=>"55,50F",
Livraison=>"7,50F",
Couleur=>"rouge" ),
"ORAC AI" => array( Prix=>"2200,50F",
Livraison=>"34,50F",
Couleur=>"bleu" ),
"HAL 2000" => array( Prix=>"4500,50F",
Livraison=>"18,50F",
Couleur=>"rose" )
);
$dbh = dbmopen( "./data/newproducts", "c" )
or die("Impossible d'ouvrir produits DBM");
while ( list ( $key, $value ) = each ( $products ) )
dbmreplace( $dbh, $key, serialize( $value ) );
dbmclose( $dbh );
?>
</table>
</body>
</html>
Listing 11.5 : Retirer des données sérialisées d'une base
DBM
1: <html>
2: <head>
3: <title>Listing 11.5 : Retirer des données sérialisées
4: d'une base de données DBM</title>
5: </head>
6: <body>
7: Dans notre magasin de gadgets impossibles,
8: nous vous offrons les produits intéressants
9: suivants :
<p>
<table border=1 cellpadding ="5">
<tr>
<td align="center"> <b>Produit</b></td>
<td align="center"> <b>Couleur</b> </td>
<td align="center"> <b>Livraison</b> </td>
<td align="center"> <b>Prix</b> </td>
</tr>
<?php
$dbh = dbmopen( "./data/newproducts", "c" )
or die("Impossible d'ouvrir test DBM");
$key = dbmfirstkey( $dbh );
while ( $key != "" )
{
$prodarray = unserialize( dbmfetch( $dbh, $key ) );
print "<tr><td align=\"left\"> $key </td>";
print "<td align=\"left\">$prodarray[Couleur] </td>\n";
print "<td align=\"right\">\$$prodarray[Livraison] </td>\n";
print "<td align=\"right\">\$$prodarray[Prix] </td></tr>\n";
$key = dbmnextkey( $dbh, $key );
}
dbmclose( $dbh );
?>
</table>
</body>
</html>
Listing 11.6 : Créer un formulaire HTML basé sur le contenu d'une
base de données DBM
1: <?
2: $dbh = dbmopen( "./data/products", "c" )
3: or die("Impossible d'ouvrir test DBM");
4: ?>
5: <html>
6: <head>
7: <title>Listing 11.6 : créer un formulaire HTML basé
8: sur le contenu d'une base de données DBM</title>
9: </head>
<body>
<form action="POST">
<table border="1">
<tr>
<td>Suppression</td>
<td>Produit</td>
<td>Prix</td>
</tr>
<?php
$key = dbmfirstkey( $dbh );
while ( $key != "" )
{
$price = dbmfetch( $dbh, $key );
print "<tr><td><input type='checkbox' name=\"delete[]\"
";
print "value=\"$key\"></td>";
print "<td>$key</td>";
print "<td> <input type=\"text\" name=\"prices[$key]\"
";
print "value=\"$price\"> </td></tr>";
$key = dbmnextkey( $dbh, $key );
}
dbmclose( $dbh );
?>
<tr>
<td> </td>
<td><input type="text" name="name_add"></td>
<td><input type="text" name="price_add"></td>
</tr>
<tr>
<td colspan=3 align="right">
<input type="submit" value="Modifier">
</td>
</tr>
</table>
</form>
</body>
</html>
Listing 11.7 : Le code de maintenance de produit complet
1: <?php
2: $dbh = dbmopen( "./data/products", "c" )
3: or die("Impossible d'ouvrir test DBM");
4:
5: if ( isset ( $delete ) )
6: {
7: while ( list ( $key, $val ) = each ( $delete ) )
8: {
9: unset( $prices[$val]);
dbmdelete( $dbh, $val );
}
}
if ( isset ( $prices ) )
{
while ( list ( $key, $val ) = each ( $prices ) )
dbmreplace( $dbh, $key, $val );
}
if ( ! empty( $name_add ) && ! empty( $price_add ) )
dbminsert( $dbh, "$name_add", "$price_add" );
?>
<html>
<head>
<title>Listing 11.7 : le code de maintenance de produit complet</title>
</head>
<body>
<form action="<? print $PHP_SELF; ?>" action="POST">
<table border="1">
<tr>
<td>Supprimer</td>
<td>Produit</td>
<td>Prix</td>
</tr>
<?php
$key = dbmfirstkey( $dbh );
while ( $key != "" )
{
$price = dbmfetch( $dbh, $key );
print "<tr><td><input type='checkbox' name=\"delete[]\"
";
print "value=\"$key\"></td>";
print "<td>$key</td>";
print "<td> <input type=\"text\" name=\"prices[$key]\"
";
print "value=\"$price\"> </td></tr>";
$key = dbmnextkey( $dbh, $key );
}
dbmclose( $dbh );
?>
<tr>
<td> </td>
<td><input type="text" name="name_add"></td>
<td><input type="text" name="price_add"></td>
</tr>
<tr>
<td colspan=3 align="right">
<input type="submit" value="Modifier">
</td>
</tr>
</table>
</form>
</body>
</html>
Listing 12.1 : Ouvrir une connexion et sélectionner une base de données
1: <html>
2: <head>
3: <title>Listing 12.1 : ouvrir une connexion et
4: sélectionner une base de données</title>
5: </head>
6: <body>
7: <?php
8: $user = "harry";
9: $pass = "elbomonkey";
$db = "sample";
$link = mysql_connect( "localhost", $user, $pass );
if ( ! $link )
die( "Impossible de se connecter à MySQL" );
print "Connexion au serveur réussie<P>";
mysql_select_db( $db )
or die ( "Impossible d'ouvrir $db: ".mysql_error() );
print "Sélection de la base de données réussie \"$db\"<P>";
mysql_close( $link );
?>
</body>
</html>
Listing 12.2 : Ajout d'une ligne à une table
1: <html>
2: <head>
3: <title>Listing 12.2 : ajout d'une ligne à une table</title>
4: </head>
5: <body>
6: <?php
7: $user = "harry";
8: $pass = "elbomonkey";
9: $db = "sample";
$link = mysql_connect( "localhost", $user, $pass );
if ( ! $link )
die( "Impossible de se connecter à MySQL" );
mysql_select_db( $db, $link )
or die ( "Impossible d'ouvrir $db: ".mysql_error() );
$query = "INSERT INTO domains ( domain, sex, mail )
values( '123xyz.com', 'F', 'sharp@adomain.com' )";
mysql_query( $query, $link )
or die ( "Impossible d'ajouter des données à la table \"domains\"
"
.mysql_error() );
mysql_close( $link );
?>
</body>
</html>
Listing 12.3 : Ajout d'une entrée d'utilisateur dans une base de données
1: <html>
2: <head>
3: <title>Listing 12.3 : ajout d'une entrée d'utilisateur dans
une base de données</title>
4: </head>
5: <body>
6: <?php
7: if ( isset( $domain ) && isset( $sex ) && isset( $domain
) )
8: {
9: // contrôle de l'entrée de l'utilisateur ici !
$dberror = "";
$ret = add_to_database( $domain, $sex, $mail, $dberror );
if ( ! $ret )
print "Erreur : $dberror<BR>";
else
print "Merci beaucoup";
}
else {
write_form();
}
function add_to_database( $domain, $sex, $mail, &$dberror )
{
$user = "harry";
$pass = "elbomonkey";
$db = "sample";
$link = mysql_pconnect( "localhost", $user, $pass );
if ( ! $link )
{
$dberror = "Impossible de se connecter au serveur MySQL";
return false;
}
if ( ! mysql_select_db( $db, $link ) )
{
$dberror = mysql_error();
return false;
}
$query = "INSERT INTO domains ( domain, sex, mail )
values( '$domain', '$sex', '$mail' )";
if ( ! mysql_query( $query, $link ) )
{
$dberror = mysql_error();
return false;
}
return true;
}
function write_form()
{
global $PHP_SELF;
print "<form action=\"$PHP_SELF\" method=\"POST\">\n";
print "<input type=\"text\" name=\"domain\">
";
print "Le domaine que vous aimeriez<p>\n";
print "<input TYPE=\"text\" name=\"mail\"> ";
print "Votre adresse postale<p>\n";
print "<select name=\"sexe\">\n";
print "\t<option value=\"F\"> Féminin\n";
print "\t<option value=\"M\"> Masculin\n";
print "</select>\n";
print "<input type=\"submit\" value=\"submit!\">\n</form>\n";
}
?>
</body>
</html>
Listing 12.4 : Rechercher le nombre de lignes renvoyées par une instruction
SELECT avec mysql_num_rows()
1: <html>
2: <head>
3: <title>Listing 12.4 : utiliser mysql_num_rows()</title>
4: </head>
5: <body>
6: <?php
7: $user = "harry";
8: $pass = "elbomonkey";
9: $db = "sample";
$link = mysql_connect( "localhost", $user, $pass );
if ( ! $link )
die( "Impossible de se connecter à MySQL" );
mysql_select_db( $db, $link )
or die ( "Impossible d'ouvrir $db: ".mysql_error() );
$result = mysql_query( "SELECT * FROM domains" );
$num_rows = mysql_num_rows( $result );
print "Il existe $num_rows lignes dans la table<P>";
mysql_close( $link );
?>
</body>
</html>
Listing 12.5 : Affichage de toutes les lignes et les champs d'une table
1: <html>
2: <head>
3: <title>Listing 12.5 : affichage de toutes les lignes et champs d'une
table</title>
4: </head>
5: <body>
6: <?php
7: $user = "harry";
8: $pass = "elbomonkey";
9: $db = "sample";
$link = mysql_connect( "localhost", $user, $pass );
if ( ! $link )
die( "Impossible de se connecter à MySQL" );
mysql_select_db( $db, $link )
or die ( "Impossible d'ouvrir $db: ".mysql_error() );
$result = mysql_query( "SELECT * FROM domains" );
$num_rows = mysql_num_rows( $result );
print "Il existe $num_rows lignes dans la table<P>";
print "<table border=1>\n";
while ( $a_row = mysql_fetch_row( $result ) )
{
print "<tr>\n";
foreach ( $a_row as $field )
print "\t<td>$field</td>\n";
print "</tr>\n";
}
print "</table>\n";
mysql_close( $link );
?>
</body>
</html>
Listing 12.6 : Utiliser mysql_query() pour modifier les lignes d'une base de
données
1: <html>
2: <head>
3: <title>Listing 12.6 : utiliser mysql_query()
4: pour modifier les lignes d'une base de données</title>
5: </head>
6: <body>
7: <?php
8: $user = "harry";
9: $pass = "elbomonkey";
$db = "sample";
$link = mysql_connect( "localhost", $user, $pass );
if ( ! $link )
die( "Impossible de se connecter à MySQL" );
mysql_select_db( $db, $link )
or die ( "Impossible d'ouvrir $db: ".mysql_error() );
if ( isset( $domain ) && isset( $id ) )
{
$query = "UPDATE domains SET domain = '$domain' where id=$id";
$result = mysql_query( $query );
if ( ! $result )
die ("Impossible de mettre à jour : ".mysql_error());
print "<h1>Table mise à jour ". mysql_affected_rows()
.
" row(s) modifiées</h1><p>";
}
?>
<form action="<? print $PHP_SELF ?>" method="POST">
<select name="id">
<?
$result = mysql_query( "SELECT domain, id FROM domains" );
while( $a_row = mysql_fetch_object( $result ) )
{
print "<OPTION VALUE=\"$a_row->id\"";
if ( isset($id) && $id == $a_row->id )
print " SELECTED";
print "> $a_row->domain\n";
}
mysql_close( $link );
?>
</select>
<input type="text" name="domain">
</form>
</body>
</html>
Listing 12.7 : Etablir la liste des bases de données disponibles dans
une connexion
1: <html>
2: <head>
3: <title>Listing 12.7 : établir la liste des bases de données
4: disponibles dans une connexion</title>
5: </head>
6: <body>
7: <?php
8: $user = "harry";
9: $pass = "elbomonkey";
$link = mysql_connect( "localhost", $user, $pass );
if ( ! $link )
die( "Impossible de se connecter à MySQL" );
$db_res = mysql_list_dbs( $link );
$num = mysql_num_rows( $db_res );
for( $x = 0; $x < $num; $x++ )
print mysql_tablename( $db_res, $x )."<br>";
mysql_close( $link );
?>
</body>
</html>
Listing 12.8 : Etablir la liste de chaque base de données, table et
champ
1: <html>
2: <head>
3: <title>Listing 12.8 : établir la liste de chaque base de données,
table et champ</title>
4: </head>
5: <body>
6: <?php
7: $user = "root";
8: $pass = "n1ckel";
9: $db = "sample";
$link = mysql_connect( "localhost", $user, $pass );
if ( ! $link )
die( "Impossible de se connecter à MySQL" );
$db_res = mysql_list_dbs( $link );
while ( $db_rows = mysql_fetch_row( $db_res ) )
{
print "<b>$db_rows[0]</b>\n";
if ( !@mysql_select_db( $db_rows[0], $link ) )
{
print "<dl><dd>impossible de se connecter -- " . mysql_error()
." </dl>";
continue;
}
$tab_res = mysql_list_tables( $db_rows[0], $link );
print "\t<dl><dd>\n";
while ( $tab_rows = mysql_fetch_row( $tab_res ) )
{
print "\t<b>$tab_rows[0]</b>\n";
$query_res = mysql_query( "SELECT * from $tab_rows[0]" );
$num_fields = mysql_num_fields( $query_res );
print "\t\t<dl><dd>\n";
for ( $x=0; $x<$num_fields; $x++ )
{
print "\t\t<i>";
print mysql_field_type( $query_res, $x );
print "</i> <i>";
print mysql_field_len( $query_res, $x );
print "</i> <b>";
print mysql_field_name( $query_res, $x );
print "</b> <i>";
print mysql_field_flags( $query_res, $x );
print "</i><br>\n";
}
print "\t\t</dl>\n";
}
print "\t</dl>\n";
}
mysql_close( $link );
?>
</body>
</html>
Listing 13.1 : Affichage d'une liste de variables d'environnement
1: <html>
2: <head>
3: <title>Listing 13.1 : affichage d'une liste de variables d'environnement</title>
4: </head>
5: <body>
6: <?php
7: $envs = array( "HTTP_REFERER", "HTTP_USER_AGENT", "REMOTE_ADDR",
"REMOTE_HOST", "QUERY_STRING", "PATH_INFO" );
8: foreach ( $envs as $env )
9: {
if ( isset( $$env ) )
print "$env: ${$env}<br>";
}
?>
</body>
</html>
Listing 13.2 : Des en-têtes de client typiques envoyés par Netscape
GET / HTTP/1.0
Referer: http://zink.demon.co.uk:8080/matt/php-book/network/test2.php
Connection: Keep-Alive
User-Agent: Mozilla/4.6 [en] (X11; I; Linux 2.2.6-15apmac ppc)
Host: www.corrosive.co.uk
Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, image/png, */*
Accept-Encoding: gzip
Accept-Language: en
Accept-Charset: iso-8859-1,*,utf-8
Listing 13.3 : Une réponse de serveur
1: HTTP/1.1 200 OK
2: Date: Sun, 30 Jan 2000 18:02:20 GMT
3: Server: Apache/1.3.9 (Unix)
4: Connection: close
5: Content-Type: text/html
6:
7: <html>
8: <head>
9: <title>Listing 13.3 : une réponse de serveur</title>
</head>
<body>
Bonjour
</body>
</html>
Listing 13.4 : Obtenir et afficher une page Web avec fopen()
1: <html>
2: <head>
3: <title>Listing 13.4 : obtenir et afficher une page Web avec fopen()</title>
4: </head>
5: <body>
6: <?php
7: $webpage = "http://www.corrosive.co.uk/php/hello.html";
8: $fp = fopen( $webpage, "r" ) or die("impossible d'ouvrir $webpage");
9: while ( ! feof( $fp ))
print fgets( $fp, 1024 );
?>
</body>
</html>
Listing 13.5 : Utiliser gethostbyaddr() pour obtenir un nom d'hôte
1: <html>
2: <head>
3: <title>Listing 13.5 : utiliser gethostbyaddr()pour obtenir un nom d'hôte</title>
4: </head>
5: <body>
6: <?php
7: if ( isset( $REMOTE_HOST ) )
8: print "Bonjour à $REMOTE_HOST<br>";
9: elseif ( isset ( $REMOTE_ADDR ) )
print "Bonjour à ".gethostbyaddr( $REMOTE_ADDR )."<br>";
else
print "Bonjour à vous, où que vous soyez<br>";
?>
</body>
</html>
Listing 13.6 : Extraire une page Web à l'aide de fsockopen()
1: <html>
2: <head>
3: <title>Listing 13.6 : extraire une page Web à l'aide de fsockopen()</title>
4: </head>
5: <body>
6: <?php
7: $host = "www.corrosive.co.uk";
8: $page = "/index.html";
9: $fp = fsockopen( "$host", 80, &$errno, &$errdesc);
if ( ! $fp )
die ( "Impossible de se connecter à $host:\nError: $errno\nDesc:
$errdesc\n" );
$request = "GET $page HTTP/1.0\r\n";
$request .= "Host: $host\r\n";
$request .= "Referer: http://www.corrosive.co.uk/refpage.html\r\n";
$request .= "User-Agent: PHP test client\r\n\r\n";
$page = array();
fputs ( $fp, $request );
while ( ! feof( $fp ) )
$page[] = fgets( $fp, 1024 );
fclose( $fp );print "le serveur a renvoyé ".(count($page))."
lignes!";
?>
</body>
</html>
Listing 13.7 : Transmettre en sortie les lignes d'état renvoyées
par les serveurs Web
1: <html>
2: <head>
3: <title>Listing 13.7 : transmettre en sortie les lignes d'état
renvoyées par les serveurs Web</title>
4: </head>
5: <body>
6: <?php
7: $to_check = array ( "www.corrosive.co.uk" => "/index.html",
8: "www.virgin.com" => "/notthere.html",
9: "www.4332blah.com" => "/nohost.html"
);
foreach ( $to_check as $host => $page )
{
$fp = fsockopen( "$host", 80, &$errno, &$errdesc, 10);
print "Essayer $host<BR>\n";
if ( ! $fp )
{
print "Impossible de se connecter à $host:\n<br>Erreur: $errno\n<br>Desc:
$errdesc\n";
print "<br><hr><br>\n";
continue;
}
print "Recherche de la page $page<br>\n";
fputs( $fp, "HEAD $page HTTP/1.0\r\n\r\n" );
print fgets( $fp, 1024 );
print "<br><br><br>\n";
fclose( $fp );
}
?>
</body>
</html>
Listing 13.8 : Etablir une connexion NNTP de base à l'aide de fsockopen()
1: <html>
2: <head>
3: <title>Listing 13.8 : établir une connexion NNTP de base à
l'aide de fsockopen()</title>
4: </head>
5: <body>
6: <?php
7: $server = "news"; // remplacez par le nom de votre serveur
8: $group = "alt.test";
9: $line = "";
print "<pre>\n";
print "-- tentative de connexion à $server\n\n";
$fp = fsockopen( "$server", 119, &$error, &$description, 10
);
if ( ! $fp )
die("Impossible de se connecter à $server\n$errno\n$errdesc\n\n");
print "-- Connecté à $server\n\n";
$line = fgets( $fp, 1024 );
$status = explode( " ", $line );
if ( $status[0] != 200 )
{
fputs( $fp, "close" );
die("Erreur: $line\n\n");
}
print "$line\n";
print "-- Sélection de $group\n\n";
fputs( $fp, "group alt.test\n" );
$line = fgets( $fp, 1024 );
$status = explode( " ", $line );
if ( $status[0] != 211 )
{
fputs( $fp, "close" );
die("Erreur: $line\n\n");
}
print "$line\n";
print "-- lecture des en-têtes du premier message\n\n";
fputs( $fp, "head\n" );
$line = fgets( $fp, 1024 );
$status = explode( " ", $line );
print "$line\n";
if ( $status[0] != 221 )
{
fputs( $fp, "close" );
die("Erreur: $line\n\n");
}
while ( ! ( strpos($line, ".") === 0 ) )
{
$line = fgets( $fp, 1024 );
print $line;
}
fputs( $fp, "close\n" );
print "</pre>";
?>
</body>
</html>
Listing 14.1 : Une image créée dynamiquement
<?php
header("Content-type: image/gif");
$image = imagecreate( 200, 200 );
imagegif($image);
?>
Listing 14.2 : Tracer une ligne avec imageline()
<?php
header("Content-type: image/gif");
$image = imagecreate( 200, 200 );
$red = imagecolorallocate($image, 255,0,0);
$blue = imagecolorallocate($image, 0,0,255 );
imageline( $image, 0, 0, 199, 199, $blue );
imagegif($image);
?>
Listing 14.3 : Emploi de imagefill()
1: <?php
2: header("Content-type: image/gif");
3: $image = imagecreate( 200, 200 );
4: $red = imagecolorallocate($image, 255,0,0);
5: $blue = imagecolorallocate($image, 0,0,255 );
6: imageline( $image, 0, 0, 199, 199, $blue );
7: imagefill( $image, 0, 199, $blue );
8: imagegif($image);
9: ?>
Listing 14.4 : Tracer un cercle avec imagearc()
1: <?php
2: header("Content-type: image/gif");
3: $image = imagecreate( 200, 200 );
4: $red = imagecolorallocate($image, 255,0,0);
5: $blue = imagecolorallocate($image, 0,0,255 );
6: imagearc( $image, 99, 99, 180, 180, 0, 360, $blue );
7: imagefill( $image, 99, 99, $blue );
8: imagegif($image);
9: ?>
Listing 14.5 : Tracer un rectangle avec imagefilledrectangle()
<?php
header("Content-type: image/gif");
$image = imagecreate( 200, 200 );
$red = imagecolorallocate($image, 255,0,0);
$blue = imagecolorallocate($image, 0,0,255 );
imagefilledrectangle( $image, 19, 19, 179, 179, $blue );
imagegif( $image );
?>
Listing 14.6 : Dessiner un polygone avec imagefilledpolygon()
1: <?php
2: header("Content-type: image/gif");
3: $image = imagecreate( 200, 200 );
4: $red = imagecolorallocate($image, 255,0,0);
5: $blue = imagecolorallocate($image, 0,0,255 );
6: $points = array ( 10, 10,
7: 190, 190,
8: 190, 10,
9: 10, 190
);
imagefilledpolygon( $image, $points, count( $points )/2 , $blue );
imagegif($image);
?>
Listing 14.7 : Rendre les couleurs transparentes avec imagecolortransparent()
1: <?php
2: header("Content-type: image/gif");
3:
4: $image = imagecreate( 200, 200 );
5: $red = imagecolorallocate($image, 255,0,0);
6: $blue = imagecolorallocate($image, 0,0,255 );
7:
8: $points = array ( 10, 10,
9: 190, 190,
190, 10,
10, 190
);
imagefilledpolygon( $image, $points, count( $points )/2 , $blue );
imagecolortransparent( $image, $red );
imagegif($image);
?>
Listing 14.8 : Ecrire une chaîne avec imageTTFtext()
1: <?php
2: header("Content-type: image/gif");
3:
4: $image = imagecreate( 400, 200 );
5: $red = imagecolorallocate($image, 255,0,0);
6: $blue = imagecolorallocate($image, 0,0,255 );
7: $font = "/usr/local/jdk121_pre-v1/jre/lib/fonts/LucidaSansRegular.ttf";
8:
9: imageTTFtext( $image, 50, 0, 20, 100, $blue, $font, "Bienvenue !"
);
imagegif($image);
?>
Listing 14.9 : Aligner du texte dans un espace fixe à l'aide de imageTTFbox()
1: <?php
2: header("Content-type: image/gif");
3: $height = 100;
4: $width = 200;
5: $fontsize = 50;
6: if ( ! isset ( $text ) )
7: $text = "Changez moi !";
8: $image = imagecreate( $width, $height );
9: $red = imagecolorallocate($image, 255,0,0);
$blue = imagecolorallocate($image, 0,0,255 );
$font = "/usr/local/jdk121_pre-v1/jre/lib/fonts/LucidaSansRegular.ttf";
$textwidth = $width;
$textheight;
while ( 1 )
{
$box = imageTTFbbox( $fontsize, 0, $font, $text );
$textwidth = abs( $box[2] );
$textbodyheight = ( abs($box[7]) )-2;
if ( $textwidth < $width - 20 )
break;
$fontsize[dbhy];
}
$gifXcenter = (int) ( $width/2 );
$gifYcenter = (int) ( $height/2 );
imageTTFtext( $image, $fontsize, 0,
(int) ($gifXcenter-($textwidth/2)),
(int) ($gifYcenter+(($textbodyheight)/2) ),
$blue, $font, $text );
imagegif($image);
?>
Listing 14.10 : Un histogramme dynamique
1: <?php
2: header("Content-type: image/gif");
3: $cells = array ( aime=>200, déteste=>400, indifférent=>900
);
4: $max = max( $cells );
5: $total = count ( $cells );
6: $totalwidth = 300;
7: $totalheight = 200;
8: $xgutter = 20; // marge gauche/droite
9: $ygutter = 20; // marge supérieure/inférieure
$internalgap = 10; // espace entre les cellules
$bottomspace = 30; // intervalle dans le bas (en plus de la marge)
$font = "/usr/local/jdk121_pre-v1/jre/lib/fonts/LucidaSansRegular.ttf";
$graphCanX = ( $totalwidth - $xgutter*2 );
$graphCanY = ( $totalheight - $ygutter*2 - $bottomspace );// emplacement de
début du tracé - axe- x
$posX = $xgutter; // emplacement de début du tracé - axe - y
$posY = $totalheight - $ygutter - $bottomspace;
$cellwidth = (int) (( $graphCanX - ( $internalgap * ( $total-1 ) )) / $total)
;
$textsize = (int)($bottomspace);
// ajustement de la taille de police
while ( list( $key, $val ) = each ( $cells ) )
{
while ( 1 )
{
$box = ImageTTFbBox( $textsize, 0, $font, $key );
$textWidth = abs( $box[2] );
if ( $textWidth < $cellwidth )
break;
$textsize[dbhy];
}
}
$image = imagecreate( $totalwidth, $totalheight );
$red = ImageColorAllocate($image, 255, 0, 0);
$blue = ImageColorAllocate($image, 0, 0, 255 );
$black = ImageColorAllocate($image, 0, 0, 0 );
$grey = ImageColorAllocate($image, 100, 100, 100 );
reset ($cells);
while ( list( $key, $val ) = each ( $cells ) )
{
$cellheight = (int) (($val/$max) * $graphCanY);
$center = (int)($posX+($cellwidth/2));
imagefilledrectangle( $image, $posX, ($posY-$cellheight), ($posX+$cellwidth),
$posY, $blue );
$box = ImageTTFbBox( $textsize, 0, $font, $key );
$tw = $box[2];
ImageTTFText( $image, $textsize, 0, ($center-($tw/2)),
($totalheight-$ygutter), $black, $font, $key );
$posX += ( $cellwidth + $internalgap);
}
imagegif( $image );
?>
Listing 15.1 : Obtenir des informations concernant la date avec getdate()
1: <html>
2: <head>
3: <title>Listing 15.1 : obtenir des informations concernant la date avec
getdate()</title>
4: </head>
5: <body>
6: <?php
7: $date_array = getdate(); // aucun argument n'a été transmis,
la date d'aujourd'hui sera donc utilisée
8: foreach ( $date_array as $key => $val )
9: {
print "$key = $val<br>";
}
?>
<hr>
<?
print "Nous sommes le : $date_array[mday]/$date_array[mon]/$date_array[year]<p>";
?>
</body>
</html>
Listing 15.2 : Mettre une date en forme avec date()
1: <html>
2: <head>
3: <title>Listing 15.2 : mettre une date en forme avec date()</title>
4: </head>
5: <body>
6: <?php
7: print date("d/m/y G.i:s<br>", time());
8: // 20/07/00 13.27:55
9: print "Nous sommes le ";
print date("j F Y, \à g.i a", time());
// Nous sommes le 20 July 2000, à 1.27 pm
?>
</body>
</html>
Listing 15.3 : Création d'un horodateur avec mktime()
1: <html>
2: <head>
3: <title>Listing 15.3 : création d'un horodateur avec mktime()</title>
4: </head>
5: <body>
6: <?php
7: // création d'un horodateur pour le 1/5/99 à 2.30 am
8: $ts = mktime( 2, 30, 0, 5, 1, 1999 );
9: print date("d/m/y G.i:s<br>", $ts);
// 01/05/99 2.30:00
print "Nous sommes le ";
print date("j F Y, \à g.i a", $ts );
// Nous sommes le 1 May 1999, à 2.30 am
?>
</body>
</html>
Listing 15.4 : Contrôle de l'entrée de l'utilisateur pour le script
du calendrier
1: <?php
2: if ( ! checkdate( $month, 1, $year ) )
3: {
4: $nowArray = getdate();
5: $month = $nowArray[mon];
6: $year = $nowArray[year];
7: }
8: $start = mktime ( 0, 0, 0, $month, 1, $year );
9: $firstDayArray = getdate($start);
?>
Listing 15.5 : Création du formulaire HTML pour le script de calendrier
1: <?php
2: if ( ! checkdate( $month, 1, $year ) )
3: {
4: $nowArray = getdate();
5: $month = $nowArray[mon];
6: $year = $nowArray[year];
7: }
8: $start = mktime ( 0, 0, 0, $month, 1, $year );
9: $firstDayArray = getdate($start);
?>
<html>
<head>
<title><?php print "Calendrier : $firstDayArray[month]
$firstDayArray[year]" ?></title>
<head>
<body>
<form method="post">
<select name="month">
<?php
$months = Array("Janvier", "Février", "Mars",
"Avril",
"Mai", "Juin", "Juillet", "Août",
"Septembre",
"Octobre", "Novembre", "Décembre");
for ( $x=1; $x <= count( $months ); $x++ )
{
print "\t<option value=\"$x\"";
print ($x == $month)?" SELECTED":"";
print ">".$months[$x-1]."\n";
}
?>
</select>
<select name="year">
<?php
for ( $x=1980; $x<2010; $x++ )
{
print "\t<option";
print ($x == $year)?" SELECTED":"";
print ">$x\n";
}
?>
</select>
<input type="submit" value="Rechercher">
</form>
</body>
</html>
Listing 15.6 : Le script du calendrier complet
1: <?php
2: define("ADAY", (60*60*24) );
3: if ( ! checkdate( $month, 1, $year ) )
4: {
5: $nowArray = getdate();
6: $month = $nowArray[mon];
7: $year = $nowArray[year];
8: }
9: $start = mktime ( 0, 0, 0, $month, 1, $year );
$firstDayArray = getdate($start);
?>
<html>
<head>
<title><?php print "Calendrier : $firstDayArray[month]
$firstDayArray[year]" ?></title>
<head>
<body>
<form action="<? print $PHP_SELF ?>" method="post">
<select name="month">
<?php
$months = Array("Janvier", "Février", "Mars",
"Avril",
"Mai", "Juin", "Juillet", "Août",
"Septembre",
"Octobre", "Novembre", "Décembre");
for ( $x=1; $x <= count( $months ); $x++ )
{
print "\t<option value=\"$x\"";
print ($x == $month)?" SELECTED":"";
print ">".$months[$x-1]."\n";
}
?>
</select>
<select name="year">
<?php
for ( $x=1980; $x<2010; $x++ )
{
print "\t<option";
print ($x == $year)?" SELECTED":"";
print ">$x\n";
}
?>
</select>
<input type="submit" value="Rechercher">
</form>
<p>
<?php
$days = Array("Dimanche", "Lundi", "Mardi", "Mercredi",
"Jeudi", "Vendredi", "Samedi");
print "<TABLE BORDER = 1 CELLPADDING=5>\n";
foreach ( $days as $day )
print "\t<td><b>$day</b></td>\n";
for ( $count=0; $count < (6*7); $count++ )
{
$dayArray = getdate( $start );
if ( (($count) % 7) == 0 )
{
if ( $dayArray[mon] != $month )
break;
print "</tr><tr>\n";
}
if ( $count < $firstDayArray[wday] || $dayArray[mon] != $month )
{
print "\t<td><br></td>\n";
}
else
{
print "\t<td>$dayArray[mday] $dayArray[month]</td>\n";
$start += ADAY;
}
}
print "</tr></table>";
?>
</body>
</html>
Listing 16.1 : Utilisation de usort() pour trier un tableau multidimensionnel
1: <?php
2: $products = array(
3: array( name=>"HAL 2000", price=>4500,5 ),
4: array( name=>"Tricorde", price=>55,5 ),
5: array( name=>"ORAC AI", price=>2200,5 ),
6: array( name=>"Tournevis sonique", price=>22,5 )
7: );
8: function priceCmp( $a, $b )
9: {
if ( $a[price] == $b[price] )
return 0;
if ( $a[price] < $b[price] )
return -1;
return 1;
}
usort( $products, priceCmp );
foreach ( $products as $val )
print "$val[name]: $val[price]<BR>\n";
?>
Listing 16.2 : Utiliser uasort() pour trier un tableau associatif multidimensionnel
en fonction de l'un de ses champs
1: <?php
2: $products = array(
3: "HAL 2000" => array( color =>"rouge", price=>4500,5
),
4: "Tricorde" => array( color =>"bleu", price=>55,5
),
5: "ORAC AI" => array( color =>"vert", price=>2200,5
),
6: "Tournevis sonique" => array( color =>"rouge",
price=>22,5 )
7: );
8: function priceCmp( $a, $b )
9: {
if ( $a[price] == $b[price] )
return 0;
if ( $a[price] < $b[price] )
return -1;
return 1;
}
uasort( $products, priceCmp );
foreach ( $products as $key => $val )
print "$key: $val[price]<BR>\n";
?>
Listing 16.3 : Utiliser uksort() pour trier un tableau associatif en fonction
de la longueur de ses clés
1: <?php
2: $exes = array(
3: xxxx => 4,
4: xxx => 5,
5: xx => 7,
6: xxxxx => 2,
7: x => 8
8: );
9: function priceCmp( $a, $b )
{
if ( strlen( $a ) == strlen( $b ) )
return 0;
if ( strlen( $a ) < strlen( $b ) )
return -1;
return 1;
}
uksort( $exes, priceCmp );
foreach ( $exes as $key => $val )
print "$key: $val<BR>\n";
// transmet en sortie :
// x: 8
// xx: 7
// xxx: 5
// xxxx: 4
// xxxxx: 2
?>
Listing 17.1 : Illustration de certains spécifieurs de type
1: <html>
2: <head>
3: <title>Illustration de certains spécifieurs de type </title>
4: </head>
5: <body>
6: <?php
7: $number = 543;
8: printf("Décimal: %d<br>", $number );
9: printf("Binaire: %b<br>", $number );
printf("Double: %f<br>", $number );
printf("Octal: %o<br>", $number );
printf("Chaîne: %s<br>", $number );
printf("Hex (minusc.): %x<br>", $number );
printf("Hex (Maj.): %X<br>", $number );
?>
</body>
</html>
Listing 17.2 : Utilisation de printf() pour mettre en forme une liste de prix
de produits
1: <html>
2: <head>
3: <title> Utilisation de printf() pour mettre en forme une liste de prix
de produits </title>
4: </head>
5: <body>
6: <?php
7: $products = Array( "Fauteuil vert"=>"222.4",
8: "Bougeoir"=>"4",
9: "Table basse"=>80.6
);
print "<pre>";
printf("%-20s%23s\n", "Nom", "Prix");
printf("%'-43s\n", "");
foreach ( $products as $key=>$val )
printf( "%-20s%20.2f\n", $key, $val );
printf("</pre>");
?>
</body>
</html>
Listing 17.3 : Découpage d'une chaîne avec strtok()
1: <html>
2: <head>
3: <title>Listing 17.3 : découpage d'une
4: chaîne avec strtok()</title>
5: </head>
6: <body>
7: <?php
8: $test = "http://www.deja.com/qs.xp?[ccc]
9: OP=dnquery.xp&ST=MS&DBS=2&QRY=developer+php";
$delims = "?&";
$word = strtok( $test, $delims );
while ( is_string( $word ) )
{
if ( $word )
print "$word<br>";
$word = strtok( $delims);
}
?>
</body>
</html>
Listing 18.1 : Utilisation de preg_match_all() pour rechercher globalement
un modèle
1: <html>
2: <head>
3: <title>Utilisation de preg_match_all() pour rechercher globalement
un modèle </title>
4: </head>
5: <body>
6: <?php
7: $text = "I sell pots, plants, pistachios, pianos and parrots";
8: if ( preg_match_all( "/\bp\w+s\b/", $text, $array ) )
9: {
for ( $x=0; $x< count( $array ); $x++ )
{
for ( $y=0; $y< count( $array[$x] ); $y++ )
print "\$array[$x][$y]: ".$array[$x][$y]."<BR>\n";
}
}
// affiche:
// $array[0][0]: pots
// $array[0][1]: plants
// $array[0][2]: pistachios
// $array[0][3]: pianos
// $array[0][4]: parrots
?>
</body>
</html>
Listing 19.1 : Définition et affichage d'une valeur de cookie
1: <?php
2: setcookie( "vegetable", "artichoke", time()+3600, "/",
3: "zink.demon.co.uk", 0 );
4: ?>
5: <html>
6: <head>
7: <title>Listing 19.1 : définition et affichage d'une valeur de
cookie </title>
8: </head>
9: <body>
<?php
if ( isset( $vegetable ) )
print "<p>Hello, vous avez choisi $vegetable</p>";
else
print "<p>Hello. C'est peut-être votre première visite</p>";
?>
</body>
</html>
Listing 19.2 : Script ajoutant les informations concernant tout nouvel utilisateur
dans une base de données MySQL
1: <?php
2: $link = mysql_connect( "localhost", "harry", "elbomonkey"
);
3: if ( ! $link )
4: die( "La connexion à mysqld a échoué" );
5: mysql_select_db( "sample", $link ) or die ( mysql_error() );
6: if ( ! isset ( $visit_id ) )
7: $user_stats = newuser( $link );
8: else
9: print "Bienvenue $visit_id<P>";
function newuser( $link )
{
// un nouvel utilisateur!
$visit_data = array (
first_visit => time(),
last_visit => time(),
num_visits => 1,
total_duration => 0,
total_clicks => 1
);
$query = "INSERT INTO track_visit ( first_visit,
last_visit,
num_visits,
total_duration,
total_clicks ) ";
$query .= "values( $visit_data[first_visit],
$visit_data[last_visit],
$visit_data[num_visits],
$visit_data[total_duration],
$visit_data[total_clicks] )";
$result = mysql_query( $query );
$visit_data[id] = mysql_insert_id();
setcookie( "visit_id", $visit_data[id],
time()+(60*60*24*365*10), "/" );
return $visit_data;
}
?>
Listing 19.3 : Script de suivi des utilisateurs basé sur les cookies
et une base de données MySQL
1: <?php
2: $slength = 300; // 5 minutes en secondes
3: $link = mysql_connect( "localhost", "harry", "elbomonkey"
);
4: if ( ! $link )
5: die( "La connexion à mysqld a échoué" );
6: mysql_select_db( "sample", $link ) or die ( mysql_error() );
7: if ( ! isset ( $visit_id ) )
8: $user_stats = newuser( $link );
9: else
{
$user_stats = olduser( $link, $visit_id, $slength );
print "Bienvenue $visit_id<P>";
}
function newuser( $link )
{
// un nouvel utilisateur !
$visit_data = array (
first_visit => time(),
last_visit => time(),
num_visits => 1,
total_duration => 0,
total_clicks => 1
);
$query = "INSERT INTO track_visit ( first_visit,
last_visit,
num_visits,
total_duration,
total_clicks ) ";
$query .= "values( $visit_data[first_visit],
$visit_data[last_visit],
$visit_data[num_visits],
$visit_data[total_duration],
$visit_data[total_clicks] )";
$result = mysql_query( $query );
$visit_data[id] = mysql_insert_id();
setcookie( "visit_id", $visit_data[id],
time()+(60*60*24*365*10), "/" );
return $visit_data;
}
function olduser( $link, $visit_id, $slength )
{
// il/elle est déjà venu(e)!
$query = "SELECT * FROM track_visit WHERE id=$visit_id";
$result = mysql_query( $query );
if ( ! mysql_num_rows( $result ) )
// cookie détecté mais id inconnu--utilisateur considéré
comme nouveau
return newuser( $link );
$visit_data = mysql_fetch_array( $result, $link );
// il y a eu une autre consultation, on incrémente
$visit_data[total_clicks]++;
if ( ( $visit_data[last_visit] + $slength ) > time() )
// toujours en session, on ajoute donc au temps décompté total
$visit_data[total_duration] +=
( time() - $visit_data[last_visit] );
else
// il s'agit d'une nouvelle visite
$visit_data[num_visits]++;
// mise à jour de la base de données
$query = "UPDATE track_visit SET last_visit=".time().",
num_visits=$visit_data[num_visits], ";
$query .= "total_duration=$visit_data[total_duration],
total_clicks=$visit_data[total_clicks] ";
$query .= "WHERE id=$visit_id";
$result = mysql_query( $query );
return $visit_data;
}
?>
Listing 19.4 : Script d'affichage des données statistiques récupérées
avec le Listing 19.3
1: <?php
2: include("listing19.3.php");
3: outputStats();
4: function outputStats()
5: {
6: global $user_stats;
7: $clicks = sprintf( "%.2f",
8: ($user_stats[total_clicks]/$user_stats[num_visits]) );
9: $duration = sprintf( "%.2f",
($user_stats[total_duration]/$user_stats[num_visits]) );
print "<p>Hello! Votre id est $user_stats[id]</p>\n\n";
print "<p>Vous avez consulté
$user_stats[num_visits] fois</p>\n\n";
print "<p>Consultations moy. par visite: $clicks</p>\n\n";
print "<p>Durée moy. D'une visite: $duration secondes</p>\n\n";
}
?>
Listing 19.5 : Fonction de création d'une chaîne de requête
1: <html>
2: <head>
3: <title>Listing 19.5 : fonction de création d'une chaîne
de requête</title>
4: </head>
5: <body>
6: <?php
7: function qlink( $q )
8: {
9: GLOBAL $QUERY_STRING;
if ( ! $q ) return $QUERY_STRING;
$ret = "";
foreach( $q as $key => $val )
{
if ( strlen( $ret ) ) $ret .= "&";
$ret .= urlencode( $key ) . "=" . urlencode( $val );
}
return $ret;
}
$q = array ( name => "Arthur Harold Smith",
interest => "Cinema (mainly art house)",
homepage => "http://www.corrosive.co.uk/harold/"
);
print qlink( $q );
// affiche name=Arthur+Harold+Smith&interest=Cinema+%28mainly+art+house
// %29&homepage=http%3A%2F%2Fwww.corrosive.co.uk%2Fharold%2F
?>
<p>
<a href="anotherpage.php?<? print qlink($q) ?>">Go!</a>
</p>
</body>
</html>
Listing 20.1 : Démarrage ou reprise d'une session
1: <?php
2: session_start();
3: ?>
4: <html>
5: <head>
6: <title>Listing 20.1 : démarrage ou reprise d'une session</title>
7: </head>
8: <body>
9: <?php
print "<p>Bienvenue, votre ID de session est ".session_id()."</p>\n\n";
?>
</body>
</html>
Listing 20.2 : Enregistrement de variables avec une session
1: <?php
2: session_start();
3: ?>
4: <html>
5: <head>
6: <title>Listing 20.2 : enregistrement de variables avec une session</title>
7: </head>
8: <body>
9: <?php
session_register( "product1" );
session_register( "product2" );
$product1 = "Sonic Screwdriver";
$product2 = "HAL 2000";
print session_encode();
print "Les produits ont été enregistrés";
?>
</body>
</html>
Listing 20.3 : Accéder aux variables enregistrées
1: <?php
2: session_start();
3: ?>
4: <html>
5: <head>
6: <title>Listing 20.3 : accéder aux variables enregistrées</title>
7: </head>
8: <body>
9: <?php
print "Vous aviez choisi les produits:\n\n";
print "<ul><li>$product1\n<li>$product2\n</ul>\n";
?>
</body>
</html>
Listing 20.4 : Enregistrement d'une variable tableau avec une session
1: <?php
2: session_start();
3: ?>
4: <html>
5: <head>
6: <title>Listing 20.4 : enregistrement d'une variable tableau avec une
session</title>
7: </head>
8: <body>
9: <h1>Page de sélection des produits</h1>
<?php
if ( isset( $form_products ) )
{
$products = $form_products;
session_register( "products" );
print "<p>Vos produits ont été enregistrés !</p>";
}
?><p>
<form method="POST">
<select name="form_products[]" multiple size=3>
<option> Sonic Screwdriver
<option> Hal 2000
<option> Tardis
<option> ORAC
<option> Transporter bracelet
</select>
</p><p>
<input type="submit" value="Sélectionner">
</form>
</p>
<a href="listing20.5.php">Une page de données</a>
</body>
</html>
Listing 20.5 : Accès aux variables de session
1: <?php
2: session_start();
3: print session_encode();
4: ?>
5: <html>
6: <head>
7: <title>Listing 20.5 : accès aux variables de session</title>
8: </head>
9: <body>
<h1>Une page d'informations</h1>
<?php
if ( isset( $products ) )
{
print "<b>Votre carte:</b><ol>\n";
foreach ( $products as $p )
print "<li>$p";
print "</ol>";
}
?>
<a href="listing20.4.php">Retour vers la page de sélection
des produits</a>
</body>
</html>
Listing 21.1 : Utiliser popen() pour lire la sortie de la commande UNIX who
1: <html>
2: <head>
3: <title>Listing 21.1 : Utiliser popen() pour lire la sortie de la
4: commande UNIX who </title>
5: </head>
6: <body>
7: <h2>Administrateurs actuellement connectés au serveur</h1>
8: <?php
9: $ph = popen( "who", "r" )
or die( "Impossible d'ouvrir une connexion vers la commande 'who'"
);
$host="zink.demon.co.uk";
while ( ! feof( $ph ) )
{
$line = fgets( $ph, 1024 );
if ( strlen( $line ) <= 1 )
continue;
$line = ereg_replace( "^([a-zA-Z0-9_\-]+).*",
"<a href=\"mailto:\\1@$host\">\\1</a><BR>\n",
$line );
print "$line";
}
pclose( $ph );
?>
</table>
</body>
</html>
Listing 21.2 : Utilisation de popen() pour transmettre des données à
l'application column
1: <html>
2: <head>
3: <title>Listing 21.2 : utilisation de popen() pour transmettre
4: des données à la commande column</title>
5: </head>
6: <body>
7: <?php
8: $products = array(
9: array( "HAL 2000", 2, "red" ),
array( "Tricorder", 3, "blue" ),
array( "ORAC AI", 1, "pink" ),
array( "Sonic Screwdriver", 1, "orange" )
);
$ph = popen( "column -tc 3 -s / > purchases/user3.txt", "w"
)
or die( "Impossible d'établir une connexion avec 'column'"
);
foreach ( $products as $prod )
fputs( $ph, join('/', $prod)."\n");
pclose( $ph );
?>
</table>
</body>
</html>
Listing 21.3 : Utilisation d'exec() pour afficher le contenu d'un répertoire
1: <html>
2: <head>
3: <title>Listing 21.3 : utilisation d'exec() pour afficher le contenu
4: d'un répertoire</title>
5: </head>
6: <body>
7: <?php
8: exec( "ls -al .", $output, $return );
9: print "<p>Valeur renvoyée: $return</p>";
foreach ( $output as $file )
print "$file<br>";
?>
</table>
</body>
</html>
Listing 21.4 : Appel de la commande man
1: <html>
2: <head>
3: <title>Listing 21.4 : appel de la commande man.
4: ce script comporte un problème de sécurité</title>
5: </head>
6: <body>
7: <form>
8: <input type="text" value="<?php print $manpage; ?>"
name="manpage">
9: </form>
<pre>
<?php
if ( isset($manpage) )
system( "man $manpage | col -b" );
?>
</pre>
</table>
</body>
</html>
Listing 21.5 : Codage de l'entrée utilisateur avec escapeshellcmd()
1: <html>
2: <head>
3: <title>Listing 21.5 : codage de l'entrée utilisateur avec
4: escapeshellcmd()</title>
5: </head>
6: <body>
7: <form>
8: <input type="text" value="<?php print $manpage; ?>"
name="manpage">
9: </form>
<pre>
<?php
if ( isset($manpage) )
{
$manpage = escapeshellcmd( $manpage );
system( "man $manpage | col -b" );
}
?>
</pre>
</table>
</body>
</html>
Listing 21.6 : Utilisation de passthru() pour transmettre des données
binaires en sortie
1: <?php
2: if ( isset($image) && file_exists( $image ) )
3: {
4: header( "Content-type: image/gif" );
5: passthru( "giftopnm $image | pnmscale -xscale .5 -yscale .5 | ppmtogif"
);
6: }
7: else
8: print "Impossible de trouver l'image $image";
9: ?>
Listing 22.1 : Script de test de phpinfo()
1: <?php
2: setcookie("id", "2344353463433", time()+3600, "/"
);
3: ?>
4: <html>
5: <head>
6: <title>Listing 22.1 : script de test de phpinfo()</title>
7: </head>
8: <body>
9: <form action="<?php print "$PHP_SELF" ?>" METHOD="get">
<input type="text" name="user">
<br>
<select name="products[]" multiple>
<option>Pommes de terre
<option>Fromage
<option>Pain
<option>Poulet
</select>
<br>
<input type="submit" value="test!">
</form>
<p></p>
<hr>
<p></p>
<?php
phpinfo();
?>
</body>
</html>
Listing 22.2 : Afficher le code source du document
1: <html>
2: <head>
3: <title>Listing 22.2 : afficher le code source du document </title>
4: </head>
5: <body>
6: <form action="<?php print $PHP_SELF ?>" method="get">
7: Saisissez le nom du fichier:
8: <input type="text" name="file" value="<?php
print $file; ?>">
9: <p></p><hr><p></p>
<?php
if ( isset( $file ) )
show_source( $file ) or print "Impossible d'ouvrir \"$file\"";
?>
</body>
</html>
Listing 22.3 : Une erreur délibérée
<?php
error_reporting( E_ERROR|E_WARNING|E_PARSE );
$flag = 45;
if ( $flg == 45 )
print "Je sais que \$flag est 45";
else
print "Je sais que \$flag n'est pas 45";
?>
Listing 22.4 : Une fonction de présentation des messages de débogage
1: <?php
2: function debug( $line, $msg )
3: {
4: static $calls = 1;
5: print "<P><HR>\n";
6: print "DEBUG $calls: Ligne $line: $msg<br>";
7: $args = func_get_args();
8: if ( count( $args ) % 2 )
9: print "Nombre d'args impair<BR>";
else
{
for ( $x=2; $x< count($args); $x += 2 )
{
print "  \$$args[$x]: ".$args[$x+1];
print " .... (".gettype( $args[$x+1] ).")<BR>\n";
}
}
print "<hr><p></p>\n";
$calls++;
}
$test = 55;
debug( __LINE__, "Premier message", "test", $test );
$test = 66;
$test2 = $test/2;
debug( __LINE__, "Deuxième message", "test", $test,
"test2", $test2 );
?>
Listing 23.1 : Un extrait de dblib.inc
1: $link;
2: connectToDB();
3: function connectToDB()
4: {
5: global $link;
6: $link = mysql_connect( "localhost", "harry", "elbomonkey"
);
7: if ( ! $link )
8: die( "Impossible d'établir une connexion avec MySQL" );
9: mysql_select_db( "organizer", $link )
or die ( "Impossible d'ouvrir organizer: ".mysql_error() );
}
Listing 23.2 : Un extrait de clublib.inc
session_start();
session_register( "session" );
Listing 23.3 : join.php
1: <?php
2: include("dblib.inc");
3: include("clublib.inc");
4: $message="";
5: if ( isset( $actionflag ) && $actionflag=="join")
6: {
7: if ( empty( $form[login] ) ||
8: empty( $form[password] ) ||
9: empty( $form[password] ) )
$message .= "Vous devez remplir tous les champs<BR>\n";
if ( $form[password] != $form[password2] )
$message .= "Vos mots de passe ne concordent pas<BR>\n";
if ( strlen( $form[password] ) > 8 )
$message .= " Votre mot de passe doit comporter
moins de 8 caractères <BR>\n";
if ( strlen( $form[login] ) > 8 )
$message .= "Votre nom de connexion doit comporter
moins de 8 caractères<BR>\n";
if ( getRow( "clubs", "login", $form[login] ) )
$message .= "Le nom de connexion \"$form[login]\" existe déjà.
Choisissez-en un autre<BR>\n";
if ( $message == "" ) // aucune erreur détectée
{
$id = newUser( $form[login], $form[password] );
cleanMemberSession( $id, $form[login], $form[password] );
header( "Location: updateclub.php?".SID );
exit;
}
}
?>
<html>
<head>
<title>Enregistrez-vous !</title>
</head>
<body>
<?php
include("publicnav.inc");
?>
<p>
<h1>Enregistrement</h1>
<?php
if ( $message != "" )
{
print "<b>$message</b><p>";
}
?>
<p>
<form action="<?php print $PHP_SELF;?>">
<input type="hidden" name="actionflag" value="join">
<input type="hidden" name="<?php print session_name() ?>"
value="<?php print session_id() ?>">
Nom de connexion: <br>
<input type="text" name="form[login]"
value="<?php print $form[login] ?>" maxlength=8>
</p>
<p>
Mot de passe: <br>
<input type="password" name="form[password]" value=""
maxlength=8>
</p>
<p>
Confirmez le mot de passe: <br>
<input type="password" name="form[password2]" value=""
maxlength=8>
</p>
<p>
<input type="submit" value="Mettre à jour">
</p>
</form>
</body>
</html>
Listing 23.4 : Un extrait de publicnav.inc
<a href="viewclubs.php?<?php print SID ?>">Parcourir les
clubs</a> |
<a href="viewevents.php?<?php print SID ?>">Afficher les
événements</a> |
<a href="join.php?<?php print SID ?>">S'enregistrer</a>
|
<a href="login.php?<?php print SID ?>">Se connecter</a>
|
<a href="index.php?<?php print SID ?>">Accueil</a>
Listing 23.5 : Un extrait de dblib.inc
function getRow( $table, $fnm, $fval )
{
global $link;
$result = mysql_query( "SELECT * FROM $table WHERE $fnm='$fval'",
$link );
if ( ! $result )
die ( "Erreur fatale avec getRow: ".mysql_error() );
return mysql_fetch_array( $result );
}
Listing 23.6 : Un extrait de dblib.inc
function newUser( $login, $pass )
{
global $link;
$result = mysql_query( "INSERT INTO clubs (login, password)
VALUES('$login', '$pass')", $link);
return mysql_insert_id( $link );
}
Listing 23.7 : Un extrait de clublib.inc
function cleanMemberSession( $id, $login, $pass )
{
global $session;
$session[id] = $id;
$session[login] = $login;
$session[password] = $pass;
$session[logged_in] = true;
}
Listing 23.8 : updateclub.php
1: <?php
2: include("dblib.inc");
3: include("clublib.inc");
4: $club_row = checkUser();
5: $message = "";
6: if ( isset( $actionflag ) && $actionflag=="update" )
7: {
8: if ( empty( $form[name] ) )
9: $message .="Vous devez nommer votre club<br>\n";
if ( ! getRow( "areas", "id", $form[area] ) )
$message .= "PANIC: aucun lieu correspondant à ce code<br>";
if ( ! getRow( "types", "id", $form[type] ) )
$message .= "PANIC: aucun type correspondant à ce code<BR>";
if ( $message == "" )
{
updateOrg( $session[id], $form[name], $form[area],
$form[type],