Web development ... the Web development ... the server side (of the force) server side (of the force)
Fabien POULARD Fabien POULARD
Document under license Creative Commons Document under license Creative Commons
Attribution Share Alike 2.5 Attribution Share Alike 2.5
http://www.creativecommons.org/learnmore
Web development ... the server side Web development ... the server side
(of the force) (of the force)
● To take full advantage of the current slides, you To take full advantage of the current slides, you can go to :
can go to :
–
http://www.grdscarabe.net/formations/php http://www.grdscarabe.net/formations/php
Contents Contents
● Server side / Client side ... brief review of HTTPServer side / Client side ... brief review of HTTP
● PHP 4 vs. PHP 5 ... the real reasons for switchingPHP 4 vs. PHP 5 ... the real reasons for switching
● Fundamentals of PHP (language syntax)Fundamentals of PHP (language syntax)
● Execution flow controlExecution flow control
● Object oriented programmingObject oriented programming
● Interfacing with a databaseInterfacing with a database
● Interfacing with the client sideInterfacing with the client side
● Variables and constants you should knowVariables and constants you should know
● Resources ... behind this short formationResources ... behind this short formation
Server side / Client side ... brief Server side / Client side ... brief
review of HTTP review of HTTP
● Accessing a web application on the network is Accessing a web application on the network is done is several times :
done is several times :
CLIENT SIDE SERVER SIDE
1 : ask URL HTTP
Server side / Client side ... brief Server side / Client side ... brief
review of HTTP review of HTTP
● Accessing a web application on the network is Accessing a web application on the network is done is several times :
done is several times :
CLIENT SIDE SERVER SIDE
2 : get the document by eventually executing scripts
Server side / Client side ... brief Server side / Client side ... brief
review of HTTP review of HTTP
● Accessing a web application on the network is Accessing a web application on the network is done is several times :
done is several times :
CLIENT SIDE SERVER SIDE
3 : send the document
HTTP
Server side / Client side ... brief Server side / Client side ... brief
review of HTTP review of HTTP
● Accessing a web application on the network is Accessing a web application on the network is done is several times :
done is several times :
CLIENT SIDE SERVER SIDE
4 : execute eventually client scripts to display the document
Server side / Client side ... brief Server side / Client side ... brief
review of HTTP review of HTTP
● On the client side we find :On the client side we find :
–
HTML/XHTML/CSS HTML/XHTML/CSS
–
JavaScript / VBScript JavaScript / VBScript
–
Applets Java Applets Java
–
... ...
● On the server side we find :On the server side we find :
–
PHP / ASP / CGI / ... PHP / ASP / CGI / ...
–
Servlets Java Servlets Java
–
... ...
Server side / Client side ... brief Server side / Client side ... brief
review of HTTP review of HTTP
● The service scripts are executed on the server and The service scripts are executed on the server and transformed into client side languages.
transformed into client side languages.
● The execution process on the server side cannot The execution process on the server side cannot be interrupted by a client side action (except
be interrupted by a client side action (except AJAX ...)
AJAX ...)
● It is possible to send data from the server to the It is possible to send data from the server to the client before the end of the script execution,
client before the end of the script execution,
especially when the script need a long execution especially when the script need a long execution
but is able to give results along its execution but is able to give results along its execution
Server side / Client side ... brief Server side / Client side ... brief
review of HTTP review of HTTP
● In order to develop in PHP it is more than a good In order to develop in PHP it is more than a good idea to have a webserver (and databases servers idea to have a webserver (and databases servers
depending on the need) installed locally on the depending on the need) installed locally on the
computer used for the development.
computer used for the development.
● Under Windows, you can use EasyPHP to install Under Windows, you can use EasyPHP to install a complete WAMP (Windows, Apache, MySQL, a complete WAMP (Windows, Apache, MySQL,
PHP) server :
PHP) server : http://www.easyphp.org/http://www.easyphp.org/
● You will then be able to access your server at the You will then be able to access your server at the address : http://localhost
address : http://localhost
Server side / Client side ... brief Server side / Client side ... brief
review of HTTP review of HTTP
Web Server (includes PHP)
MySQL Server
PHP 4 vs. PHP 5 ... the real reasons PHP 4 vs. PHP 5 ... the real reasons
for switching for switching
● There are currently two major versions of PHP There are currently two major versions of PHP existing concurrently : PHP4 and PHP5.
existing concurrently : PHP4 and PHP5.
–
Considering the huge number of scripts in Considering the huge number of scripts in PHP4, the migration to PHP5 is very slow.
PHP4, the migration to PHP5 is very slow.
–
It is difficult to have PHP4 and PHP5 It is difficult to have PHP4 and PHP5
cohabiting on the same server, reason why cohabiting on the same server, reason why PHP5 is not yet well adopted.
PHP5 is not yet well adopted.
● However, PHP5 is mostly retrocompatible with However, PHP5 is mostly retrocompatible with PHP4, only PHP4 hacks are not compatible. So, PHP4, only PHP4 hacks are not compatible. So,
a clean PHP4 scripts will work with PHP5.
a clean PHP4 scripts will work with PHP5.
PHP 4 vs. PHP 5 ... the real reasons PHP 4 vs. PHP 5 ... the real reasons
for switching for switching
● The advantages of PHP5 over PHP4 are :The advantages of PHP5 over PHP4 are :
–
the interpreter (Zend Engine 2.0) is way the interpreter (Zend Engine 2.0) is way faster and so the scripts are executed in faster and so the scripts are executed in less time, consuming less resource on the less time, consuming less resource on the server side
server side
–
PHP5 supports a larger number of PHP5 supports a larger number of databases (MySQL5, SQLite, ...) databases (MySQL5, SQLite, ...)
–
The PHP5 object programming handling is The PHP5 object programming handling is more evolved than the one from PHP4 and more evolved than the one from PHP4 and provides a syntax close to Java/C++
provides a syntax close to Java/C++
–
PHP5 integrates an exception model such PHP5 integrates an exception model such that you can throw and catch exceptions.
that you can throw and catch exceptions.
Fundamentals of PHP Fundamentals of PHP
(language syntax) (language syntax)
● The syntax is similar to C, proof is that most of PHP The syntax is similar to C, proof is that most of PHP developers use their editor in C-mode when they
developers use their editor in C-mode when they develop in PHP.
develop in PHP.
● A bloc script starts with “A bloc script starts with “<?php<?php” and ends with “” and ends with “?>?>””
● ““/* *//* */” and “” and “////” delimit comments” delimit comments
● Each instruction ends with a semi-colon : “Each instruction ends with a semi-colon : “;;””
<?php
/* A comment spreaded out on * several lines in the file
*/
echo “Hello World”; // a comment on one line ?>
Fundamentals of PHP Fundamentals of PHP
(language syntax) (language syntax)
● Variables MUST start with a dollar “Variables MUST start with a dollar “$$””
● There is no need to declare the variables and all the There is no need to declare the variables and all the variables (except $this) are mutable (no fixed type) variables (except $this) are mutable (no fixed type)
● You do not have to take care of the memory, PHP will You do not have to take care of the memory, PHP will unset the variables by itself
unset the variables by itself
<?php
/* Assign the string “Hello World” to * the variable
*/
$var = “Hello World”;
echo '$var'; // will output $var
echo “$var”; // will output Hello World echo $var; // will output Hello World ?>
Fundamentals of PHP Fundamentals of PHP
(language syntax) (language syntax)
● By default the variables are set to NULL which By default the variables are set to NULL which is equivalent to 0 or to the empty string.
is equivalent to 0 or to the empty string.
● Arrays are declared implicitly with the Arrays are declared implicitly with the constructor “
constructor “array()”array()” or explicitly by using “ or explicitly by using “[][]””
<?php
$var = “Hello World”; // $var is a string
$var = array(); // $var has mutated to an array $n; // $n is a variable with value NULL
$n[] = 3; // $n is an array with one row $n[] = 4;
print_r($n); // Array ( [0] => 3 [1] => 4) ?>
Fundamentals of PHP Fundamentals of PHP
(language syntax) (language syntax)
● Variables are available only in their scope !Variables are available only in their scope !
● The scope of a variable declared outside any The scope of a variable declared outside any function/class bloc is global. Otherwise it is function/class bloc is global. Otherwise it is
local.
local.
● The keyword The keyword “global” “global” indicates to consider the indicates to consider the global value identified by the name in parameter.
global value identified by the name in parameter.
<?php
$var = “Hello World”; // $var is global function dummy() {
$var = 10; // $var has a local scope echo $var; // 10
global $var; // now we consider the global echo $var; // Hello World
} ?>
Fundamentals of PHP Fundamentals of PHP
(language syntax) (language syntax)
● Blocs begin with an open bracket “Blocs begin with an open bracket “{{“ and end “ and end with a closing bracket “
with a closing bracket “}}””
● Functions are declared using the keyword Functions are declared using the keyword
““functionfunction” and their result is returned with the ” and their result is returned with the keyword “
keyword “returnreturn””
<?php
/* a function returning “Hello World” */
function hello() {
return “Hello World”;
}
echo hello(); // will output Hello World echo “hello()”; // will output hello()
?>
Fundamentals of PHP Fundamentals of PHP
(language syntax) (language syntax)
● As C, PHP uses only functions. However, it is As C, PHP uses only functions. However, it is possible to declare a function that returns
possible to declare a function that returns nothing.
nothing.
● By default, the parameters are passed by copy. In By default, the parameters are passed by copy. In order to pass them by reference, the parameter order to pass them by reference, the parameter
must be preceded by a “
must be preceded by a “&&”.”.
<?php
function silly($param1, &$param2) {
$param1 = 10; // modification in local scope $param2 = 10; // modification of the original }
$var1=0; $var2=0;
silly($var1, $var2);
echo “$var1 , $var2”; // will output 0 , 10 ?>
Fundamentals of PHP Fundamentals of PHP
(language syntax) (language syntax)
● PHP has a lot of functions already implemented PHP has a lot of functions already implemented that can help you. You fill find an exhaustive list that can help you. You fill find an exhaustive list
of these functions at : of these functions at :
http://www.php.net/manual/en/funcref.php http://www.php.net/manual/en/funcref.php
Execution flow control Execution flow control
● There are two types of conditions control : There are two types of conditions control : if if and and switch
switch
<?php
if (condition1) {
// executed if condition1 is true } elseif (condition2) {
// executed if condition1 is false and // if condition 1 is true
} else {
// executed if condition1 and condition2 // are both false
} ?>
Execution flow control Execution flow control
<?php
switch ($variable) { case value1 :
// executed if $variable = value1 break; // necessary
case value2 :
// executed if $variable = value2 break; // necessary
default :
// executed if no value found equal }
?>
Execution flow control Execution flow control
● Available loops are Available loops are whilewhile,, do while do while,, for for andand foreach
foreach
<?php
while (condition) {
// execution while the condition is true }
do {
// execution at least once and then as long // as the condition is true
} while (condition);
?>
Execution flow control Execution flow control
<?php
// initial is evaluated once at the beginning for (initial ; condition ; step) {
// executed until the condition is false
// at the end of each loop, step is executed }
foreach( $array as $index => $value) { // executed for each entry of the array // with access to the index as variable
// $index and the value as variable $value }
?>
Execution flow control Execution flow control
<?php
/* Example of simple loop to print the content of an array */
$arr = array('dog', 'cat', 'fish');
foreach( $arr as $value) { if ($value != “cat”)
echo $value.”<br/>”;
else
echo “Mawww<br/>”;
}
/* result : * dog
* Mawww * fish
*/
?>
Object oriented programming ...
Object oriented programming ...
PHP4 PHP4
● The object model of PHP is based, as C++, Java, The object model of PHP is based, as C++, Java, ..., on classes.
..., on classes.
● A class is a collection of attributes and methods A class is a collection of attributes and methods without any protection system. Everything in a without any protection system. Everything in a
class is public.
class is public.
● The attributes are variables that share the same The attributes are variables that share the same properties as any PHP variable.
properties as any PHP variable.
● The methods are functions that share the same The methods are functions that share the same properties as any PHP function.
properties as any PHP function.
● A special variable A special variable $this $this represents the current represents the current object. A bug in PHP4 makes this variable
object. A bug in PHP4 makes this variable mutable ... but it should not be the case.
mutable ... but it should not be the case.
<?php
/* A class representing a chicken ... original */
class chicken { var $weight;
var $age;
/* the constructor is a function with the same name as the class. There is no destructor. */
function chicken($age, $weight) { $this->weight = $weight;
$this->age = $age;
}
function cook() {
if ($this->age > 3 || $this->weight > 3) echo “Hmm ... delicious”;
else
echo “Not ready to be cooked !”;
} }
?>
Object oriented programming ...
Object oriented programming ...
PHP4 PHP4
● The constructor is implemented as a method with The constructor is implemented as a method with the same name as the name of the class it is
the same name as the name of the class it is supposed to build.
supposed to build.
● There is no destructor.There is no destructor.
● The only object oriented functionalities The only object oriented functionalities
implemented in PHP4 are the inheritance, and implemented in PHP4 are the inheritance, and
the methods redefinition.
the methods redefinition.
● inheritance :inheritance : a class inherits attributes and a class inherits attributes and methods from its parent.
methods from its parent.
● method redefinition :method redefinition : a child redefines the a child redefines the method it has inherited from its parent.
method it has inherited from its parent.
<?php
/* A class representing a coffee recipient */
class coffee_recipient { function fill() {
echo “You fill the recipient !”;
} }
/*Child of coffee_recipient that does not redefine the method fill */
class cup extends coffee_recipient { }
/*Child of coffee_recipient that does redefine the method fill */
class mug extends coffee_recipient { function fill() {
echo “Hop ... do not forget the cover!”;
} }
?>
Object oriented programming Object oriented programming
● Sometimes you want to access a class method Sometimes you want to access a class method without instantiated an object. You can use the without instantiated an object. You can use the
scope resolution operator “
scope resolution operator “::::”.”.
● You can also use the scope resolution operator to You can also use the scope resolution operator to call a function from your ancestors that you have call a function from your ancestors that you have
redefined. In the particular case of you direct redefined. In the particular case of you direct
parent, you can use “
parent, you can use “parent::parent::””
● Important Note (maybe to much hacking) :Important Note (maybe to much hacking) : the the function
function newnew used to instantiate objects from a used to instantiate objects from a class returns a copy of the object, not a reference.
class returns a copy of the object, not a reference.
<?php
/*Child of coffee_recipient that does redefine the method fill */
class mug extends coffee_recipient { function fill() {
echo “Hop ... do not forget the cover!”;
parent::fill();
} }
/* call the method fill from no object */
coffee_recipient::fill(); // “You fill the recipient !”
/* create an object mug now */
$obj = new mug();
$obj->fill(); // “Hop...do not forget the cover!”
// “You fill the recipient !”
?>
Object oriented programming Object oriented programming
● PHP5 introduces new constructors and PHP5 introduces new constructors and destructors :
destructors :
–
__construct() __construct()
–
__destruct() __destruct()
● Apparition of visibility keywords : Apparition of visibility keywords : publicpublic, , private
private and and protectedprotected that can be used like in that can be used like in Java.
Java.
● Introduction of keywords Introduction of keywords staticstatic and and abstractabstract..
● Possibility to overload the functions Possibility to overload the functions __get__get, , __set
__set, __call, __call, __isset, __isset and and __unset__unset. However, to . However, to understand those you need a good understanding understand those you need a good understanding
of the PHP core.
of the PHP core.
Interfacing with a database Interfacing with a database
● PHP is extensible with modules that can be PHP is extensible with modules that can be
included at compilation time. Therefore you can included at compilation time. Therefore you can access almost any existing database with PHP if access almost any existing database with PHP if
you include the right module at compilation time.
you include the right module at compilation time.
● Most likely, those databases will be available :Most likely, those databases will be available :
–
MySQL MySQL
–
PostgreSQL PostgreSQL
–
Oracle Oracle
● Using directly the functions for those database Using directly the functions for those database give you the best handling on it. However, most give you the best handling on it. However, most
of the time you do not need it.
of the time you do not need it.
Interfacing with a database Interfacing with a database
● PEAR (pear.php.net) is a collection of php libraries PEAR (pear.php.net) is a collection of php libraries under BSD licenses implementing almost all the basic under BSD licenses implementing almost all the basic
feature you may need in a project.
feature you may need in a project.
● In the particular case you want to abstract your database In the particular case you want to abstract your database such that your application can work on any database
such that your application can work on any database available, you should use the excellent
available, you should use the excellent MDB2MDB2 : :
–
http://pear.php.net/package/MDB2 http://pear.php.net/package/MDB2
–
http://pear.php.net/package/MDB2_Driver_mysql http://pear.php.net/package/MDB2_Driver_mysql (MySQL driver)
(MySQL driver)
Interfacing with a database Interfacing with a database
● In order to use a PEAR package, you have to install In order to use a PEAR package, you have to install PEAR on your system and update some php
PEAR on your system and update some php configuration to take care of them.
configuration to take care of them.
● For those who have the good idea to use a Linux (or For those who have the good idea to use a Linux (or BSD) Distribution, just use your package manager to BSD) Distribution, just use your package manager to
install PEAR.
install PEAR.
–
Debian : apt-get install PEAR-MDB2 Debian : apt-get install PEAR-MDB2
–
Gentoo : emerge PEAR-MDB2 Gentoo : emerge PEAR-MDB2
–
... ...
● For those still using Windows, you can find some For those still using Windows, you can find some information :
information :
–
http://pear.php.net/manual/en/faq.windows.php http://pear.php.net/manual/en/faq.windows.php
–
http://builder.com.com/5100-6371-5163311.html http://builder.com.com/5100-6371-5163311.html
Interfacing with a database Interfacing with a database
<?php
/* --- SET THE PATH TO FIND MDB2 --- */
ini_set('include_path', '/path/to/pear/directory'
. PATH_SEPARATOR . ini_get('include_path'));
$dsn = “mysql://login:pass@localhost/db”;
$db = &MDB2::factory($dsn);
$c = $db->exec(“DELETE FROM table”);
echo “$c rows deleted !”;
$res = $db->queryAll(“SELECT * FROM table”);
print_r($res);
$db->disconnect();
?>
Interfacing with the client side Interfacing with the client side
● HTTP is (was) a non connected protocol, there is HTTP is (was) a non connected protocol, there is no synchrony operations between the server side no synchrony operations between the server side and the client side. Each one acts independently and the client side. Each one acts independently
from the other.
from the other.
● However, the client and the server exchange However, the client and the server exchange some data.
some data.
–
POST and GET data POST and GET data
● Moreover the server and the clients are able to Moreover the server and the clients are able to remember informations about a specific client remember informations about a specific client
from one time to another.
from one time to another.
–
cookies and sessions cookies and sessions
Interfacing with the client side Interfacing with the client side
POST and GET data POST and GET data
● The main way of a client to interact with a server The main way of a client to interact with a server is to use forms. Those one can send the
is to use forms. Those one can send the
information to the server through different information to the server through different
methods : methods :
–
GET : the information is encoded in the GET : the information is encoded in the URL. For example :
URL. For example :
● www.google.com/search?hl=en&q=phpwww.google.com/search?hl=en&q=php
–
POST : the information is sent to the POST : the information is sent to the server in an “hidden” (different from server in an “hidden” (different from secure) way.
secure) way.
Interfacing with the client side Interfacing with the client side
POST and GET data POST and GET data
● The form is defined on the client side, in HTML :The form is defined on the client side, in HTML :
<form name=”dum” action=”index.php” method=”POST”>
<input type=”text” name=”id”>
<input type=”submit”>
</form>
method to use to send the form script that will
receive the data name used to identify
the data on the server side button to send the
form to the server
Interfacing with the client side Interfacing with the client side
POST and GET data POST and GET data
● On the server side, the script receives the data by On the server side, the script receives the data by special variables :
special variables :
<?php
// file index.php that receives the script /* check the value to validate the user */
if ( $_POST['id'] == “admin”) echo “Access granted”;
else
echo “Access denied !”;
?>
name of the field sent determined by
the method used
Interfacing with the client side Interfacing with the client side
POST and GET data POST and GET data
● In the case the method GET is used, the principle In the case the method GET is used, the principle is identical. But instead of the variable $_POST, is identical. But instead of the variable $_POST,
we will retrieve the data from the variable we will retrieve the data from the variable
$_GET.
$_GET.
● Moreover, as the data for the GET method is Moreover, as the data for the GET method is passed directly by the URL, it is possible to passed directly by the URL, it is possible to
format URL to send the data without needing format URL to send the data without needing
forms forms
<!-- this is my menu -->
<a href=”my_script.php?action=home”>Home</a><br/>
<a href=”my_script.php?action=forum”>Forums</a><br/>
<a href=”my_script.php?action=contact”>Contacts</a><br/>
Client Side
<?php // this is my_script.php switch ($_GET['action']) { case 'home' :
launch_home_interface();
break;
case 'forum' :
launch_forum_interface();
break;
case 'contact' :
launch_contact_interface();
break;
default :
echo “I cannot understand your request!”;
}
?>
Server Side
Variables and constants you should Variables and constants you should
know know
● $_SERVER $_SERVER : indexed array with a lot of information : indexed array with a lot of information about the server :
about the server :
– HTTP_HOSTHTTP_HOST : domain name : domain name
– HTTP_USER_AGENTHTTP_USER_AGENT : identifier of the client that : identifier of the client that sent the request
sent the request
– SERVER_ADDRSERVER_ADDR : address of the server on the : address of the server on the network
network
– DOCUMENT_ROOT : root directory where the DOCUMENT_ROOT : root directory where the scripts are located
scripts are located
– REQUEST_METHODREQUEST_METHOD : indicates the request method : indicates the request method used (GET or POST).
used (GET or POST).
– PHP_SELFPHP_SELF : location of the script from the root : location of the script from the root directory
directory
Variables and constants you should Variables and constants you should
know know
● $_POST$_POST : array indexed by the names of the : array indexed by the names of the elements of a form sent by a POST method.
elements of a form sent by a POST method.
● $_GET $_GET : array indexed by the names of the : array indexed by the names of the elements of a form sent by a GET method.
elements of a form sent by a GET method.
● __FILE____FILE__ : constant which value corresponds to : constant which value corresponds to the current name and location of the file
the current name and location of the file executed. You can use this constant in executed. You can use this constant in
combination with the function
combination with the function dirname()dirname() to get to get the location of the current script.
the location of the current script.
● __LINE____LINE__ : current line (useful when something : current line (useful when something goes wrong on you need details)
goes wrong on you need details)
● __CLASS____CLASS__ : name of the current class : name of the current class
Resources ... behind this short Resources ... behind this short
formation formation
● The reference : The reference : http://www.php.nethttp://www.php.net
● Others tutorials :Others tutorials :
–
http://www.php-mysql-tutorial.com/ http://www.php-mysql-tutorial.com/
–
http://www.w3schools.com/php/ http://www.w3schools.com/php/
–
http://www.freewebmasterhelp.com/tutorials/php http://www.freewebmasterhelp.com/tutorials/php
● Coding ... coding ... and coding ! There is no secret, the Coding ... coding ... and coding ! There is no secret, the only way to progress is to get experience.
only way to progress is to get experience.
● Do not hesitate to ask for help on specialized lists :Do not hesitate to ask for help on specialized lists :
–
comp.lang.php comp.lang.php
–
alt.php alt.php
–