Web development... the server side (of the force) Fabien POULARD Document under license Creative Commons Attribution Share Alike 2.5 http://www.creativecommons.org/learnmore
Web development... the server side (of the force) To take full advantage of the current slides, you can go to : http://www.grdscarabe.net/formations/php
Contents Server side / Client side... brief review of HTTP PHP 4 vs. PHP 5... the real reasons for switching Fundamentals of PHP (language syntax) Execution flow control Object oriented programming Interfacing with a database Interfacing with the client side Variables and constants you should know Resources... behind this short formation
Server side / Client side... brief review of HTTP Accessing a web application on the network is done is several times : CLIENT SIDE SERVER SIDE HTTP 1 : ask URL
Server side / Client side... brief review of HTTP Accessing a web application on the network is done is several times : CLIENT SIDE SERVER SIDE 2 : get the document by eventually executing scripts
Server side / Client side... brief review of HTTP Accessing a web application on the network is done is several times : CLIENT SIDE SERVER SIDE 3 : send the document HTTP
Server side / Client side... brief review of HTTP Accessing a web application on the network is done is several times : CLIENT SIDE SERVER SIDE 4 : execute eventually client scripts to display the document
Server side / Client side... brief review of HTTP On the client side we find : HTML/XHTML/CSS JavaScript / VBScript Applets Java... On the server side we find : PHP / ASP / CGI /... Servlets Java...
Server side / Client side... brief review of HTTP The service scripts are executed on the server and transformed into client side languages. The execution process on the server side cannot be interrupted by a client side action (except AJAX...) It is possible to send data from the server to the client before the end of the script execution, especially when the script need a long execution but is able to give results along its execution
Server side / Client side... brief review of HTTP In order to develop in PHP it is more than a good idea to have a webserver (and databases servers depending on the need) installed locally on the computer used for the development. Under Windows, you can use EasyPHP to install a complete WAMP (Windows, Apache, MySQL, PHP) server : http://www.easyphp.org/ You will then be able to access your server at the address : http://localhost
Server side / Client side... brief review of HTTP Web Server (includes PHP) MySQL Server
PHP 4 vs. PHP 5... the real reasons for switching There are currently two major versions of PHP existing concurrently : PHP4 and PHP5. Considering the huge number of scripts in PHP4, the migration to PHP5 is very slow. It is difficult to have PHP4 and PHP5 cohabiting on the same server, reason why PHP5 is not yet well adopted. However, PHP5 is mostly retrocompatible with PHP4, only PHP4 hacks are not compatible. So, a clean PHP4 scripts will work with PHP5.
PHP 4 vs. PHP 5... the real reasons for switching The advantages of PHP5 over PHP4 are : the interpreter (Zend Engine 2.0) is way faster and so the scripts are executed in less time, consuming less resource on the server side PHP5 supports a larger number of databases (MySQL5, SQLite,...) The PHP5 object programming handling is more evolved than the one from PHP4 and provides a syntax close to Java/C++ PHP5 integrates an exception model such that you can throw and catch exceptions.
Fundamentals of PHP (language syntax) The syntax is similar to C, proof is that most of PHP developers use their editor in C-mode when they develop in PHP. A bloc script starts with <?php <?php and ends with?>?> /* */ and // // delimit comments 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 (language syntax) Variables MUST start with a dollar $ There is no need to declare the variables and all the variables (except $this) are mutable (no fixed type) You do not have to take care of the memory, PHP will 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 (language syntax) By default the variables are set to NULL which is equivalent to 0 or to the empty string. Arrays are declared implicitly with the constructor array() 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 (language syntax) Variables are available only in their scope! The scope of a variable declared outside any function/class bloc is global. Otherwise it is local. The keyword global indicates to consider the 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 (language syntax) Blocs begin with an open bracket { and end with a closing bracket } Functions are declared using the keyword function and their result is returned with the keyword return return <?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 (language syntax) As C, PHP uses only functions. However, it is possible to declare a function that returns nothing. By default, the parameters are passed by copy. In order to pass them by reference, the parameter 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 (language syntax) PHP has a lot of functions already implemented that can help you. You fill find an exhaustive list of these functions at : http://www.php.net/manual/en/funcref.php
Execution flow control There are two types of conditions control : if and 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 <?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 Available loops are while, do while, for and 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);?>
<?php Execution flow control // 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 }?>
?> <?php Execution flow control /* 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... PHP4 The object model of PHP is based, as C++, Java,..., on classes. A class is a collection of attributes and methods without any protection system. Everything in a class is public. The attributes are variables that share the same properties as any PHP variable. The methods are functions that share the same properties as any PHP function. A special variable $this represents the current object. A bug in PHP4 makes this variable 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... PHP4 The constructor is implemented as a method with the same name as the name of the class it is supposed to build. There is no destructor. The only object oriented functionalities implemented in PHP4 are the inheritance, and the methods redefinition. inheritance : a class inherits attributes and methods from its parent. method redefinition : a child redefines the 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 Sometimes you want to access a class method without instantiated an object. You can use the scope resolution operator :: ::. You can also use the scope resolution operator to call a function from your ancestors that you have redefined. In the particular case of you direct parent, you can use parent:: parent:: Important Note (maybe to much hacking) : the function new used to instantiate objects from a 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 PHP5 introduces new constructors and destructors : construct() destruct() Apparition of visibility keywords : public, private and protected that can be used like in Java. Introduction of keywords static and abstract. Possibility to overload the functions get, set, call, isset and unset.. However, to understand those you need a good understanding of the PHP core.
Interfacing with a database PHP is extensible with modules that can be included at compilation time. Therefore you can access almost any existing database with PHP if you include the right module at compilation time. Most likely, those databases will be available : MySQL PostgreSQL Oracle Using directly the functions for those database give you the best handling on it. However, most of the time you do not need it.
Interfacing with a database PEAR (pear.php.net) is a collection of php libraries under BSD licenses implementing almost all the basic feature you may need in a project. In the particular case you want to abstract your database such that your application can work on any database available, you should use the excellent MDB2 : http://pear.php.net/package/mdb2 http://pear.php.net/package/mdb2_driver_mysql (MySQL driver)
Interfacing with a database In order to use a PEAR package, you have to install PEAR on your system and update some php configuration to take care of them. For those who have the good idea to use a Linux (or BSD) Distribution, just use your package manager to install PEAR. Debian : apt-get install PEAR-MDB2 Gentoo : emerge PEAR-MDB2... For those still using Windows, you can find some information : http://pear.php.net/manual/en/faq.windows.php http://builder.com.com/5100-6371-5163311.html
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 HTTP is (was) a non connected protocol, there is no synchrony operations between the server side and the client side. Each one acts independently from the other. However, the client and the server exchange some data. POST and GET data Moreover the server and the clients are able to remember informations about a specific client from one time to another. cookies and sessions
Interfacing with the client side POST and GET data The main way of a client to interact with a server is to use forms. Those one can send the information to the server through different methods : GET : the information is encoded in the URL. For example : www.google.com/search?hl=en&q=php POST : the information is sent to the server in an hidden (different from secure) way.
Interfacing with the client side POST and GET data The form is defined on the client side, in HTML : button to send the script that will form to the server receive the data name used to identify method to use to the data on send the form the server side <form name= dum action= index.php method= POST > <input type= text name= id > <input type= submit > </form>
Interfacing with the client side POST and GET data On the server side, the script receives the data by special variables : determined by the method used name of the field sent <?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! ;?>
Interfacing with the client side POST and GET data In the case the method GET is used, the principle is identical. But instead of the variable $_POST, we will retrieve the data from the variable $_GET. Moreover, as the data for the GET method is passed directly by the URL, it is possible to format URL to send the data without needing forms
Client Side <!-- 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/> Server 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! ; }?>
Variables and constants you should know $_SERVER : indexed array with a lot of information about the server : HTTP_HOST : domain name HTTP_USER_AGENT : identifier of the client that sent the request SERVER_ADDR : address of the server on the network DOCUMENT_ROOT : root directory where the scripts are located REQUEST_METHOD : indicates the request method used (GET or POST). PHP_SELF : location of the script from the root directory
Variables and constants you should know $_POST : array indexed by the names of the elements of a form sent by a POST method. $_GET : array indexed by the names of the elements of a form sent by a GET method. FILE : constant which value corresponds to the current name and location of the file executed. You can use this constant in combination with the function dirname() to get the location of the current script. LINE : current line (useful when something goes wrong on you need details) CLASS : name of the current class
Resources... behind this short formation The reference : http://www.php.net Others tutorials : http://www.php-mysql-tutorial.com/ http://www.w3schools.com/php/ http://www.freewebmasterhelp.com/tutorials/php Coding... coding... and coding! There is no secret, the only way to progress is to get experience. Do not hesitate to ask for help on specialized lists : comp.lang.php alt.php alt.comp.lang.php