From Edutechwiki - Reading time: 16 minPHP standards for Hypertext Preprocessor
History:
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:
Purpose:
Links:
PHP features
Availability:
Installation:
Highlights:
Alternatives to PHP:
HTML and PHP integration
PHP code is defined within an XML processing instruction
<?php ..... ?>
For example:
<?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("style.php");
Require:
inserts content of file when the php file is loaded
require("my_functions.inc");
Variant (recommended):
include_once() and require_once().
Only include once, will make your application faster.
File inclusion example
<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>
PHP syntax overview:
PHP looks like "C" (C, C++, Java, Perl, etc.)
Variables are “containers” for information.
Principle:
$variable = "content" ;
Illustrations:
$a = 10; $name = "Patrick Ott"; $sum = 123.456;
Using variables with content strings example:
<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>
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
<?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.";
?>
$fruits = array(
"fruits" => array("a"=>"orange","b"=>"banana","c"=>"apple"),
"numbers" => array(1, 2, 3, 4, 5, 6)
"holes" => array("first", 5 => "second", "third")
);
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 are "variables" with information that cannot change.
define(<NAME>, <value>);
Examples:
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.
Like normal math ...
Example:
$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;
For 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!";
You can use parenthesis if you like to group operators !
Some simple comparisons:
$a = "Migros";
$b = "Coop";
$result = $a==$b;
$result2 = $a > $b;
$result3 = $result==TRUE;
echo "Result One = $result. Result TWO = $result2. Result THREE = $result3.";
(Conditions and tests)
Principle (several typical situations):
"IF" (several variants)
explanations:
Execution model:
Simple "if" example (comparison)
Compares two numbers: $a and $b, and displays a message.
<?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 contructs:
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).
Principle: "Hey, take that information, do something and (maybe) return the result"
Usually, you will find function definition in the beginning of a program (or within include files)

Color mixing for paint example
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 example:
<?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>";
?>
The "for loop" syntax
FOR (expr1; expr2; expr3) statement
Love generation example:
for ($i=1; $i<=10; $i++) {
print "I love you so ! "; }
Result:
I love you so ! I love you so ! I love you so ! I love you so ! I love you so ! I love you so ! ......
Here is a slightly more complex one:
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:
Generation of html tables example
$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:
(1) Look at the generated HTML code "View Source")
(2) Insert phpinfo() in your PHP file (will give you lots of information, e.g. about PHP installation, its environment, variables passed to script from the server, etc.)
phpinfo();
(3) Insert print statements!
echo "DEBUG: \$var = $var";
echo "TEST: var = $var";
(4) Raise "error reporting" to its maximum ! Insert this on top:
error_reporting(E_ALL);
(5) Know where your server / php log files are
In some configurations, php error messages and notices are not displayed on the rendered web page. You will have to find these in the log files or the server. Check the settings of the php.ini file to find out.
(6) Portals
Warning: NEVER insert blank lines at start or end of a file ! Most files should stop like this (no line feed !!)
?>
Simple quiz and POST to a php file
This example shows:
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>
Retrieve values of an HTML form
Data from a form a stored by the server in a so-called super global variables
Use $_POST to deal with POST variables
Use $_GET for GET variables
You can use the "name" attribute of the form to retrieve values
In our example, we use $_POST:
$choice = $_POST['choice'];
$choice2 = $_POST['choice2'];
We now have two PHP variables: $choice and $choice2
Computing and display of results
We add the the two values and compute a summary 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 "<h3>Votre score is de " . $score . "</h3>";
if ($score < 3) {
echo "<p>Vous êtes un débutant</p>";
} elseif ($score < 5) {
echo "<p>Vous avez un niveau moyen</p>";
} else {
echo "<p>Vous êtes un expert !</p>";
}
?>
Inhibit direct access to PHP (without data)
(Checkboxes with PHP - arrays)
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> </td></tr></table>
<input type="checkbox" name="choice[]" value="Blue">Blue
<table bgcolor="blue" width="50"><tr><td> </td></tr></table>
<input type="checkbox" name="choice[]" value="Green">Green
<table bgcolor="green" width="50"><tr><td> </td></tr></table>
.....
<input type="checkbox" name="choice[]" value="Black">Black
<table bgcolor="black" width="50"><tr><td> </td></tr></table>
<input type="submit" value="Voir le result!">
</form>
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] - ");
}
}
?>
You can put both the form and the processing code in a single php page. In this case, test if the file is called with data from a form or through a link/a navigator. See the variable$process below
<?php
if (!isset($_POST['process'])) {
?>
//... lets display the form)
<FORM METHOD="POST" ACTION="<? echo $PHP_SELF ?>">
</FORM>
<?php
} else {'''
//... we got data, so let’s process
}
?>
To test if we have all the POST/GET variables, we may use two methods to see what we have in $_POST or $_GET:
if (array_key_exists('first', $_POST)) { .... do something ...};
if (isset($POST['first']) ) { .... do ....}
The difference is that:
ATTENTION, to test <input type="text"> you also may want to test if there is an empty string.
if (empty ($input) ) { ... complain ... } else { ... do ...}
PHP has session support (can keep variables over a whole user session).
Restrict repetitive access to a page example:
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
This is a simple code that shows how to collect survey data.
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")
fputs(<handle>, “string”)
Dump contents of a file
.... we just insert it a
with an “include”
<source lang="html4strict">
<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:
PHP supports any other format. By default a PHP script starts creating an HTML script as soon as it encounters and HTML section or an echo/print/etc. instruction.
Principle: Before any other output in your program, you have to define the content-type (e.g. put this into the first line).
Example binary pictures
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 example
<?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>";
?>