PHP tutorial - basics: Difference between revisions

The educational technology and digital learning wiki
Jump to navigation Jump to search
Line 74: Line 74:
PHP code is defined within an XML processing instruction
PHP code is defined within an XML processing instruction


<tt>'''<nowiki><?php ..... ?></nowiki>'''</tt>
<tt>'''<nowiki><?php ..... ?>'''</tt>


<source lang="php">
<source lang="php">
Line 109: Line 109:
: [http://tecfa.unige.ch/guides/php/examples/includes/ http://tecfa.unige.ch/guides/php/examples/includes/]
: [http://tecfa.unige.ch/guides/php/examples/includes/ http://tecfa.unige.ch/guides/php/examples/includes/]


<source lang="xml">
<source lang="php">
  <HTML>
  <HTML>
   <HEAD>
   <HEAD>
Line 148: Line 148:
[[image:programming-elements.png|frame|none|Programming elements]]
[[image:programming-elements.png|frame|none|Programming elements]]


: '''PHP syntax'''
'''PHP syntax overview''':
: PHP looks like "C" (C, C++, Java, Perl, etc.)
 
PHP looks like "C" (C, C++, Java, Perl, etc.)
: Each instruction is ended with a ";"
: Each instruction is ended with a ";"
: Comments // or #, or included within /* ... */
: Comments // or #, or included within /* ... */
: '''Variables and assignments'''
: Variables are “containers” for information.
: Each identifier with a $ in front is a variable
: Variables don’t need to be declared
: Assignment operator: =
: '''Simple variables'''
:  assignment


$variable = "content" ;
=== Variables and assignments ===


Illustrations:
Variables are “containers” for information.
* Each identifier with a $ in front is a variable
* Variables don’t need to be declared
* Assignment operator: =


    $a = 10;
Principle:
    $name = "Patrick Ott";
    $sum = 123.456;


: '''Display variable contents'''
$variable = "content" ;
: Files:
 
 
{| class="prettytable"
| <center>Application</center>
| : [http://tecfa.unige.ch/guides/php/examples/simple/simple-echo.php /guides/php/examples/simple/simple-echo.php]


Illustrations:


  $a = 10;
  $name = "Patrick Ott";
  $sum = 123.456;


|-
'''Using variables with content strings example''':
| <center>Source (to see)</center>
: [http://tecfa.unige.ch/guides/php/examples/simple/simple-echo.php /guides/php/examples/simple/simple-echo.php] (application)
| : [http://tecfa.unige.ch/guides/php/examples/simple/simple-echo.phps /guides/php/examples/simple/simple-echo.phps]
: [http://tecfa.unige.ch/guides/php/examples/simple/simple-echo.phps /guides/php/examples/simple/simple-echo.phps] (pretty source)
 
: [http://tecfa.unige.ch/guides/php/examples/simple/simple-echo.text /guides/php/examples/simple/simple-echo.text] (source)
 
 
|-
| <center>Source (to copy</center>
| : [http://tecfa.unige.ch/guides/php/examples/simple/simple-echo.text /guides/php/examples/simple/simple-echo.text]
 
 
 
|}
:  
:  
<source lang="php">
<BODY>
  <H1>Simple Echo of variables with PHP</H1>


  <nowiki><BODY></nowiki>
  <?php
  <nowiki><H1>Simple Echo of variables with PHP</H1></nowiki>
 
<nowiki><?php</nowiki>
 
   $a = 10;
   $a = 10;
   $nom = "Patrick Ott";
   $nom = "Patrick Ott";
   $somme = 123.456;
   $somme = 123.456;
  echo "Le nommé $nom a $somme francs dans la poche, mais il voudrait $a fois plus.";
echo "Le nommé $nom a $somme francs dans la poche, mais il voudrait $a fois plus.";
  ?>
  ?>
   
   
  <nowiki><p><hr></nowiki>
  <p><hr>
  <nowiki></BODY></nowiki>
  </BODY>
</source>


: echo an “instruction” to display a string (chain of characters)
: echo is an “instruction” to display a string (chain of characters)
: Note: all the $xxx are replaced by their contents !
: Note: all the $xxx are replaced by their contents !
: '''Simple arrays'''
: Arrays are a sort of list (several values within the same variable)


Method 1:
=== Simple arrays ===
 
: Arrays are a sort of lists (several values within the same variable)
 
Array creation - method 1:


  <nowiki>$numbers[] =1;</nowiki>
  $numbers[] =1;
  <nowiki>$numbers[] =2;</nowiki>
  $numbers[] =2;
  <nowiki>$numbers[] =3;</nowiki>
  $numbers[] =3;
  <nowiki>$numbers[] =4;</nowiki>
  $numbers[] =4;


Method 2:
Array creation - method 2:


  $numbers = array (1, 2, 3, 4);
  $numbers = array (1, 2, 3, 4);
  $names = array ("Pat", "Dave", "Surf", "K");
  $names = array ("Pat", "Dave", "Surf", "K");


'''''Simple arrays usage'''''
Use of simple arrays:
$array[index]


  <nowiki>$array[index]</nowiki>
Index starts at 0 ! (zero). Example:
  echo "Second element of $names is: $names[1];


: Index starts at 0 ! (zero)
'''Example: Simple variables and some HTML generation'''


<nowiki>echo "Second element of $names is: $names[1];</nowiki>
: [http://tecfa.unige.ch/guides/php/examples/simple/simple-arrays.php /guides/php/examples/simple/simple-arrays.php]


: '''Simple variables and some HTML generation'''
<source lang="php">
: '''See: [http://tecfa.unige.ch/guides/php/examples/simple/simple-arrays.php /guides/php/examples/simple/simple-arrays.php] '''
<?php
 
<nowiki><?php</nowiki>
   
   
  // Some simple HTML
  // Some simple HTML
  <nowiki>echo"<h1>Simple arrays</h1>";</nowiki>
  echo"<h1>Simple arrays</h1>";
   
   
  $utilisateur = "cher étudiant";
  $utilisateur = "cher étudiant";
Line 246: Line 231:
  $numbers = array (1, 2, 3, 4);
  $numbers = array (1, 2, 3, 4);
  $names = array ("Pat", "Dave", "Surf", "K");
  $names = array ("Pat", "Dave", "Surf", "K");
  <nowiki>$names[] = "Zorro";</nowiki>
  $names[] = "Zorro";
   
   
  <nowiki>// Note html <br> tag</nowiki>
  // Note html <br> tag
  <nowiki>echo "Salut $utilisateur. Vous êtes le numéro $no_utilisateur.<br>";</nowiki>
  echo "Salut $utilisateur. Vous êtes le numéro $no_utilisateur.<br>";
   
   
  // echo with concatenation, use it to print complex things
  // echo with concatenation, use it to print complex things
  <nowiki>echo "La quatrième personne s’appelle " . $names[3] ." ";</nowiki>
  echo "La quatrième personne s’appelle " . $names[3] ." ";
   
   
  // simple echo
  // simple echo
  <nowiki>echo "et la cinquième personne s’appelle $names[4].<p>";</nowiki>
  echo "et la cinquième personne s’appelle $names[4].<p>";
  $n = sizeof($numbers);
  $n = sizeof($numbers);
   
   
Line 261: Line 246:
  echo "We have $n numbers in array \$numbers.";
  echo "We have $n numbers in array \$numbers.";
  ?>
  ?>
</source>


: '''Associative arrays and multi-dimensional tables'''
=== Associative arrays and multi-dimensional tables ===


<source lang="php">
  $fruits = array(
  $fruits = array(
     "fruits"  <nowiki>=> array("a"=>"orange","b"=>"banana","c"=>"apple"),</nowiki>
     "fruits"  => array("a"=>"orange","b"=>"banana","c"=>"apple"),
     "numbers" => array(1, 2, 3, 4, 5, 6)
     "numbers" => array(1, 2, 3, 4, 5, 6)
     "holes"  <nowiki>=> array("first", 5 => "second", "third")</nowiki>
     "holes"  => array("first", 5 => "second", "third")
  );
  );
</source>


: '''Summary - variables'''
: '''Summary - variables'''
: You should, but don’t need to initialize varibales
: You should, but don’t need to initialize varibales
 
<source lang="php">
  $a = 1234; # decimal number
  $a = 1234; # decimal number
  $a = -123; # a negative number
  $a = -123; # a negative number
  $a = 1.234; $a = 1.2e3; # floating point number
  $a = 1.234; $a = 1.2e3; # floating point number
  $str = "This is a string"; # string
  $str = "This is a string"; # string
  <nowiki>$a[0] = "abc"; # element zero of un array</nowiki>
  $a[0] = "abc"; # element zero of un array
  <nowiki>$a[1] = "def"; # element 1 of an array</nowiki>
  $a[1] = "def"; # element 1 of an array
  <nowiki>$b["foo"] = 13; # element "foo" of an array</nowiki>
  $b["foo"] = 13; # element "foo" of an array
</source>


: '''Constants.'''
: '''Constants.'''
Line 286: Line 275:
: By convention, use capital letters.
: By convention, use capital letters.
: '''Definition'''
: '''Definition'''
<nowiki>define(<NAME>, <value>);</nowiki>
:  define(<NAME>, <value>);


<source lang="php">
  define("PI", 3.14);
  define("PI", 3.14);
  <nowiki>define("REMERCIEMENTS", "Thanx for using our program<br>");</nowiki>
  define("REMERCIEMENTS", "Thanx for using our program<br>");
  define("SALUTATIONS", "Je vous prie d’agréer, Madame, Monsieur, l’expression de nos sentiments dévoués");
  define("SALUTATIONS", "Je vous prie d’agréer, Madame, Monsieur, l’expression de nos sentiments dévoués");
  $radius = 12;
  $radius = 12;
  $perimeter = 2 * $radius * PI;
  $perimeter = 2 * $radius * PI;
  echo REMERCIEMENTS;
  echo REMERCIEMENTS;
  <nowiki>echo "le périmètre du cercle is de " . $perimeter . "<br>";</nowiki>
  echo "le périmètre du cercle is de " . $perimeter . "<br>";
  echo SALUTATIONS;
  echo SALUTATIONS;
</source>


'''''result:'''''
'''''result:'''''
Line 364: Line 355:
:  
:  


<source lang="php">
  $leisure_satisfaction = 5;
  $leisure_satisfaction = 5;
  $work_satisfaction = 7;
  $work_satisfaction = 7;
Line 369: Line 361:
  $index = ($leisure_satisfaction + $work_satisfaction + $family_satisfaction)
  $index = ($leisure_satisfaction + $work_satisfaction + $family_satisfaction)
           / 3 ;
           / 3 ;
  <nowiki>echo "<p align=center> Satisfaction Index = $index <b>";</nowiki>
  echo "<p align=center> Satisfaction Index = $index <b>";
</source>


assignment + addition in one step:
assignment + addition in one step:


<source lang="php">
  // sets $a to 8, as if we had said: $a = $a + 5;
  // sets $a to 8, as if we had said: $a = $a + 5;
  $a += 5;  
  $a += 5;  
</source>


: '''Operators for strings'''
: '''Operators for strings'''
Line 384: Line 379:
example:
example:


<source lang="php">
  $a = "Hello ";
  $a = "Hello ";
  $b = $a . "World!"; // now $b = "Hello World!"
  $b = $a . "World!"; // now $b = "Hello World!"
</source>


: Note: There are dozens of string manipulation functions in PHP !!
: Note: There are dozens of string manipulation functions in PHP !!
Line 391: Line 388:
assignment + concatenation in one step
assignment + concatenation in one step


<source lang="php">
  $b = "Hello ";
  $b = "Hello ";
   // sets $b to "Hello There!", just like $b = $b . "There!";
   // sets $b to "Hello There!", just like $b = $b . "There!";
  $b .= "There!";
  $b .= "There!";
</source>


: '''Logical operators'''
: '''Logical operators'''
Line 463: Line 462:


|-
|-
| <center><nowiki>$a < $b</nowiki></center>
| <center>$a < $b</center>
| <center>inferior</center>
| <center>inferior</center>
| <center>True if $a is strictly less than $b.</center>
| <center>True if $a is strictly less than $b.</center>
Line 473: Line 472:


|-
|-
| <center><nowiki>$a <= $b</nowiki></center>
| <center>$a <= $b</center>
| <center>inferior or equal</center>
| <center>inferior or equal</center>
| <center>True if $a is less than or equal to $b.</center>
| <center>True if $a is less than or equal to $b.</center>
Line 490: Line 489:
: Note: in PHP each number equal or small than 0 is FALSE, each superior is TRUE
: Note: in PHP each number equal or small than 0 is FALSE, each superior is TRUE


<source lang="php">
  $a = "Migros";
  $a = "Migros";
  $b = "Coop";
  $b = "Coop";
Line 496: Line 496:
  $result3 = $result==TRUE;
  $result3 = $result==TRUE;
  echo "Result One = $result. Result TWO = $result2. Result THREE = $result3.";
  echo "Result One = $result. Result TWO = $result2. Result THREE = $result3.";
</source>


: '''Selection (Conditions and tests)'''
: '''Selection (Conditions and tests)'''
Line 510: Line 511:
:  '''if''' (expr) ''statements'' '''else''' ''statements''
:  '''if''' (expr) ''statements'' '''else''' ''statements''
:  '''if''' (''expr'') ''statements'' '''elseif''' (''expr'') ''statements'' else ...
:  '''if''' (''expr'') ''statements'' '''elseif''' (''expr'') ''statements'' else ...
:  '''if''' (expr) statements '''elseif'''<nowiki> (expr) statements [ </nowiki>'''elseif '''(expr) ... ]
:  '''if''' (expr) statements '''elseif''' (expr) statements [ '''elseif '''(expr) ... ]
: <tt>''expr''</tt> = Expression must return TRUE or FALSE
: <tt>''expr''</tt> = Expression must return TRUE or FALSE
: <tt>''statements ''</tt><nowiki>= simple instructions or a block or instructions</nowiki>
: <tt>''statements ''</tt>= simple instructions or a block or instructions
: simple: $a = 10;
: simple: $a = 10;
: block: { $a =12; echo "salut"; ..... }
: block: { $a =12; echo "salut"; ..... }
Line 527: Line 528:
<center>[[Image:]]</center>
<center>[[Image:]]</center>


 
<source lang="php">
  <nowiki><?php</nowiki>
  <?php
   
   
  $a = 10; $b = 11;
  $a = 10; $b = 11;
Line 541: Line 542:
   
   
  ?>
  ?>
</source>
   
   


Line 562: Line 564:
: [http://tecfa.unige.ch/guides/php/examples/simple/ http://tecfa.unige.ch/guides/php/examples/simple/] (files color-mix.*)'''
: [http://tecfa.unige.ch/guides/php/examples/simple/ http://tecfa.unige.ch/guides/php/examples/simple/] (files color-mix.*)'''


<source lang="php">
  function color_mix($color1,$color2) {
  function color_mix($color1,$color2) {
   $result= "unknown";
   $result= "unknown";
Line 584: Line 587:
  // Print
  // Print


  echo "Bleu  <nowiki>et rouge donne $situation1 <br>";</nowiki>
  echo "Bleu  et rouge donne $situation1 <br>";
  echo "Jaune et bleu  donne $situation2";
  echo "Jaune et bleu  donne $situation2";
</source>


: '''HTML generation with functions'''
: '''HTML generation with functions'''
Line 591: Line 595:
: [http://tecfa.unige.ch/guides/php/examples/simple/function-demo.phps /guides/php/examples/simple/function-demo.phps]
: [http://tecfa.unige.ch/guides/php/examples/simple/function-demo.phps /guides/php/examples/simple/function-demo.phps]


<nowiki><?php</nowiki>
<source lang="php">
<?php
   
   
  // html formats a data element
  // html formats a data element
  '''function pretty_print''' ($output) {
  '''function pretty_print''' ($output) {
     separator ();
     separator ();
     <nowiki>echo "<p align='center'> <strong>ELEMENT:</strong> $output </p>";</nowiki>
     echo "<p align='center'> <strong>ELEMENT:</strong> $output </p>";
  }
  }
  // outputs a separator
  // outputs a separator
  '''function separator ()''' {
  '''function separator ()''' {
     <nowiki>echo "<hr size=4 width=70%>";</nowiki>
     echo "<hr size=4 width=70%>";
  }
  }
  // data we have
  // data we have
Line 612: Line 617:
   
   
  '''separator''' ();
  '''separator''' ();
  <nowiki>echo "<hr>";</nowiki>
  echo "<hr>";
  ?>
  ?>
</source>


: '''Loops (iterations)'''
: '''Loops (iterations)'''


'''The "for loop" syntax'''
'''The "for loop" syntax'''
 
<source lang="php">
  FOR (expr1; expr2; expr3) statement
  FOR (expr1; expr2; expr3) statement
</source>


: expr1 is evaluated at start
: expr1 is evaluated at start
Line 629: Line 636:
: '''see: [http://tecfa.unige.ch/guides/php/examples/html-generate/love.phps /guides/php/examples/html-generate/love.phps]
: '''see: [http://tecfa.unige.ch/guides/php/examples/html-generate/love.phps /guides/php/examples/html-generate/love.phps]


<nowiki>for ($i=1; $i<=10; $i++) {</nowiki>
<source lang="php">
for ($i=1; $i<=10; $i++) {
     print "I love you so ! "; }
     print "I love you so ! "; }
</source>


result:love you so ! I love you so ! I love you so ! I love you so ! I love you so ! I love you so ! ......
result:love you so ! I love you so ! I love you so ! I love you so ! I love you so ! I love you so ! ......


<nowiki>echo "Je t’aime plus que toi.<br></nowiki>
<source lang="php">
  <nowiki>for ($i=2; $i<=10; $i++) {</nowiki>
echo "Je t’aime plus que toi.<br>
  for ($i=2; $i<=10; $i++) {
     echo "Non, je t’aime $i fois plus que  toi ! ";
     echo "Non, je t’aime $i fois plus que  toi ! ";
  }
  }
</source>


'''result:'''
'''result:'''
Line 654: Line 665:
: '''see: [http://tecfa.unige.ch/guides/php/examples/html-generate/love.text /guides/php/examples/html-generate/love.text]
: '''see: [http://tecfa.unige.ch/guides/php/examples/html-generate/love.text /guides/php/examples/html-generate/love.text]


<source lang="php">
  '''$love_list''' = array ("a lot", "a bit", "somewhat", "à mourir", "forever", "until notice", "more than I love my dog");
  '''$love_list''' = array ("a lot", "a bit", "somewhat", "à mourir", "forever", "until notice", "more than I love my dog");
  <nowiki><table border align="center"></nowiki>
  <table border align="center">
  <nowiki><?</nowiki>
  <?
  // define a function to generate a table
  // define a function to generate a table
  function build_table($list) {
  function build_table($list) {
   '''<nowiki>for ($i=0; $i < sizeof($list); $i++) {</nowiki>
   '''for ($i=0; $i < sizeof($list); $i++) {
     <nowiki>$love_text = $list[$i];</nowiki>
     $love_text = $list[$i];
     <nowiki>echo "<tr> <td> ... I love you</td> <td>$love_text</td>";</nowiki>
     echo "<tr> <td> ... I love you</td> <td>$love_text</td>";
     }
     }
  }
  }
Line 667: Line 679:
  build_table($love_list);
  build_table($love_list);
  ?>'''
  ?>'''
  <nowiki></table></nowiki>
  </table>
</source>


Note:
Note:


: <nowiki>PHP is used with the HTML <table> element</nowiki>
: PHP is used with the HTML <table> element
: The <tt>'''build_table'''</tt> function is called with an array
: The <tt>'''build_table'''</tt> function is called with an array
: There exist more looping constructs in PHP (like while or for-each) !
: There exist more looping constructs in PHP (like while or for-each) !
Line 679: Line 692:
: Insert this in you PHP file (will give you lots of information !)
: Insert this in you PHP file (will give you lots of information !)


<source lang="php">
  phpinfo();
  phpinfo();
</source>


: Insert print statements!
: Insert print statements!


<source lang="php">
  echo "DEBUG: \$var = $var";
  echo "DEBUG: \$var = $var";
  echo "TEST: var = $var";
  echo "TEST: var = $var";
</source>


: Raise "error reporting" to its maximum !!!
: Raise "error reporting" to its maximum !!!
Line 690: Line 707:
Insert this on top:
Insert this on top:


<source lang="php">
  error_reporting(E_ALL);
  error_reporting(E_ALL);
</source>


: '''Portals'''
: '''Portals'''
: Warning: NEVER insert blank lines at start or end of a file !!
: Warning: NEVER insert blank lines at start or end of a file !!
: Most files should stop like this (no line feed !!) ?>
: Most files should stop like this (no line feed !!) ?>
: <nowiki>... because PHP starts producing HMTL headers as soon as it sees a little blank space before or after php code <?php .... ?></nowiki>
: ... because PHP starts producing HMTL headers as soon as it sees a little blank space before or after php code <?php .... ?>
: '''HTML forms processing with PHP'''
: '''HTML forms processing with PHP'''
: '''Forms processing with PHP I (Calcul)'''
: '''Forms processing with PHP I (Calcul)'''
Line 710: Line 729:
'''Part of the HTML form:'''
'''Part of the HTML form:'''


<nowiki><form </nowiki>'''''action="calcul.php"''''' method="post">
<source lang="htmlstrict">
<form '''''action="calcul.php"''''' method="post">
   
   
  Quelles sont vos connaissances de HTML ?
  Quelles sont vos connaissances de HTML ?
  <nowiki><input type="radio" </nowiki>'''''name="choice" value="1"''''' checked>faibles
  <input type="radio" '''''name="choice" value="1"''''' checked>faibles
  <nowiki><input type="radio" name="choice" value="2">moyennes</nowiki>
  <input type="radio" name="choice" value="2">moyennes
  <nowiki><input type="radio" name="choice" value="3">bonnes</nowiki>
  <input type="radio" name="choice" value="3">bonnes
  <nowiki><br></nowiki>
  <br>
  Indiquez votre expertise en programmation:
  Indiquez votre expertise en programmation:
  <nowiki><input type="radio" </nowiki>'''''name="choice2" value="1"''''' checked>absente
  <input type="radio" '''''name="choice2" value="1"''''' checked>absente
  <nowiki><input type="radio" name="choice2" value="2">moyenne</nowiki>
  <input type="radio" name="choice2" value="2">moyenne
  <nowiki><input type="radio" name="choice2" value="3">bonne</nowiki>
  <input type="radio" name="choice2" value="3">bonne
  <nowiki><P></nowiki>
  <P>
  <nowiki><input type="submit" value="Voir le result!"></nowiki>
  <input type="submit" value="Voir le result!">
  <nowiki></form></nowiki>
  </form>
</source>
   
   


Line 738: Line 759:
In our example, we use $_POST:
In our example, we use $_POST:


<nowiki>$choice = $_POST[’choice’];</nowiki>
<source lang="php">
  <nowiki>$choice2 = $_POST[’choice2’];</nowiki>
$choice = $_POST[’choice’];
  $choice2 = $_POST[’choice2’];
</source>


: In our example, we will use two PHP variables:$choice and $choice2
: In our example, we will use two PHP variables:$choice and $choice2
Line 746: Line 769:
: we add result of the two values and compute a result with an if clause.
: we add result of the two values and compute a result with an if clause.


  <nowiki><?php</nowiki>
  <?php


  // Get values from the form
  // Get values from the form
  <nowiki>$choice = $_POST[’choice’];</nowiki>
  $choice = $_POST[’choice’];
  <nowiki>$choice2 = $_POST[’choice2’];</nowiki>
  $choice2 = $_POST[’choice2’];


  // Compute score
  // Compute score
Line 756: Line 779:


  // Compute message as function of result
  // Compute message as function of result
  <nowiki>echo "<h3>Votre score is de " . $score . "</h3>";</nowiki>
  echo "<h3>Votre score is de " . $score . "</h3>";
  <nowiki>if ($score < 3) {</nowiki>
  if ($score < 3) {
   <nowiki>echo "<p>Vous &ecirc;tes un d&eacute;butant</p>";</nowiki>
   echo "<p>Vous &ecirc;tes un d&eacute;butant</p>";
  <nowiki>} elseif ($score < 5) {</nowiki>
  } elseif ($score < 5) {
   <nowiki>echo "<p>Vous avez un niveau moyen</p>";</nowiki>
   echo "<p>Vous avez un niveau moyen</p>";
  } else {
  } else {
   <nowiki>echo "<p>Vous &ecirc;tes un expert !</p>";</nowiki>
   echo "<p>Vous &ecirc;tes un expert !</p>";
  }
  }
  ?>
  ?>


: '''Inhibit direct access to PHP (without data)'''
: '''Inhibit direct access to PHP (without data)'''
: <nowiki>(1) if (isset($_POST[’choice’])) then { ..... } else { echo "sorry ......."; }</nowiki>
: (1) if (isset($_POST[’choice’])) then { ..... } else { echo "sorry ......."; }
: <nowiki>(2) Alternative: if (!isset($_POST[’choice’])) {echo "sorry"; exit; }</nowiki>
: (2) Alternative: if (!isset($_POST[’choice’])) {echo "sorry"; exit; }
: '''Forms processing with PHP II'''
: '''Forms processing with PHP II'''
: '''Checkboxes with PHP - arrays'''
: '''Checkboxes with PHP - arrays'''
Line 776: Line 799:
'''Part of the HTML code:'''
'''Part of the HTML code:'''


<nowiki><form action="</nowiki>'''calcul4.php'''" method=post>
<source lang="htmlstrict">
<form action="'''calcul4.php'''" method=post>
  Quels sont vos couleurs préféres?
  Quels sont vos couleurs préféres?
  <nowiki><br></nowiki>
  <br>
  <nowiki><input type="</nowiki>'''<nowiki>checkbox" name="choice[]"</nowiki>''' value="Red">Red
  <input type="'''checkbox" name="choice[]"''' value="Red">Red
  <nowiki><table bgcolor="red" width="50"><tr><td>&nbsp;</td></tr></table></nowiki>
  <table bgcolor="red" width="50"><tr><td>&nbsp;</td></tr></table>


  <nowiki><input type="checkbox" </nowiki>'''<nowiki>name="choice[]</nowiki>'''" value="Blue">Blue
  <input type="checkbox" '''name="choice[]'''" value="Blue">Blue
  <nowiki><table bgcolor="blue" width="50"><tr><td>&nbsp;</td></tr></table></nowiki>
  <table bgcolor="blue" width="50"><tr><td>&nbsp;</td></tr></table>


  <nowiki><input type="checkbox" </nowiki>'''<nowiki>name="choice[]</nowiki>'''" value="Green">Green
  <input type="checkbox" '''name="choice[]'''" value="Green">Green
  <nowiki><table bgcolor="green" width="50"><tr><td>&nbsp;</td></tr></table></nowiki>
  <table bgcolor="green" width="50"><tr><td>&nbsp;</td></tr></table>
  .....
  .....
  <nowiki><input type="checkbox" </nowiki>'''<nowiki>name="choice[]</nowiki>'''" value="Black">Black
  <input type="checkbox" '''name="choice[]'''" value="Black">Black
  <nowiki><table bgcolor="black" width="50"><tr><td>&nbsp;</td></tr></table></nowiki>
  <table bgcolor="black" width="50"><tr><td>&nbsp;</td></tr></table>


  <nowiki><input type="submit" value="Voir le result!"></nowiki>
  <input type="submit" value="Voir le result!">
  <nowiki></form></nowiki>
  </form>
</source>


: Remember the syntax to put all values into an array: <tt><nowiki>"choice[]"</nowiki></tt>
: Remember the syntax to put all values into an array: <tt>"choice[]"</tt>


'''PHP code:'''
'''PHP code:'''




<nowiki><?php</nowiki>
<source lang="php">
  <nowiki>$choice = $_POST[’choice’];</nowiki>
<?php
  $choice = $_POST[’choice’];


  <nowiki>echo("<h3>Vos couleurs préférées sont </h3>");</nowiki>
  echo("<h3>Vos couleurs préférées sont </h3>");


  <nowiki>for ($i=0;$i<sizeof($choice);$i++) {</nowiki>
  for ($i=0;$i<sizeof($choice);$i++) {
     if (isset('''<nowiki>$choice[$i]</nowiki>''')) {
     if (isset('''$choice[$i]''')) {
         echo("'''<nowiki>$choice[$i]</nowiki>''' - ");
         echo("'''$choice[$i]''' - ");
     }
     }
  }
  }
  ?>
  ?>
</source>


: '''All in one solution ?'''
: '''All in one solution ?'''
Line 816: Line 843:


   
   
'''<nowiki><? </nowiki>
<source lang="php">
  <nowiki>if (!isset($_POST[’process’])) </nowiki>{
<?php
  if (!isset($_POST[’process’])) {
  ?>'''
  ?>'''
  //... lets display the form)
  //... lets display the form)
   
   
   <nowiki><FORM METHOD="POST" ACTION="<? echo $PHP_SELF ?>"></nowiki>
   <FORM METHOD="POST" ACTION="<? echo $PHP_SELF ?>">
  &nbsp;&nbsp;.....
  &nbsp;&nbsp;.....
  <nowiki>&nbsp;&nbsp;</FORM></nowiki>
  &nbsp;&nbsp;</FORM>
   
   
  '''<nowiki><?</nowiki>
  '''<?php
  } else {'''
  } else {'''
  //... we got data, so let’s process
  //... we got data, so let’s process
  '''}
  '''}
  ?>'''
  ?>'''
</source>


: '''Polishing: Test if we have all the POST/GET variables'''
: '''Polishing: Test if we have all the POST/GET variables'''
Line 837: Line 866:
: "array_key_exists()"
: "array_key_exists()"


<source lang="php">
  if (array_key_exists(’first’, $_POST)) { .... do something ...};
  if (array_key_exists(’first’, $_POST)) { .... do something ...};
</source>


: '''''"isset()"''''' to see if a variable exists:
: '''''"isset()"''''' to see if a variable exists:


<nowiki>if (isset($POST[’first’]) ) { .... do ....}</nowiki>
<source lang="php">
if (isset($POST[’first’]) ) { .... do ....}
</source>


: The difference is that  
: The difference is that  
Line 847: Line 880:
: isset returns FALSE if value is NULL.
: isset returns FALSE if value is NULL.


'''<nowiki>ATTENTION, to test <input type="text"> you also may want to test if there is an empty string.</nowiki>'''
'''ATTENTION, to test <input type="text"> you also may want to test if there is an empty string.'''


: '''''“empty()”'''''  
: '''''“empty()”'''''  
: to decide if user filled in a text field
: to decide if user filled in a text field


<source lang="php">
  if (empty ($input) ) { ... complain ... } else { ... do ...}
  if (empty ($input) ) { ... complain ... } else { ... do ...}
</source>


: empty() returns TRUE if a value is: "", 0, "0", NULL, FALSE, array(), ....
: empty() returns TRUE if a value is: "", 0, "0", NULL, FALSE, array(), ....
Line 862: Line 897:
: [http://tecfa.unige.ch/guides/php/examples/sessions/ http://tecfa.unige.ch/guides/php/examples/sessions/] '''
: [http://tecfa.unige.ch/guides/php/examples/sessions/ http://tecfa.unige.ch/guides/php/examples/sessions/] '''


<source lang="php">
  session_start();
  session_start();
  <nowiki>if (!isset($_SESSION[’count’])) {</nowiki>
  if (!isset($_SESSION[’count’])) {
     <nowiki>$_SESSION[’count’] = 0;</nowiki>
     $_SESSION[’count’] = 0;
  } else {
  } else {
     <nowiki>$_SESSION[’count’]++;</nowiki>
     $_SESSION[’count’]++;
  }
  }
  <nowiki>if ($_SESSION[’count’] > 2) {</nowiki>
  if ($_SESSION[’count’] > 2) {
  <nowiki>echo ’<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">’;</nowiki>
  echo ’<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">’;
     <nowiki>echo "<html> <body>";</nowiki>
     echo "<html> <body>";
     echo "Sorry it’s over you can’t do it twice";
     echo "Sorry it’s over you can’t do it twice";
     <nowiki>echo "</body> </html>";</nowiki>
     echo "</body> </html>";
     exit;
     exit;
   }  
   }  
  // .... continue code with access time = 1 and 2
  // .... continue code with access time = 1 and 2
</source>


: '''On-line surveys and file-based storage'''
: '''On-line surveys and file-based storage'''
Line 885: Line 922:
: This time we use PHP to generate the HTML code
: This time we use PHP to generate the HTML code


<source lang="php">
  $scales = array("food", "work", "love", "leisure", "sports");
  $scales = array("food", "work", "love", "leisure", "sports");
  function scale ($thing) {
  function scale ($thing) {
     <nowiki>echo "<TR> <TD align=right>Importance of <STRONG>$thing</STRONG>:</TD>";</nowiki>
     echo "<TR> <TD align=right>Importance of <STRONG>$thing</STRONG>:</TD>";
     <nowiki>echo "<TD><select name=$thing>";</nowiki>
     echo "<TD><select name=$thing>";
     <nowiki>echo "<option value=1>1 - totally unimportant";</nowiki>
     echo "<option value=1>1 - totally unimportant";
     <nowiki>echo "<option value=2>2 - not important";</nowiki>
     echo "<option value=2>2 - not important";
     <nowiki>echo "<option value=3 selected>3 - rather not important";</nowiki>
     echo "<option value=3 selected>3 - rather not important";
     <nowiki>echo "<option value=4>4 - slightly important";</nowiki>
     echo "<option value=4>4 - slightly important";
     <nowiki>echo "<option value=5>5 - rather important";</nowiki>
     echo "<option value=5>5 - rather important";
     <nowiki>echo "<option value=6>6 - very important";</nowiki>
     echo "<option value=6>6 - very important";
     <nowiki>echo "</select>";</nowiki>
     echo "</select>";
     <nowiki>echo "</TD></TR>";</nowiki>
     echo "</TD></TR>";
     }
     }


Line 909: Line 947:
     while (next($scales));
     while (next($scales));
   } ?>
   } ?>
  <nowiki><form> <table></nowiki>
  <form> <table>
  ......
  ......
  dump_scales();
  dump_scales();
  ......
  ......
  <nowiki></table> </form></nowiki>
  </table> </form>
  Ecrire dans un fichier
  Ecrire dans un fichier
  // check existance of file (or try to create it)
  // check existance of file (or try to create it)
Line 919: Line 957:
     $try = touch($file_name);
     $try = touch($file_name);
   if (!$try) {
   if (!$try) {
     <nowiki>echo "<p>Sorry I can’t open a file, something is wrong";</nowiki>
     echo "<p>Sorry I can’t open a file, something is wrong";
     exit;
     exit;
   }
   }
Line 941: Line 979:
   // give feedback
   // give feedback
     if ($result) {
     if ($result) {
       <nowiki>echo "<p>Your data have successfully been registered.";</nowiki>
       echo "<p>Your data have successfully been registered.";
     }
     }
   else {
   else {
     <nowiki>echo "<p>Too bad, the db did not want your data.";</nowiki>
     echo "<p>Too bad, the db did not want your data.";
   }
   }
   // close the file pointer
   // close the file pointer
Line 950: Line 988:
   ?>
   ?>
   
   
  <nowiki><?</nowiki>
  <?
   // EXIT here ... we don’t want to see the form again. If you do, kill the exit
   // EXIT here ... we don’t want to see the form again. If you do, kill the exit
   exit;
   exit;
  }
  }
  ?>
  ?>
</source>


'''Remember'''
'''Remember'''


<nowiki>fopn (<file name>, "a")</nowiki>
<source lang="php">
fopn (<file name>, "a")
</source>


: to open a file and then append.
: to open a file and then append.


<nowiki>fputs(<handle>, “string”)</nowiki>
<source lang="php">
fputs(<handle>, “string”)
</source>


: to write to a file
: to write to a file
Line 968: Line 1,011:
: '''Dump contents of a file'''
: '''Dump contents of a file'''


<nowiki>.... we just insert it a <pre> with an “include”</nowiki>
.... we just insert it a <pre> with an “include”


   
   
<nowiki><BODY></nowiki>
<source lang="htmlstrict">
     <nowiki><H1>PHP/MySQL Demo - Dump Database Contents</H1></nowiki>
<BODY>
     <H1>PHP/MySQL Demo - Dump Database Contents</H1>
   
   
  <nowiki><? </nowiki>
  <?  
   /* Daniel.Schneider@tecfa.unige.ch
   /* Daniel.Schneider@tecfa.unige.ch
   Will dump the contents of the results file
   Will dump the contents of the results file
   <nowiki>*/</nowiki>
   */
  ?>
  ?>
   
   
   <nowiki><strong>Results registered so far:</strong></nowiki>
   <strong>Results registered so far:</strong>
  <nowiki><pre></nowiki>
  <pre>
  <nowiki><? readfile("results/result.text"); ?></nowiki>
  <? readfile("results/result.text"); ?>
  <nowiki></pre></nowiki>
  </pre>
  ..........
  ..........
   
   
  <nowiki></BODY></nowiki>
  </BODY>
</source>
   
   


Line 1,000: Line 1,045:
'''''Example XML'''''
'''''Example XML'''''


<source lang="php">
  Header("Content-type: text/xml);
  Header("Content-type: text/xml);
</source>


'''''Example SVG'''''
'''''Example SVG'''''


<source lang="php">
  Header("Content-type: image/svg+xml");
  Header("Content-type: image/svg+xml");
</source>


'''''Example RDF'''''
'''''Example RDF'''''


<source lang="php">
  Header("Content-type: application/rdf+xml");
  Header("Content-type: application/rdf+xml");
</source>


: '''Generate some simple XML'''
: '''Generate some simple XML'''
Line 1,015: Line 1,066:
: [http://tecfa.unige.ch/guides/php/examples/simple/simple-calcul-xml.css http://tecfa.unige.ch/guides/php/examples/simple/simple-calcul-xml.css] '''
: [http://tecfa.unige.ch/guides/php/examples/simple/simple-calcul-xml.css http://tecfa.unige.ch/guides/php/examples/simple/simple-calcul-xml.css] '''


<nowiki><?php</nowiki>
<source lang="php">
<?php
  '''header("Content-type: text/xml");'''
  '''header("Content-type: text/xml");'''
  '''<nowiki>print(’<?xml version="1.0" encoding="iso-8859-1"?>’ . "\n");</nowiki>'''
  '''print(’<?xml version="1.0" encoding="iso-8859-1"?>’ . "\n");'''
  '''<nowiki>print(’<?xml-stylesheet href="simple-calcul-xml.css" type="text/css" ?>’);</nowiki>'''
  '''print(’<?xml-stylesheet href="simple-calcul-xml.css" type="text/css" ?>’);'''


  $leisure_satisfaction = 5; $work_satisfaction = 7;  $family_satisfaction = 8;
  $leisure_satisfaction = 5; $work_satisfaction = 7;  $family_satisfaction = 8;
  $index = ($leisure_satisfaction + $work_satisfaction + $family_satisfaction) / 3 ;
  $index = ($leisure_satisfaction + $work_satisfaction + $family_satisfaction) / 3 ;
  echo "'''<nowiki><resultat></nowiki>''' Satisfaction Index = '''$index''' '''<nowiki></resultat></nowiki>'''";
  echo "'''<resultat>''' Satisfaction Index = '''$index''' '''</resultat>'''";
  ?>
  ?>
</source>

Revision as of 18:37, 9 February 2010

Introduction

Learning goals
  • Be able to make modifications in a PHP file (in particular configuration files)
Prerequisites
Moving on
Level and target population
  • Beginners
Remarks
  • This is a first version ...

PHP standards for Hypertext Preprocessor

History:

Personal Home Page Generator (Php2/FI) in the mid-nineties
PHP 3 since 1997,
PHP 4 since 1999,
PHP 5 since 2004/2005

Since PHP 3.0, the language is used to write larger web applications. PHP Version 3.0 was defined as HTML-embedded scripting language. Much of its syntax is borrowed from C, Java and Perl with a couple of unique PHP-specific features thrown in. The goal of the language is to allow web developers to write dynamically generated pages quickly. This definition remains the same in the PHP 5 FAQ.

Principle:

Analogy with JavaScript: PHP code can be mixed with HTML
BUT: The server reads the files and computes it (and end-user never can see the code)
Servers are configured to read *.php files as PHP (sometimes also *.php3, *.php4 etc.)

Purpose:

Create dynamic web pages (small applications) or program larger web applications

Links:

PHP features

Availability:

Free and open source (GPL)
cross-platform (Unix, Linux, BSD, MacOS X, Win32, etc.)

Installation:

can run as CGI program (external to a web server)
can run as web server module (this is the standard case, e.g. with the Apache server)
can be used as command-line scripting engine

Highlights:

good database support (Oracle, Sybase, Microsoft, MySQL, Postgres, ODBC, etc.)
good system integration (files)
complete programming language, including OO support
easy to learn
made for internet application (cookies, authentication, sessions, redirection...)
dozens of integrated libraries (LDAP, PDF, XML, GIF,...)
support for object-oriented programming since PHP 4 (PHP 5 introduced a new model)

Alternatives to PHP:

ASP (Microsoft)
JSP (Java)
Cold Fusion (Adobe)

HTML and PHP integration

PHP code is defined within an XML processing instruction

<nowiki><?php ..... ?>

<?php
 echo("if you want to serve XML documents, do like this\n");
 ?>

File inclusion

Let's now introduce our first PHP code. PHP code can be spread over many files (hundreds or thousands in some larger applications).

Include:

inserts content of file when this expression is evaluated

include ("file name");
include("style.php");

Require:

inserts content of file when the php file is loaded

require ("file name");
require("my_functions.inc");

Variant (recommended):

include_once() and require_once().

Only include once, will make your application faster.

File inclusion example

http://tecfa.unige.ch/guides/php/examples/includes/
 <HTML>
   <HEAD>
     <TITLE>Simple Include Demo (21-Apr-1998)</TITLE>
 <?php include("style.text"); ?>
   </HEAD>
   <BODY>
     <H1>Simple Include Demo</H1>
 
 In this file we include a <A HREF="style.text">style sheet</A> and
     a <A HREF="footer.text">footer</A>.
     <P>
       Look at <A HREF="include1.phps">the formatted source</A>
       or the <A HREF="include1.source">unformatted one</A>
  if you want to know how this is done.
 
     <H1>Yet another styled title</H1>
     <UL>
       <LI> bullet item </LI>
       <LI> bullet item </LI>
     </UL>
 
 <?php
 /* A footer */
 include("footer.text"); 
 ?>
   </BODY>
 </HTML>


The programming language PHP

Elements of programming

Program= algorithm + data structures
Programming elements

PHP syntax overview:

PHP looks like "C" (C, C++, Java, Perl, etc.)

Each instruction is ended with a ";"
Comments // or #, or included within /* ... */

Variables and assignments

Variables are “containers” for information.

  • Each identifier with a $ in front is a variable
  • Variables don’t need to be declared
  • Assignment operator: =

Principle:

$variable = "content" ;

Illustrations:

 $a = 10;
 $name = "Patrick Ott";
 $sum = 123.456;

Using variables with content strings example:

/guides/php/examples/simple/simple-echo.php (application)
/guides/php/examples/simple/simple-echo.phps (pretty source)
/guides/php/examples/simple/simple-echo.text (source)
 <BODY>
  <H1>Simple Echo of variables with PHP</H1>

 <?php
  $a = 10;
  $nom = "Patrick Ott";
  $somme = 123.456;
  echo "Le nommé $nom a $somme francs dans la poche, mais il voudrait $a fois plus.";
 ?>
 
 <p><hr>
 </BODY>
echo is an “instruction” to display a string (chain of characters)
Note: all the $xxx are replaced by their contents !

Simple arrays

Arrays are a sort of lists (several values within the same variable)

Array creation - method 1:

$numbers[] =1;
$numbers[] =2;
$numbers[] =3;
$numbers[] =4;

Array creation - method 2:

$numbers = array (1, 2, 3, 4);
$names = array ("Pat", "Dave", "Surf", "K");

Use of simple arrays:

$array[index]

Index starts at 0 ! (zero). Example:

echo "Second element of $names is: $names[1];

Example: Simple variables and some HTML generation

/guides/php/examples/simple/simple-arrays.php
<?php
 
 // Some simple HTML
 echo"<h1>Simple arrays</h1>";
 
 $utilisateur = "cher étudiant";
 $no_utilisateur = 3;
 
 $numbers = array (1, 2, 3, 4);
 $names = array ("Pat", "Dave", "Surf", "K");
 $names[] = "Zorro";
 
 // Note html <br> tag
 echo "Salut $utilisateur. Vous êtes le numéro $no_utilisateur.<br>";
 
 // echo with concatenation, use it to print complex things
 echo "La quatrième personne s’appelle " . $names[3] ." ";
 
 // simple echo
 echo "et la cinquième personne s’appelle $names[4].<p>";
 $n = sizeof($numbers);
 
 // note that we have to use \ in order to print a $ !
 echo "We have $n numbers in array \$numbers.";
 ?>

Associative arrays and multi-dimensional tables

 $fruits = array(
     "fruits"  => array("a"=>"orange","b"=>"banana","c"=>"apple"),
     "numbers" => array(1, 2, 3, 4, 5, 6)
     "holes"   => array("first", 5 => "second", "third")
 );
Summary - variables
You should, but don’t need to initialize varibales
 $a = 1234; # decimal number
 $a = -123; # a negative number
 $a = 1.234; $a = 1.2e3; # floating point number
 $str = "This is a string"; # string
 $a[0] = "abc"; # element zero of un array
 $a[1] = "def"; # element 1 of an array
 $b["foo"] = 13; # element "foo" of an array
Constants.
Constants are "variables" with information that cannot change.
Do not use "$".
By convention, use capital letters.
Definition
define(<NAME>, <value>);
 define("PI", 3.14);
 define("REMERCIEMENTS", "Thanx for using our program<br>");
 define("SALUTATIONS", "Je vous prie d’agréer, Madame, Monsieur, l’expression de nos sentiments dévoués");
 $radius = 12;
 $perimeter = 2 * $radius * PI;
 echo REMERCIEMENTS;
 echo "le périmètre du cercle is de " . $perimeter . "<br>";
 echo SALUTATIONS;

result:

Thanx for using our program
le périmètre du cercle is de 77.76
Je vous prie d’agréer, Madame, Monsieur, l’expression de nos sentiments dévoués.
Simple expressions and operators
Arithmetic operators
Like normal math:


example
name
Returns the result:
$a +$b
Addition
Sum of $a and $b
$a - $b
Subtraction
$b minus $a
$a * $b
Multiplication
$a / $b
Division
$a % $b
Modulo
Rest of integer division $a by $b
Simple arithmetic


Application
: /guides/php/examples/simple/simple-calcul.php


Source
: /guides/php/examples/simple/simple-calcul.phps


To copy 
: /guides/php/examples/simple/simple-calcul.text


 $leisure_satisfaction = 5;
 $work_satisfaction = 7;
 $family_satisfaction = 8;
 $index = ($leisure_satisfaction + $work_satisfaction + $family_satisfaction)
          / 3 ;
 echo "<p align=center> Satisfaction Index = $index <b>";

assignment + addition in one step:

 // sets $a to 8, as if we had said: $a = $a + 5;
 $a += 5;
Operators for strings

concatenation of strings

Use the "." operator

example:

 $a = "Hello ";
 $b = $a . "World!"; // now $b = "Hello World!"
Note: There are dozens of string manipulation functions in PHP !!

assignment + concatenation in one step

 $b = "Hello ";
  // sets $b to "Hello There!", just like $b = $b . "There!";
 $b .= "There!";
Logical operators


example
name
result
$a and $b
"and"
result true, if $a et $b are true
$a && $b
"and"
"
$a or $b
"or"
result true, if $a or $b or both are true
$a
$b
"or"
"
$a xor $b
Or exclusive
result true, if $a or $b are true, but not both
! $a
"not"
result true, if $a is false(
comparison


example
name
result
$a == $b
equal
True if $a is equal to $b.
$a===$b
identical
True if $a==$b and same type (php 4.x)
$a != $b
different
True if $a is not equal to $b.
$a!==$b
not identical
True if $a!=$b or not same type (php4.x)
$a < $b
inferior
True if $a is strictly less than $b.
$a > $b
superior
True if $a is strictly greater than $b.
$a <= $b
inferior or equal
True if $a is less than or equal to $b.
$a >= $b
superior or equal
True if $a is greater than or equal to $b
You can use parenthesis if you like to group operators !
Simple comparisons
[/guides/php/examples/simple/simple-compare.php /guides/php/examples/simple/simple-compare.php]
[/guides/php/examples/simple/simple-compare.phps /guides/php/examples/simple/simple-compare.phps]
Note: in PHP each number equal or small than 0 is FALSE, each superior is TRUE
 $a = "Migros";
 $b = "Coop";
 $result = $a==$b;
 $result2 = $a > $b;
 $result3 = $result==TRUE;
 echo "Result One = $result. Result TWO = $result2. Result THREE = $result3.";
Selection (Conditions and tests)

Principle (several typical situations):

If a condition is true then do ...
If a condition is true then do ... , else do .....
If a condition is true then do ... , else if an other condition is true do ... , else ......

"IF" (several variants)

if (expr) statements
if (expr) statements else statements
if (expr) statements elseif (expr) statements else ...
if (expr) statements elseif (expr) statements [ elseif (expr) ... ]
expr = Expression must return TRUE or FALSE
statements = simple instructions or a block or instructions
simple: $a = 10;
block: { $a =12; echo "salut"; ..... }
Execution model
If expression = TRUE then execute statement(s)
If expression = FALSE then go to the next clause
Simple "if" (comparison)
/guides/php/examples/simple/simple-if.php
/guides/php/examples/simple/simple-if.phps (source)
Compares two numbers: $a and $b, and displays a message.
Here is a decision tree.
Simple decision tree
[[Image:]]
 <?php
 
 $a = 10; $b = 11;
 print "a was $a, b was $b. ";
 if ($a > $b) {
     print "a is bigger than b";
 } elseif ($a == $b) {
     print "a is equal to b";
 } else {
     print "==> a is smaller than b.";
 }
 
 ?>


See also the following:

switch
foreach
do ... while
break and continue
PHP functions
Like all programming languages PHP allows to define procedures/functions.
A function is a a mini program that has a name and that you can "call" (invoke).

"Hey, take these informations, do something and (maybe) return the result"

Usually, you find function definition in the beginning of program (or within include files)
[[Image:]]
Color mixing for paint
http://tecfa.unige.ch/guides/php/examples/simple/ (files color-mix.*)
 function color_mix($color1,$color2) {
   $result= "unknown";

   if ($color1 == "bleu" and $color2 == "rouge") {
     $result = "violet";   }
   elseif ($color1 == "jaune" and $color2 == "bleu") {
     $result = "green";  }
   elseif ($color1 == "noire" and $color2 == "blanc") {
     $result = "gris";  }
   else {
     $result = "orange";   }
   return $result;
 }

 // Two calls to this function, results saved in variables

 $situation1 =  color_mix ("bleu", "rouge") ;

 $situation2 =  color_mix ("jaune", "bleu") ;

 // Print

 echo "Bleu  et rouge donne $situation1 <br>";
 echo "Jaune et bleu  donne $situation2";
HTML generation with functions
/guides/php/examples/simple/function-demo.php
/guides/php/examples/simple/function-demo.phps
 <?php
 
 // html formats a data element
 '''function pretty_print''' ($output) {
     separator ();
     echo "<p align='center'> <strong>ELEMENT:</strong> $output </p>";
 }
 // outputs a separator
 '''function separator ()''' {
     echo "<hr size=4 width=70%>";
 }
 // data we have
 $el1 = "Un arbre jaune";
 $el2 = "Ein gelber Hund";
 $el3 = "A yellow sky";
 // dump the data
 '''pretty_print'''($el1);
 '''pretty_print'''($el2);
 '''pretty_print'''($el3);
 
 '''separator''' ();
 echo "<hr>";
 ?>
Loops (iterations)

The "for loop" syntax

 FOR (expr1; expr2; expr3) statement
expr1 is evaluated at start
expr2 is evaluated at start of each loop,if result = TRUE the loop will continue, else it will stop
expr3 is evaluated at the end of each loop,
statement is executed for each loop.
Love generation
see: /guides/php/examples/html-generate/love.php
see: /guides/php/examples/html-generate/love.phps
 for ($i=1; $i<=10; $i++) {
     print "I love you so ! "; }

result:love you so ! I love you so ! I love you so ! I love you so ! I love you so ! I love you so ! ......

 echo "Je t’aime plus que toi.<br>
 for ($i=2; $i<=10; $i++) {
     echo "Non, je t’aime $i fois plus que  toi ! ";
 }

result:

Je t’aime plus que moi.
Non, je t’aime 2 fois plus que moi ! Non, je t’aime 3 fois plus que moi ! Non, je t’aime 4 fois plus que moi ! Non, je t’aime 5 fois plus que moi ! Non, je t’aime 6 .....

Other PHP elements:

$i is used as so-called iteration variable. At start $i = 1 or 2.
echo
print works like print.
Generation of html tables
see: /guides/php/examples/html-generate/love.php
see: /guides/php/examples/html-generate/love.phps
see: /guides/php/examples/html-generate/love.text
 '''$love_list''' = array ("a lot", "a bit", "somewhat", "à mourir", "forever", "until notice", "more than I love my dog");
 <table border align="center">
 <?
 // define a function to generate a table
 function build_table($list) {
  '''for ($i=0; $i < sizeof($list); $i++) {
    $love_text = $list[$i];
    echo "<tr> <td> ... I love you</td> <td>$love_text</td>";
    }
 }
 // call the function, generate the table
 build_table($love_list);
 ?>'''
 </table>

Note:

PHP is used with the HTML element
The build_table function is called with an array
There exist more looping constructs in PHP (like while or for-each) !
Practical advice
Debugging
Look at the generated HTML code "View Source")
Insert this in you PHP file (will give you lots of information !)
 phpinfo();
Insert print statements!
 echo "DEBUG: \$var = $var";
 echo "TEST: var = $var";
Raise "error reporting" to its maximum !!!

Insert this on top:

 error_reporting(E_ALL);
Portals
Warning: NEVER insert blank lines at start or end of a file !!
Most files should stop like this (no line feed !!) ?>
... because PHP starts producing HMTL headers as soon as it sees a little blank space before or after php code <?php .... ?>
HTML forms processing with PHP
Forms processing with PHP I (Calcul)
Simple quiz and POST to a php file
See: /guides/php/examples/simple-calculate/formulaire.html
Source: /guides/php/examples/simple-calculate/formulaire.text
This example shows:
how to treat and HTML form
how to compute and display a result.
[[Image:]]


Part of the HTML form:

 <form '''''action="calcul.php"''''' method="post">
 
 Quelles sont vos connaissances de HTML ?
 <input type="radio" '''''name="choice" value="1"''''' checked>faibles
 <input type="radio" name="choice" value="2">moyennes
 <input type="radio" name="choice" value="3">bonnes
 <br>
 Indiquez votre expertise en programmation:
 <input type="radio" '''''name="choice2" value="1"''''' checked>absente
 <input type="radio" name="choice2" value="2">moyenne
 <input type="radio" name="choice2" value="3">bonne
 <P>
 <input type="submit" value="Voir le result!">
 </form>


[[Image:]]
Retrieve values of an HTML form
Data from a from a stored by the server in a so-called super global variables
Use $_POST to deal with POST variables
POST: values are handed over attached (and not visible) to the server
Use $_GET for GET variables
GET: values are handed over in the URL string (user can see these)
You can use the "name" attribute of the form to retrieve values

In our example, we use $_POST:

 $choice = $_POST[’choice’];
 $choice2 = $_POST[’choice2’];
In our example, we will use two PHP variables:$choice and $choice2
Computing and display of results
see: /guides/php/examples/simple-calculate/calcul.phps
we add result of the two values and compute a result with an if clause.
<?php
// Get values from the form
$choice = $_POST[’choice’];
$choice2 = $_POST[’choice2’];
// Compute score
$score = $choice + $choice2;
// Compute message as function of result
echo "

Votre score is de " . $score . "

";
if ($score < 3) {
echo "

Vous êtes un débutant

";
} elseif ($score < 5) {
echo "

Vous avez un niveau moyen

";
} else {
echo "

Vous êtes un expert !

";
}
?>
Inhibit direct access to PHP (without data)
(1) if (isset($_POST[’choice’])) then { ..... } else { echo "sorry ......."; }
(2) Alternative: if (!isset($_POST[’choice’])) {echo "sorry"; exit; }
Forms processing with PHP II
Checkboxes with PHP - arrays
/guides/php/examples/simple-calculate/formulaire4.text
/guides/php/examples/simple-calculate/formulaire4.html

Part of the HTML code:

 <form action="'''calcul4.php'''" method=post>
 Quels sont vos couleurs préféres?
 <br>
 <input type="'''checkbox" name="choice[]"''' value="Red">Red
 <table bgcolor="red" width="50"><tr><td>&nbsp;</td></tr></table>

 <input type="checkbox" '''name="choice[]'''" value="Blue">Blue
 <table bgcolor="blue" width="50"><tr><td>&nbsp;</td></tr></table>

 <input type="checkbox" '''name="choice[]'''" value="Green">Green
 <table bgcolor="green" width="50"><tr><td>&nbsp;</td></tr></table>
 .....
 <input type="checkbox" '''name="choice[]'''" value="Black">Black
 <table bgcolor="black" width="50"><tr><td>&nbsp;</td></tr></table>

 <input type="submit" value="Voir le result!">
 </form>
Remember the syntax to put all values into an array: "choice[]"

PHP code:


 <?php
 $choice = $_POST[’choice’];

 echo("<h3>Vos couleurs préférées sont </h3>");

 for ($i=0;$i<sizeof($choice);$i++) {
     if (isset('''$choice[$i]''')) {
        echo("'''$choice[$i]''' - ");
     }
 }
 ?>
All in one solution ?
You can put both the form and the processing code in a single page
In this case, test if the file is called with data from a form, see $process below


<?php
 if (!isset($_POST[’process’])) {
 ?>'''
 //... lets display the form)
 
   <FORM METHOD="POST" ACTION="<? echo $PHP_SELF ?>">
 &nbsp;&nbsp;.....
 &nbsp;&nbsp;</FORM>
 
 '''<?php
 } else {'''
 //... we got data, so let’s process
 '''}
 ?>'''
Polishing: Test if we have all the POST/GET variables

2 methods to test what we have in $_POST or $_GET

"array_key_exists()"
 if (array_key_exists(’first’, $_POST)) { .... do something ...};
"isset()" to see if a variable exists:
 if (isset($POST[’first’]) ) { .... do ....}
The difference is that
array_key_exists returns TRUE if value is NULL
isset returns FALSE if value is NULL.

ATTENTION, to test <input type="text"> you also may want to test if there is an empty string.

“empty()”
to decide if user filled in a text field
 if (empty ($input) ) { ... complain ... } else { ... do ...}
empty() returns TRUE if a value is: "", 0, "0", NULL, FALSE, array(), ....
Session management
PHP has session support (can keep variables over a whole user session).
Each visitor gets an identifier (a "sessions id"). It is stored in a cookie (in the www client) or within the URL.
This information is available in super global: $_SESSION
Restrict repetitive access to a page
http://tecfa.unige.ch/guides/php/examples/sessions/
 session_start();
 if (!isset($_SESSION[’count’])) {
     $_SESSION[’count’] = 0;
 } else {
     $_SESSION[’count’]++;
 }
 if ($_SESSION[’count’] > 2) {
 echo <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">;
     echo "<html> <body>";
     echo "Sorry it’s over you can’t do it twice";
     echo "</body> </html>";
     exit;
   } 
 // .... continue code with access time = 1 and 2
On-line surveys and file-based storage
Survey
see: http://tecfa.unige.ch/guides/php/examples/form-file-demo/
new-entry.php contains the form and code
dump_results.php shows file contents
The HTML form
This time we use PHP to generate the HTML code
 $scales = array("food", "work", "love", "leisure", "sports");
 function scale ($thing) {
    echo "<TR> <TD align=right>Importance of <STRONG>$thing</STRONG>:</TD>";
    echo "<TD><select name=$thing>";
    echo "<option value=1>1 - totally unimportant";
    echo "<option value=2>2 - not important";
    echo "<option value=3 selected>3 - rather not important";
    echo "<option value=4>4 - slightly important";
    echo "<option value=5>5 - rather important";
    echo "<option value=6>6 - very important";
    echo "</select>";
    echo "</TD></TR>";
    }


 function dump_scales ()  {
  global $scales;
  reset($scales);
  do {
     $scale = scale(current($scales));
     echo "$scale\n";
     }
     while (next($scales));
  } ?>
 <form> <table>
 ......
 dump_scales();
 ......
 </table> </form>
 Ecrire dans un fichier
 // check existance of file (or try to create it)
   // a better alternative to touch() would be is_file, is_writable and so on.
     $try = touch($file_name);
   if (!$try) {
     echo "<p>Sorry I can’t open a file, something is wrong";
     exit;
   }
 
   // this is the stuff we get from the form, we insert it into an array
     $input = array ($login, $password, $fullname, $url, $food, $work, $love, $leisure, $sports);
   
   // so we can make a big string with tabs between the elements
     // note that we add a \n (line break) to the end of the string.
     $output_line = implode ($input,     "                            ")."\n";
 


 
   // Now open the file (get a file pointer)
     // We will append to it and therefore use the "a" option
     '''$output_stream = fopen($file_name, "a");'''
   // and dump the string into the file
     '''$result = fputs ($output_stream, $output_line);'''
   
   // give feedback
     if ($result) {
       echo "<p>Your data have successfully been registered.";
     }
   else {
     echo "<p>Too bad, the db did not want your data.";
   }
   // close the file pointer
     fclose($output_stream);
   ?>
 
 <?
   // EXIT here ... we don’t want to see the form again. If you do, kill the exit
   exit;
 }
 ?>

Remember

 fopn (<file name>, "a")
to open a file and then append.
 fputs(<handle>, “string”)
to write to a file
WARNING: This will attract spammers !!
Dump contents of a file
.... we just insert it a
 with an “include”

 
<source lang="htmlstrict">
 <BODY>
     <H1>PHP/MySQL Demo - Dump Database Contents</H1>
 
 <? 
   /* Daniel.Schneider@tecfa.unige.ch
   Will dump the contents of the results file
   */
 ?>
 
   <strong>Results registered so far:</strong>
 <pre>
 <? readfile("results/result.text"); ?>
 
..........

</BODY>

</source>


Important:

Use "readfile", and not "include" or "require", else you will get hacked !!
Other formats than HTML

Principle: in the FIRST line of your program you have to define the content-type:

example: Header("Content-type: image/gif");

Example XML

 Header("Content-type: text/xml);

Example SVG

 Header("Content-type: image/svg+xml");

Example RDF

 Header("Content-type: application/rdf+xml");
Generate some simple XML
http://tecfa.unige.ch/guides/php/examples/simple/simple-calcul-xml.php
http://tecfa.unige.ch/guides/php/examples/simple/simple-calcul-xml.phps
http://tecfa.unige.ch/guides/php/examples/simple/simple-calcul-xml.css
 <?php
 '''header("Content-type: text/xml");'''
 '''print(’<?xml version="1.0" encoding="iso-8859-1"?>’ . "\n");'''
 '''print(’<?xml-stylesheet href="simple-calcul-xml.css" type="text/css" ?>’);'''

 $leisure_satisfaction = 5; $work_satisfaction = 7;  $family_satisfaction = 8;
 $index = ($leisure_satisfaction + $work_satisfaction + $family_satisfaction) / 3 ;
 echo "'''<resultat>''' Satisfaction Index = '''$index''' '''</resultat>'''";
 ?>