Php5
Upcoming SlideShare
Loading in...5
×
 

Php5

on

  • 5,667 views

Designing Web Applications with PHP5, MySQL and MVC Architecture

Designing Web Applications with PHP5, MySQL and MVC Architecture

Statistics

Views

Total Views
5,667
Views on SlideShare
5,507
Embed Views
160

Actions

Likes
0
Downloads
91
Comments
0

5 Embeds 160

http://www.csesalford.com 137
http://www.slideshare.net 9
http://www.weebly.com 6
http://smartdesign21989.weebly.com 6
url_unknown 2

Accessibility

Categories

Upload Details

Uploaded via as Microsoft Word

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

Php5 Php5 Document Transcript

  • PHP 5Prepared by : Dave Parkinson Rick Ogden www.webdesigninfo.co.uk (September 2011)
  • PHP5 Page 2 PHP 5 CONTENTSChapter 1 : Introduction to PHP .............................................................................................. 41.1 Introduction to PHP ....................................................................................................................... 4Chapter 2 : PHP ........................................................................................................................ 52.1 Your Development Environment ................................................................................................... 52.2 Your Development Tools ................................................................................................................ 82.3 Exercise 1 - Your First PHP Script (HelloWorld)...................................................................... 10 2.3.1 Analysis of your first PHP Script ............................................................................................................. 11 2.3.2 Sending Data to the Browser .................................................................................................................... 11 2.3.3 Comments in PHP code ............................................................................................................................ 122.4 Datatypes ....................................................................................................................................... 14 2.4.1 Scalar Datatypes ....................................................................................................................................... 14 2.4.2 Compound Datatypes .............................................................................................................................. 142.5 Variables ........................................................................................................................................ 15 2.5.1 Naming Variables ..................................................................................................................................... 16 2.5.2 Declaring Variables .................................................................................................................................. 16 2.5.3 Type Casting in PHP ................................................................................................................................ 18 2.5.4 Constants .................................................................................................................................................. 182.6 Communicating with the User ..................................................................................................... 19 2.6.1 Form Elements ......................................................................................................................................... 19 2.6.2 Submitting your Form .............................................................................................................................. 20 2.6.3 Gathering Information from a Form ......................................................................................................... 20 2.6.4 Exercise 2 (PassingData) .......................................................................................................................... 21 2.6.5 Gathering data from other Form Elements ............................................................................................... 222.7 Programming in PHP ................................................................................................................... 23 2.7.1 PHP Operators .......................................................................................................................................... 23 2.7.2 PHP Control Structures ............................................................................................................................ 25 2.7.3 PHP Functions .......................................................................................................................................... 262.8 Object Orientated Programming with PHP ............................................................................... 26 2.8.1 Classes and Objects .................................................................................................................................. 27 2.8.2 Using Object Orientation .......................................................................................................................... 28 2.8.3 Including a Class ...................................................................................................................................... 312.9 MVC ............................................................................................................................................... 32 2.9.1 Exercise 3 – A Template for a PHP Web Site using MVC ...................................................................... 332.10 Exercise 4 – A Simple Conversion Program ............................................................................. 372.11 Exercise 5 – A Simple Calculator .............................................................................................. 41 2.11.1 Using the Debugger in Net Beans .......................................................................................................... 42 2.11.2 var_dump Function ................................................................................................................................. 442.12 Maintaining Information on the Web ....................................................................................... 45 2.12.1 Using Cookies ........................................................................................................................................ 45 2.12.2 Using Session Variables ......................................................................................................................... 46 2.12.3 Exercise 6 – Writing and Reading Cookies & Session Variables .......................................................... 47 2.12.4 Query String ........................................................................................................................................... 51 2.12.5 Exercise 7 – Passing data between PHP pages ...................................................................................... 51Chapter 3 : MySQL ................................................................................................................. 543.1 Introduction ................................................................................................................................... 54Dave Parkinson
  • PHP5 Page 33.2 Creating a database using phpMyAdmin ................................................................................... 543.3 Using PHP with MySQL............................................................................................................... 57 3.3.1 Setting up and tearing down the connection ............................................................................................. 573.4 Interacting with the Database ...................................................................................................... 58 3.4.1 Structured Query Language ...................................................................................................................... 583.5 Exercise 8 - Reading data from a MySQL Database ................................................................ 613.6 Exercise 9 – Inserting, Updating and Deleting Records in a Database ................................... 673.7 Passing Data from a Database to a PHP Page ........................................................................... 71 3.7.1 Exercise 10 – Passing Information from a MySQL Database .................................................................. 713.8 Exercise 11 – Displaying Pictures from a MySQL Database ................................................... 72Dave Parkinson
  • PHP5 Page 4 Chapter 1 : Introduction to PHP1.1 Introduction to PHP PHP originally stood for „Personal Home Page‟ when it was created in 1994 by Rasmus Lerdorf. As its usefulness and capabilities grew it came to mean PHP:Hypertext Preprocessor. According to the official web site www.php.net , PHP is „an HTML embedded scripting language‟. In many ways it is very similar to Microsoft ASP scripting language, and it offers virtually identical programming capability. PHP is a widely-used general-purpose scripting language that is especially suited for Web development and can be embedded into HTML. Since its inception PHP has seen an exponential growth in its usage with PHP being deployed on over 20 million sites worldwide. PHP is used on a similar number of sites to ASP. PHP usually runs on a UNIX or LINUX operating system but a number of Windows web hosting companies (e.g. Crystal Tech) offer PHP emulation on their Windows servers.Dave Parkinson
  • PHP5 Page 5 Chapter 2 : PHP2.1 Your Development Environment PHP pages are simply text files on the web server. To create an PHP page all you really need is a text editor such as Notepad. However as you will need to add your PHP code to HTML code, debug the PHP code locally on your PC, and upload your code to a web server then it makes sense to use an Integrated Development Environment. In this module we will be using the Net Beans IDE. In addition in order to run your code locally on your PC we will be using XAMPP for Windows. XAMPP is an easy to install Apache Web Server distribution containing MySQL, PHP and Perl. All these products are Open Source and free to install. We will be setting up our development environment on a pen drive with 1 Mb of free memory available (alternatively you could set up on the D: drive on the lab PC‟s -note the environment is too large to fit on the F: drive). In order to run PHP programs locally on our PC we need to install a web server. The best options for this are either to install Microsoft‟s Information Server (IIS) or to install the Apache Web Server (Open Source). Whichever web server we choice we also need to install a PHP interpreter. Most PHP programmes need to access a database (usually MySQL). It is often useful to install MySQL locally on your PC to enable you to fully test your application without being connected to the web. XAMPP is a free and open source cross-platform web server package, consisting mainly of the Apache HTTP Server, MySQL database, and interpreters for scripts written in the PHP and Perl programming languages. The program is released under the terms of the GNU General Public License and acts as a free web server capable of serving dynamic pages. XAMPP is available for Microsoft Windows, Linux, Solaris, and Mac OS X, and is mainly used for web development projects. XAMPP requires only one zip or exe file to be downloaded and run, and little or no configuration of the various components that make up the web server is required. XAMPP is regularly updated to incorporate the latest releases of Apache/MySQL/PHP and Perl. One of the major advantages of XAMPP is that it allows you to install your development environment onto a pen drive which can then be moved between different PC‟s enabling you to work on your PHP project in any PC lab or on your home PC without changing your configuration. To install XAMPP on your pen drive go to http://www.apachefriends.org/en/xampp- windows.html Scroll down to the download section and select the installer version as shown below:Dave Parkinson
  • PHP5 Page 6 Run the xampp-win32-1.7.4.exe file and when prompted select the path to install to point to your pen drive (e.g. e:). This will install a number of files and directories under the xampp directory on you pen drive as shown below: Note that within the directory structure we have a directory called htdocs. Any files or directories placed within htdocs will behave as if they have been uploaded onto an external web server. In order to test your development environment you need to run the file xampp- control.exe found in your xampp directory.Dave Parkinson
  • PHP5 Page 7 Start the services you require (for Web Server just start the Apache service). After Apache starts, open the URL http://localhost/index.php and examine all of the XAMPP examples and tools. If you have problems starting the Apache service on your home PC there are several possible problems.Dave Parkinson
  • PHP5 Page 8 1. You are running Microsoft IIS web server locally on your machine (you must disable this as only one web server can be used in your PC) 2. You are running a local version of MySQL (remove this as XAMPP adds its own version of MySQL) 3. You are running some other program using the required ports (the usual problem will be on Port 80). The likely candidate will be a peer-to-peer application. For example many online TV services all use the Kontiki peer-to-peer network to share TV programmes. This uses port 80 and will stop the Apache service working. In order to run Apache you need to start Task Manager, go to Processes, then Show Processes from all Users, and end the KService service. In order to restart this service and use your TV Player you will need to restart your computer which will automatically restart the service.2.2 Your Development Tools In this module we will be using the NET Beans IDE to create our web projects. This program has already been installed onto all our Computer suites. The following information will show you how to install the development tools onto your home computer. In order to run Net Beans we must first install the Java Development Kit. You can find this at http://java.sun.com/javase/downloads/index.jsp Choose the Java SE 7 Development Kit (JDK) as shown below and install it on your PC:Dave Parkinson
  • PHP5 Page 9 Select Download JDK: Select the correct Windows .exe file dependant on whether you have 32 bit or 64 bit Windows, and install the JDK. Once installed download the Net Beans IDE from: http://www.netbeans.org/downloads/index.html Choose the full version (ALL) as shown below and install the program on your PC:Dave Parkinson
  • PHP5 Page 102.3 Exercise 1 - Your First PHP Script (HelloWorld) Open Net Beans and open a New Project. Choose a PHP Category and a PHP Application. Click Next and name your project helloworld (this will create your project in E:xampphtdocshelloworld directory on your pen drive). Accept the defaults on the next two screens then select Finish. This creates a file called index.php as shown below: Add the following code to the body section of the file.Dave Parkinson
  • PHP5 Page 11 <body> <p>This page was created at <strong> <?php echo date(„l jS of F Y h:i:s A‟); ?> </strong> on the computer running PHP.</p> </body> Save your file then test the file in your web browser by clicking on the run icon or by going to the following URL: http://localhost/helloworld/index.php You should see the following :- This page was created at Thursday 11th of August 2011 02:50:19 PM on the computer running PHP. Experiment with changing the parameters in the date function (look up the PHP date format on the web).2.3.1 Analysis of your first PHP Script The script that we have produced is a mixture of HTML and PHP. Note that all the all the PHP code is surrounded by a <?php and ?>. When an PHP page is requested from a web server, the web server first fully processes all the code between <?php and ?> before sending the output to the client. The script consists of several lines of HTML and one line of PHP code. The line of PHP code, displays the current date and time. The date function is built into PHP. The echo command outputs the results of the date function to the client. Note that the browser just receives HTML text from the web server, it does not receive any of the PHP code that was between the <?php and ?> delimiters. Each PHP statement must end with a semicolon.2.3.2 Sending Data to the Browser The echo command outputs information from the web server to the HTML seen in the web browser. You can use HTML formatting tags both inside and outside of your PHP code. For example if we want to output the phrase Hello World in bold to a web page then we can use either of the two options :- Option 1 : <strong> <?php echo „Hello World‟; ?> </strong>Dave Parkinson
  • PHP5 Page 12 Option 2 : <?php echo „<strong>Hello World</strong>‟; ?> You can send multiple separate chunks of data to the Web browser using a dot. <?php echo „Hello World ‟ . „my name is Dave‟; ?>2.3.3 Comments in PHP code Documentation is very important in any application development. With Object Orientation allowing multiple developers to work on the same application without the need to understand the code that another developer has written, documentation is a way of concisely explaining the information needed by the other developer without going into detail as to what the code is doing. Comments In PHP there are 2 different ways of doing comments: line commenting and block commenting. The single line comment is prefixed with a double slash (//). This can be on a line of its own, but normally it is placed after code: <?php echo Hello World!; //prints the string Hello World! A comment block is depicted by starting with a slash then asterisk (/*) and ending with an asterisk followed by a slash (*/). This is useful for commenting out blocks of code to remove it from the application, and also for writing paragraphs of text. Normally when writing a multi-lined comment, each line is prefixed with an asterisk. <?php /* * My "Hello World!" script. This * just prints out the string * "Hello World!" to the console. */ echo Hello World!; PhpDoc PHP uses standard documentation syntax in order to allow automatic generation and use of documentation. There are programs around that generate html documentation, and a lot of IDEs (including NetBeans) will pick up on these comments, and give you hints when the code that they reference are used. Normally a general description/comment is included followed by some key words. Key words are indicated with the @ symbol in front of them. The most common ones that you will come across will be @param and @return. These are used above functions and methods to explain what parameters it takes, and what is being returned. @param is followed by the datatype, the parameter name and then an optional description.Dave Parkinson
  • PHP5 Page 13 /** * @param <type> $variableName A further description goes here */ The @return appears in much the same way but without the variable name: /** * @return <type> Description here */ If we were to put this above the profile class constructor, this is what it would appear as. /** *The constructor takes the information of the person, and assigns * them to properties. * * @param string $name Name of the person in the profile * @param string $email The persons email address * @param string $gender Whether they are male or female * @param string $dob Their date of birth */ public function __construct($name, $email, $gender, $dob) { $this->setName($name); $this->email = $email; $this->gender = $gender; $this->dob = $dob; } And similarly, the getName() method: /** * Returns the name property from the object. * * @return string The persons name */ public function getName() { return $this->name; } Further to these keywords, there are many more. Here are just a few, and these are applicable mainly to class files: @author The author of the class, normally in the form of: Persons Name <email address> @copyright The copyright and ownership of the script/code/file @license The release license of the code, normally in the form of: url License Name @version The version of the file @package The package which the file is a part of Here is an example of the information for a class: /** * Profile is a class that contains the information of an individual * profile which can be used to display a profile page, or part of a * list of profiles on a page. * * @author Rick Ogden <r.l.ogden@salford.ac.uk> * @copyright 2009 University of SalfordDave Parkinson
  • PHP5 Page 14 * @license http://opensource.org/licenses/gpl-license.php GNU Public License * @version 1.0 * @package My Profile Site */ class Profile { … There are many more that can be found in the NetBeans PHP Docs.2.4 Datatypes A datatype is the generic name assigned to any data sharing a common set of characteristics. Common datatypes include Boolean, integer, float, string and array.2.4.1 Scalar Datatypes Scalar datatypes are capable of containing a single item of information. Several datatypes fall in this category including Boolean, integer, float and string. Boolean A Boolean variable may hold a value of either True or False. Integer An integer is a whole number (i.e. it has no decimal point). For example 4, 78 etc. Float Floating-point numbers may have a decimal point. For example 3.6, 6.7 etc. String A string can hold any sequence of letters, numbers, and symbols. Strings are distinguished from code, variable names, and numbers by putting them between single or double quotation marks. For example „My name is Dave‟, „hello‟, „28‟ are all strings. Note that the string „28‟ is handled differently than the integer 28.2.4.2 Compound Datatypes Compound datatypes allow for multiple items of the same type to be aggregated under a single representative entity. The array and the object fall into this category. Array It is often useful to aggregate a series of similar items together, arranging and referencing then in some specific way. This data structure, known as an array, is formally defined as an indexed collection of data values. Each member of the array index (also known as the key) references a corresponding value and can be a simple numerical reference to the values position in the series, or it could have some direct correlation to the value. ForDave Parkinson
  • PHP5 Page 15 example, if we were to create a list of European countries, you could use a numerically indexed array e.g. $country[0] = „England‟ $country[1] = „France‟ $country[2] = „Germany‟ $country[3] = „Spain‟ However if the requirement was for a list of correlated capital cities to the countries then we could use as associated indexed array e.g. $capitals[„England‟] = „London‟ $ capitals [„France‟] = „Paris‟ $ capitals [„Germany‟] = „Berlin‟ $ capitals [„Spain‟] = „Madrid‟ Object The other compound datatype supported by PHP is the object. PHP can use primitive objects to hold data. These can be created, if needed, without initialisation. Many languages (Java, JavaScript, C# etc..) use the dot notation to access properties (in the form of object.property), whereas PHP uses the arrow notation from C++. This is a hyphen followed by a closing angle-bracket ( -> ). This is used to both set and get properties from within an object. $myObject->myProperty = hello world!; echo $myObject->myProperty; //prints "hello world!" Property names can also be referenced by a variable containing a string. This is useful when the property being requested may vary. $myObject->myProperty = hello world!; $myVar = myProperty; echo $myObject->$myVar; // also prints "hello world!"2.5 Variables A variable is a small section of the computer‟s memory that you give a name to. In it you can place numbers, letters, dates, sentences etc. The information that you put in a variable can be accessed and manipulated by you. There are many different types of data that may be stored in a variable. Some of the most common are :- integer floating point string arrays objectsDave Parkinson
  • PHP5 Page 162.5.1 Naming Variables The rules you must follow in naming variable are :- A variable‟s name must start with a dollar sign ($) e.g. $name The name can contain a combination of strings, numbers and the underscore e.g. $my_report1 The first character after the dollar sign must be a letter or an underscore Variable names are case sensitive. $name and $Name are different variables Other suggestions to make your code easier to follow are :- Include the variable type in the name. For example :- $strName would be a string variable $iNumber would be an integer variable $dblNumber would be a floating point number $bolName would be a Boolean variable (True or False) This method of naming items is known as camel casing Use descriptive names for variables2.5.2 Declaring Variables PHP is very casual in how it treats variables. You do not have to declare or initialise variables, and you can convert from one variable type to another without problems. To declare a string variable we use the following syntax :- $firstname = „Dave‟; $last_name = „Parkinson‟ $today = „January 1, 2004‟; Enclosing a string within single quotes is useful when the string should be interpreted exactly as stated. This means that any variables or escape sequences will not be interpreted when the string is parsed. To print out the value of a variable we do not use quotes e.g. echo $firstname; To print out the value of a string containing variables use echo with double quotation marks e.g. echo “Hello, $firstname”; Another method of outputting a string containing a variable is to concatenate the variable to the string using the period e.g.Dave Parkinson
  • PHP5 Page 17 echo „Hello‟. $firstname; You can concatenate strings using the period (.) $name = $firstname . $last_name; Heredoc syntax offers a convenient means of outputting large amounts of text. Rather than delimiting strings with single or double quotes, two identical identifiers are employed e.g. <?php $mystring = <<<EOT This is some PHP text. It is completely free I can use "double quotes" and single quotes, plus $variables too, which will be properly converted to their values, you can even type EOT, as long as it is not alone on a line, like this: EOT; ?> There are several key things to note about heredoc, and the example above: You can use anything you like; "EOT" is just an example You need to use <<< before the delimiter to tell PHP you want to enter heredoc mode Variable substitution is used in PHP, which means you do need to escape dollar symbols - if you do not, PHP will attempt variable replacement. You can use your delimiter anywhere in the text, but not in the first column of a new line At the end of the string, just type the delimiter with no spaces around it, followed by a semi-colon to end the statement Number variables (either integer or floating point) may be declared as follows : $num1 = 83; $num2 = 3.142; $num3 = -45.6; Unlike other languages, PHP does not require that you assign the size to an array at creation time. PHP doesn‟t even require that you declare an array before using it, although you are free to do so. You can create the array simply by making reference to it: $country[0] = „England‟; $country[1] = „France‟; You can then display the first element of the array as follows echo $country[0];Dave Parkinson
  • PHP5 Page 18 Creating associative arrays is equally easy: $country[„England‟] = „London‟; $country[„France‟] = „Paris‟; Alternatively you can use the array( ) construct to create an indexed array: $country = array(„England‟, „France‟, „Germany‟, „Spain‟); You can also use array( ) to create an associated array: $capitals = array(„England‟ => „London‟, „France‟ => „Paris‟, „Germany‟ => „Berlin‟, „Spain‟ => „Madrid‟);2.5.3 Type Casting in PHP Type casting in PHP works much as it does in other languages: the name of the desired type is written in parentheses before the variable which is to be cast e.g. $data = „10.5‟; //$data is a string $num =(float) $data //$num is a floating point number The casts allowed are: (int), (integer) - cast to integer (bool), (boolean) - cast to boolean (float), (double), (real) - cast to float (string) - cast to string (array) - cast to array (object) - cast to object Note that tabs and spaces are allowed inside the parentheses. Note: Instead of casting a variable to string, you can also enclose the variable in double quotes. $num = 10; // $num is an integer $str = "$num"; // $str is a string2.5.4 Constants Constants are similar to variables in that you give it a name and store data in it. However once declared the value of a constant cannot be changed. They are declared as follows :- Define ( „VATRATE‟ , „0.0175‟);Dave Parkinson
  • PHP5 Page 19 It is normal practice to use all capital letters for constants.2.6 Communicating with the User So far we have used PHP to send information to the browser. In order to make our PHP web pages truly interactive we must also be able to obtain information from the user. In order to obtain information from the user we must use forms. Forms contain text boxes, list boxes, check boxes, radio buttons etc. to provide a variety of different ways of collecting information from users of your web pages.2.6.1 Form Elements When you use a form you create a series of elements for your visitor to fill in. An example of a form is given below :- In order to get information from a form then you must first add a Form Control to your page. You can then add a variety of different controls onto the form within your web page. These include :- Form : this is the form itself, all other form elements need to be placed within the form. Text Field : this is where your visitor will input some text. Button : can be either a submit or a reset button Check Box : your visitor can select multiple check boxes if they wish. Radio Button : unlike check boxes, when you click on a radio button you will uncheck all the other radio buttons in the group (to belong to a group, radio buttons must have the same name).Dave Parkinson
  • PHP5 Page 20 List/Menu : either gives a popup list of entries (you can only select one of them) or a menu list (you can select more than one option). File Field : will allow your visitor to upload files to your web site. Image Field : use this instead of a button to submit a form or perform an action. Hidden Field : this icon represents a field that does not require any information to be input from your visitor but that will still be processed by the PHP script. Each of these controls must be given a unique name (and properties).2.6.2 Submitting your Form To gather the information from your form you need to add a submit button to it. When your form is complete, this button will transmit the information contained within the form to the PHP page you specify, where it can be processed. Pressing the submit button will cause the button to be actioned with the attributes specified for the form. What it will do is send the form to the Action address (this will be your PHP page designed to process the form elements) set up as part of the form attributes. The form Method must be set to POST. A reset button is usually added to a form to allow the user to clear all the data from the form elements and start again.2.6.3 Gathering Information from a Form Information from a form is gathered and processed in the PHP page that is specified in the form‟s ACTION property. To read the values of a form field, you need to use superglobal variables e.g. $_GET and $_POST. To demonstrate the use of $_POST superglobal variable, imagine that you have designed a form with a text box on it to hold the name of the person accessing your web page. The text field has been given the unique name firstname. The form then directs the user to a PHP page that contains the following script :- <html> <body> <?php $name = $_POST[„firstname‟]; echo „Hello „ . $name; ?> </body> </html>Dave Parkinson
  • PHP5 Page 21 If the person enters Dave in the form on the HTML page then the following information will be output :- Hello Dave htmlentities Whenever you allow your users to submit text to your website, you need to be careful that you dont leave any security holes open for malicious users to exploit. If you are ever going to allow user submitted text to be visible by the public you should consider using the htmlentities function to prevent them from running html code and scripts that may be harmful to your visitors. The htmlentities function takes a string and returns the same string with HTML converted into HTML entities. For example, the string "<script>" would be converted to "&lt;script&gt;". By converting the < and > into entities, it prevents the browser from using it as an HTML element and it prevents the code from running if you were to display some users input on your website. Anytime you allow users to submit content to your website, that other visitors can see, you should consider removing the ability to let them use HTML. Although this will remove a lot of cool things that your users can do, like making heavily customized content, it will prevent your site from a lot of common attacks. We can now change the above code as follows: <html> <body> <?php $name = htmlentities($_POST[„firstname‟]); echo „Hello „ . $name; ?> </body> </html>2.6.4 Exercise 2 (PassingData) Open Net Beans and create a new PHP project called passingdata. Edit the index.php page as shown below: <body> <div> <p><strong>Please enter your name and birthday :-</strong></p> <form name="form1" method="post" action="passingdata.php"> <div> <label>Your name:</label> <input type="text" name="name"> <br/> <label>Your Birthday (in DD/MM/YY format):</label> <input type="text" name="birthday">Dave Parkinson
  • PHP5 Page 22 <br/> <input type="submit" name="Submit" value="Submit"> <input type="reset" name="Submit2" value="Reset"> </div> </form> </div> </body> Note that if you just enter the text then press alt-shift-f the page will be automatically formatted with the correct tab spacing. This will create a web page containing two text boxes (note that we could have created this as a HTML page as it contains no PHP code). The user is required to put his name in the first text box (called name), and his date of birth in the second text box (called birthday). A Submit button has been added to the page to process the form in an PHP web page. A Reset button is also added to clear the form elements. Start the Apache web server and open your web browser and view: localhost/passingdata. You should see the following: Add a new PHP Web Page (passingdata.php) to your project. This page will process the data from the HTML form. The PHP page should output the name of the user and inform him of his date of birth in the following manner :– Hello Dave. You were born on 15/2/53 Add a link to this PHP page to allow you to return to your index.php page.2.6.5 Gathering data from other Form Elements There are times when a textbox is not a suitable method of gathering information. There are times when you may wish to restrict the user to a specific set of choices. To do this forms provide the capability of using list boxes, radio buttons and check boxes. List Boxes : List boxes allow the user to choice a response to a number of different options from a drop down list box. When you add a list box to your form using Expression Web you can give the list box a name and input a number of list values. For each item in the list box you can add an item label (which will appear in your drop down list) and a value (which is what will be returned when the data is requested using PHP). The value returned will correspond to whatever item in the list box is selected by the user.Dave Parkinson
  • PHP5 Page 23 Check Box : Check boxes are used when you require a YES/NO response from the user. When you add a check box to your form using Expression Web you can input a name for the check box and a checked value which will only be returned if the user has checked the box. Radio Buttons : Radio buttons are similar to check boxes but unlike check boxes, when you click on a radio button, you will uncheck all the other radio buttons in the group (to belong to a group, radio buttons must have the same name). When you add a number of radio buttons to your form using Expression Web you input the same name for each radio button in the group. Each individual radio button, however, is given a different checked value which will be returned to indicate which radio button has been selected.2.7 Programming in PHP PHP supports all the usual programming features. The syntax of PHP is virtually identical to C++, C# and Java.2.7.1 PHP Operators Operators allow you to work with data. They allow you to combine, change and replace data. There are several major classes of operator :- Assignment Operator The assignment operator is the equals sign (=). The assignment operator takes whatever is on the right hand side of it and stores it in the left hand side of it e.g. $Number = 3 $iNum = $iNum + 1 Arithmetic Operators Example Name Result $a + $b Addition Sum of $a and $b. $a - $b Subtraction Difference of $a and $b. $a * $b Multiplication Product of $a and $b. $a / $b Division Quotient of $a and $b. $a % $b Modulus Remainder of $a divided by $b. The division operator ("/") returns a float value anytime, even if the two operands are integers (or strings that get converted to integers).Dave Parkinson
  • PHP5 Page 24 Comparison Operators Example Name Result $a = = $b Equal TRUE if $a is equal to $b. $a != $b Not equal TRUE if $a is not equal to $b. $a <> $b Not equal TRUE if $a is not equal to $b. $a < $b Less than TRUE if $a is strictly less than $b. $a > $b Greater than TRUE if $a is strictly greater than $b. $a <= $b Less than or equal to TRUE if $a is less than or equal to $b. $a >= $b Greater than or equal to TRUE if $a is greater than or equal to $b. Increment/decrement Operators Example Name Effect ++$a Pre-increment Increments $a by one, then returns $a. $a++ Post-increment Returns $a, then increments $a by one. --$a Pre-decrement Decrements $a by one, then returns $a. $a-- Post-decrement Returns $a, then decrements $a by one. Logical Operators Example Name Result $a and $b And TRUE if both $a and $b are TRUE. $a or $b Or TRUE if either $a or $b is TRUE. $a xor $b Xor TRUE if either $a or $b is TRUE, but not both. ! $a Not TRUE if $a is not TRUE. $a && $b And TRUE if both $a and $b are TRUE. $a || $b Or TRUE if either $a or $b is TRUE. String Operators There are two string operators. The first is the concatenation operator (.), which returns the concatenation of its right and left arguments. The second is the concatenating assignment operator (.=), which appends the argument on the right side to the argument on the left side. For example $a = „Hello „; $b = $a . „World!‟; // now $b contains "Hello World!" $a = „Hello ; $a .= „World!‟; // now $a contains "Hello World!"Dave Parkinson
  • PHP5 Page 252.7.2 PHP Control Structures PHP supports all the commonly used control structures :- if...elseif...else Statement Use an if...elseif...else block to define several blocks of statements, one of which will execute: if (condition1) code to be executed if condition is true; elseif (condition2) code to be executed if condition is true; elseif (condition3) code to be executed if condition is true; else code to be executed if condition is false; switch Statement The switch statement is a variant of the if-else combination. It is often used when you need to compare a variable against a large number of variables. switch (n) { case label1: code to be executed if n=label1; break; case label2: code to be executed if n=label2; break; default: code to be executed if n is different from both label1 and label2; } while Statement The while loop executes a block of code while a condition is true. while (condition) { code to be executed; } do-while Statement The do...while statement will always execute the block of code once, it will then check the condition, and repeat the loop while the condition is true. do { code to be executed; } while (condition); for Statement The for loop executes a block of code a specific number of times for (counter initialisation; loop test condition; loop modifier) {Dave Parkinson
  • PHP5 Page 26 sequence of statements; } statement after loop; foreach Statement The foreach statement is used for looping through arrays, pulling each key/value pair from the array until all items have been retrieved or some internal condition has been met: foreach ($array as $value) { code to be executed; }2.7.3 PHP Functions PHP has more than 1000 functions already built into its standard distribution. You can invoke a function simply by specifying the function name (for example the date function we used in exercise1) You can also write your own functions: function functionName() { code to be executed; } To add more functionality to a function, we can add parameters. A parameter is just like a variable. To let a function return a value, use the return statement. An example of a function is shown below. <?php function add($x,$y) { $total= $x + $y; return $total; } echo "1 + 16 = " . add(1,16); ?> When run this will output the following: 1 + 16 = 172.8 Object Orientated Programming with PHP Object Orientation is a programming concept that was first developed in the 1960s, but did not make its way into mainstream programming until the mid 1990s. It is a concept forDave Parkinson
  • PHP5 Page 27 writing efficient, organised and reusable code in applications, which as computing hardware advances, are becoming increasingly larger and more complicated. Although each programming language has its own implementation of Object Orientation, the principles behind it remain similar across the board. Data is stored in instances of classes (called objects), and objects have the ability to use and manipulate data contained within it. Thus meaning that the code is completely self-sufficient. This follows the same principles of keeping things organised and separate in order to increase maintainability and structure.2.8.1 Classes and Objects Classes Classes are containers of code that the programmer writes, and creates instances of (which are called Objects). Think of the class as a blueprint for an object. Classes contain properties (also known as class variables or fields), which are variables which can be used throughout the class. Classes also contain methods (also known as functions), which can use and modify the properties. Methods can also take arguments as parameters from code outside the class, and return information, which can be used by other methods within the object or external code. Both methods and properties can be made visible or invisible to code outside the class, thus increasing the security and integrity of the data within the class instance (object). Generally a class looks like this: <?php class MyClass { protected $var1 = , $var2 = 0; public function __construct() { //the constructor //code goes here } public function methodOne() { //more code } } Objects Objects are instances of classes. Each time you want to use a class, you create a new instance of it. This means that you can have as many instances of classes as you like without having to worry about conflicts. Your external code can then call methods and fields (as long as they are public or “visible”). $myObject = new MyClass(); //creates a new instance (object) of MyClass $myObject->methodOne(); //performs the method "methodOne" Examples If we were to relate this to “real world” objects, we could say that a Dog was a class, and instances of that class are created for each dog. The objects would contain informationDave Parkinson
  • PHP5 Page 28 such as the dogs name, age, breed, colour etc.. and methods include things like make the dog walk, bark, sit etc.. However, if we want to relate this to something more relevant to programming (and particularly this module), you could take a website such as theregister.co.uk. The Register is an IT news website. You could look at as having a News Item class, and each news item is an object created from that class. The front page contains many instances of the News Item class. Green borders highlighting what could be objects of the class News item This means that the same code for displaying news items on the front page can also be used to display individual news items on the specific news item page, and also for the RSS feed. In a normal website (with embedded code), you would need to repeat a lot of the code.2.8.2 Using Object Orientation Creating a Class As mentioned before, a class is a blueprint in which objects are constructed from. As an example, we are going to build a profile of a person like you might get on a social networking site, albeit a simple one. We need to create a class in order to instantiate objects of peoples profiles. class Profile { } Notice how we start the class name with an upper-case letter? This is not required, but good practice as it follows PHP standard conventions. Classes should start with upper-case letters, but objects and methods should not. We next need to decide the properties that the objects will hold. These are permanent variables which are there throughout the existence of the object. Of course these propertiesDave Parkinson
  • PHP5 Page 29 will vary, but for simplicity we will just have the persons name, email, gender and date of birth. class Profile { var $name = , $email, $gender, $dob; } These properties (like standard PHP variables) can be initialised on creation, or left uninitiated. Properties do not need to be declared at the top. However, it does help to keep track of what properties an object has. Constructor When a new object is instantiated from a class, a specific method is run. This method is called a Constructor. Although not required, nearly all classes have them, as they are used to set up the object, and also provide information which can make that object differ from another. Variables can be passed into the constructor using parameters. In PHP the constructor method is always named “__construct” (thats a double underscore in front of the word “construct”). class Profile { var $name = , $email, $gender, $dob; function __construct($name, $email, $gender, $dob) { //constructor code here } } This means that when you instantiate a new object, you need to pass four parameters into the class. $rick = new Profile(Rick Ogden,r.l.ogden@salford.ac.uk,male,08/07/1986); This is now passing information into the constructor, meaning that we can instantiate as many objects from this class as we like, but passing different information in to make it unique. Self Referencing In the previous example you will have noticed that we used the same names for the parameters as we did for the properties. This will not cause a conflict as properties are referenced to differently from local variables and parameters. If you want to retrieve a property from an object, its simply a case of referencing the object, and then the property name. $rick->name; However, in order to for an object to refer to itself, you must use the predefined variable $this. class Profile { var $name = , $email, $gender, $dob;Dave Parkinson
  • PHP5 Page 30 function __construct($name, $email, $gender, $dob) { $this->name = $name; $this->email = $email; $this->gender = $gender; $this->dob = $dob; } } $rick = new Profile(Rick Ogden, r.l.ogden@salford.ac.uk, male, 08/07/1986); echo $rick->name; //prints Rick Ogden When a class uses the $this variable, it allows the object to refer to itself, complete with all methods and properties. The $this variable can also be used as a return value (to return itself) and also to send itself as a parameter to another objects method. Encapsulation Encapsulation is used in order to control which parts of our application are allowed to alter what variables. Sometimes you may want variables to be specific values, and to validate them before writing to the variable. Other variables you might not want any other parts of application to get at. This is where visibility comes in. By default, in PHP everything is public. However, visibility is controlled by the terms “public”, “private” and “protected”. This can be placed before a method declaration, or replace the “var” declaration for a property. class Profile { protected $name = , $email, $gender, $dob; public function __construct($name, $email, $gender, $dob) { $this->name = $name; $this->email = $email; $this->gender = $gender; $this->dob = $dob; } } Public means that the property/method can be accessed/called from anywhere in the application. Protected only allows the property/method to be accessed/called on from within the class and subclasses, and private means it cant even be called or accessed from within subclasses (this is rarely used for this reason, as it really limits expandability). If we want to modify or retrieve a protected property, we use a mutator (setter) or accessor (getter) method respectively. In these methods we can give external code “read” access to the property, and validated write access. Mutator methods take one or more argument, which determine what the property will be changed to. Here is a very simple example of the mutator method “setName”. It checks to make sure that the name is not empty. public function setName($name) { if(!empty($name)) { //makes sure its not an empty string $this->name = $name; } } An accessor method can retrieve and if need be, format the property that is required. These normally do not contain parameters, but may do if necessary for formatting.Dave Parkinson
  • PHP5 Page 31 public function getName() { return $this->name; } A method within a class can also call another method within the class. Instead of using the object name like you do in your external code, you use the $this variable. So now our class can look like this. class Profile { protected $name = , $email, $gender, $dob; public function __construct($name, $email, $gender, $dob) { $this->setName($name); $this->email = $email; $this->gender = $gender; $this->dob = $dob; } public function setName($name) { if(!empty($name)) { //makes sure its not an empty string $this->name = $name; } } public function getName() { return $this->name; } } This class can now be used as follows: $rick = new Profile(Rick Ogden, r.l.ogden@salford.ac.uk, male, 08/07/1986); $rick->setName(Dave Parkinson); echo $rick->getName(); //prints Dave Parkinson2.8.3 Including a Class Once you have written your class, you need to include it into your web page. To keep your code neat, each class should be in a separate file. This means that you then need to include the classes where theyre to be used. Require Vs Include People often get confused about where to use these two statements. The difference is that if an included file cannot be found, the rest of the script will still run. Whereas with require, the script will be terminated immediately. Generally it is recommended to “require” a class, as there can be security issues with continuing to run a script if the included class is not found. As well as these, there are also include_once and require_once. These do exactly the same as include and require, but mean that the included/required file will only be imported the once, and if there are any further requests for that file, it will just ignore them.Dave Parkinson
  • PHP5 Page 32 This is useful for importing our classes, as a class only needs to be included once. Considering that over the development of an application, a class will probably be imported into multiple directories, there is no point in importing it multiple times. <?php require_once(class.profile.php);2.9 MVC Until recently most PHP code was written by simply intertwining the PHP script with the HTML text. Because the design of the web site is now inextricably linked with the programming logic several problems arise, particularly when a large team are working on the development of the web site: Designers whose main task is to make the web site look good are now faced with the task of learning PHP. Developers who are later employed to expand the web site features are distracted by fixing the bugs and security problems introduced by the novice. In the process of changing the PHP script, they decide to add their own tweaks to the site design thus infuriating the designers. There is a solution that can go a long way to alleviating these issues, the MVC architecture. Model–view–controller (MVC) is an architectural pattern used in software engineering. Successful use of the pattern isolates business logic from the user interface, permitting one to be freely modified without affecting the other. The controller collects user input, the model manipulates application data, and the view presents results to the user. The model: The model defines the rules for the process an application is intended to represent. You can think of it as the specification responsible for both the applications data and its behaviour. For example if we were to write an application that serves as a conversion calculator, allowing users to convert from miles to kilometres, Fahrenheit to Celsius etc. The model is responsible for defining the formulas used to perform such conversions, and when presented with a value and desired conversion scenario, the model carries out the conversion and returns the result. Note that the model is not responsible for formatting the data or presenting it to the user. This is handled by the view. The view: The view is responsible for formatting the data returned by the model and presenting it to the user. It‟s possible for more than one view to utilise the same model, depending on how the data should be presented. The controller: The controller is responsible for determining how the application should respond based on events occurring within the application space (typically user actions), done by coordinating with both the model and the view to produce the appropriate response.Dave Parkinson
  • PHP5 Page 33 To better understand the dynamics of an MVC driven application consider the scenario where we wish to develop an application involving the conversion application. The following actions take place: The user desires the application to perform an action, e.g. converting an input temperature from Fahrenheit to Celsius. The user then submits the form by clicking a submit button. The controller responds by identifying the appropriate action, gathering the input from the form, and supplying it to the model. The model executes the function responsible for converting Fahrenheit to Celsius and returns the calculated and returns the calculated value to the controller. The controller calls the appropriate view, passing along the calculated value. The view renders and returns the result to the user.2.9.1 Exercise 3 – A Template for a PHP Web Site using MVC Download the file templates.zip from Blackboard and unzip it into your htdocs directory under XAMPP. This template (written by Rick Ogden) uses the 960gs CSS framework to design the site structure. In the Views/template directory it contains a header.phtml and a footer.phtml which are included on every new page generated. To add additional pages just edit the file header.phtml to add the extra link and then add a new controller (pagex.php) and a new view (pagex.phtml) for each page required. If you run the project you will view the following web site:Dave Parkinson
  • PHP5 Page 34 The home page explains how use the template. It includes a link to the free, open source CSS template, 960gs CSS Framework, which has been used to design the site. Click on this link to find more information on the framework. The template written for the MVC architecture contains the following files and directories. Views Directory This directory contains a subdirectory called template with two files, footer.phtml and header.phtml. This files will be appended onto every page of your web site to maintain a consistent look and feel to all your pages. You will need to edit the header.phtml file to add a new link to the unordered list every time you add a new page to your site. It also contains the file index.phml and page1.phtml which are the views for the two pages on your website. CSS Directory The subdirectory css (within the main css directory) contains all the files for the 960gs CSS Framework. It must not be edited. The style.css file contains all the styles for your site.Dave Parkinson
  • PHP5 Page 35 #title, #menu, #footer { background-color: #00584a; color: #fff; } #menu a { color: #fff; text-decoration: none; background-color: #008a7f; display: block; padding: 3px; } #menu li { list-style: none; margin: 2px; } #menu { height: 300px; } #footer { text-align: center; } .datatable td { border: 1px solid #000; padding: 2px; } .label { width: 100px; } .inputtd { width: 400px; } .datatable th { width: 100px; } .radbuttons, .inputtable { width: 70%; } .standardwidth { width: 200px !important; } You need to edit this file to add new styles and to change to look of your site. Images DirectoryDave Parkinson
  • PHP5 Page 36 This directory is used to store all the images on your site. Currently it contains one image used in the header. Models Directory Currently unpopulated but will be used to store all your models used on your website. Index.php <?php $view = new stdClass(); $view->pageTitle = Homepage; require_once(Views/index.phtml); Sets the name of the page title and loads the view for the page. A similar file page1.php performs the same operation for the second page in your website. For all the remaining exercises on this PHP module we will be using this template to build a multi page website to run the exercises. To start our website we will rename the project with your surname e.g. parkinson. Right click on the templates project and select rename. Rename the project yoursurname (also select Rename Project Folder). Before we can run the project we need to change the include information. Right click on the include section of the website and click properties. This will open a dialog box. Select Run Configuration and change the Project URL to reflect the new name of your project.Dave Parkinson
  • PHP5 Page 37 Run the site.2.10 Exercise 4 – A Simple Conversion Program We will be creating a simple PHP program to convert miles to kilometres and vice versa using the MVC architecture. We will add a new page to the website we created in the previous exercise. The new page will be called converter. The Models directory will contain the file responsible for the processing of data. We will add a file called class.converter.php. The Views directory will contain the file responsible for displaying the data (e.g. the HTML). We will add a file called converter.phtml. The controller (converter.php) is a file called when the visitor to the site clicks on the converter link in the navigation section of the site. It handles the user‟s input, processes the data using the model and displays the results using the view. In order to create our website we will start with the Model (although we could equally well start by writing the view). Create a new PHP Class file called class.converter.php within the Models directory. Remove the closing PHP tag (?>), this is for security reasons. This class will contain the code that performs the conversion from miles to kilometres or kilometres to miles. Add the following code: class Converter { var $number = 0, $unit = ; public function __construct($number, $unit) { $this->number = $number; $this->unit = $unit; } public function convert() { if ($this->unit == miles to km) { $result = $this->number * 1.609;Dave Parkinson
  • PHP5 Page 38 } elseif ($this->unit == km to miles) { $result = $this->number * 0.621; } else { $result = error; } return $result; } } Note that the new class is called Converter (the same as the filename). This PHP file contains the following key sections of code: class Converter { var $number = 0, $unit = ; This code sets up the class called Converter and declares and initialises two public properties (number and unit). public function __construct($number, $unit) { $this->number = $number; $this->unit = $unit; } This the constructor method for the class. When creating an instance of the class two arguments (number and unit) are required. Within the method this takes the arguments and assigns them to the respective properties. public function convert() { if ($this->unit == miles to km) { $result = $this->number * 1.609; } elseif ($this->unit == km to miles) { $result = $this->number * 0.621; } else { $result = error; } return $result; } The class also contains a public method called convert. This method performs the calculation and returns the result of the calculation. Next we create the Controller. Either add a new php file called converter.php into the Source File area of the project (or rename and edit the existing file page1.php). The controller is the page visited by the user within his web browser and its purpose is to retrieve data entered by the user and bring together the Model and the View. Replace the contents of the file with the following code: <?php $view = new stdClass(); $view->pageTitle = Converter; require_once(Models/class.converter.php);Dave Parkinson
  • PHP5 Page 39 if(isset($_POST[submit])) { $converter = new Converter($_POST[number], $_POST[unit]); $value = $converter->convert(); $view->result = Converting . $_POST[number] . from . $_POST[unit] . is . $value . .; } require_once(Views/converter.phtml); Note that the closing PHP tag has been removed. This PHP file contains the following key sections of code: require_once(Models/class.converter.php); This imports the Model which we use to perform the conversions if(isset($_POST[submit])) { $converter = new Converter($_POST[number], $_POST[unit]); $value = $converter->convert(); $view->result = Converting . $_POST[number] . from . $_POST[unit] . is . $value . .; } This if statement looks to see if the user has pressed the submit button. If so, a new instance (object) of the Converter class called converter (passing the values of number and unit submitted by the user) is instantiated. The next line creates a variable called value and assigns it the returned value from the convert method. The next line creates the primitive object called $view with the property result. This property is then assigned the string of information that is to be returned to the view (e.g. Converting 5 from km to miles is 3.105.) . This view object will be referenced in the View. require_once(Views/converter.phtml); This imports the View which contains the HTML that will be displayed to the user. This View is set up as follows. Rename the file page1.phtml to converter.phtml. Edit the file as follows:. <?php require(template/header.phtml) ?> <form action="<?php echo $_SERVER[PHP_SELF]; ?>" method="post"> <div> <label>Convert </label> <input type="text" name="number" value="<?php echo $_POST[number]; ?>" /> </div> <div> <label>From </label> <select name="unit"> <option>km to miles</option> <option>miles to km</option> </select>Dave Parkinson
  • PHP5 Page 40 </div> <div> <input type="submit" value="submit" name="submit" /> </div> </form> <?php if (isset($view->result)) : ?> <p><?php echo $view->result; ?></p> <?php endif; ?> <?php require(template/footer.phtml) ?> This phtml file contains the following key sections of code: <form action="<?php echo $_SERVER[PHP_SELF]; ?>" method="post"> This is a form tag with the action attribute set to post back to itself (this is done with a PHP statement which prints the current URL. This allows this view to be used in multiple places on the site). <input type="text" name="number" value="<?php echo $_POST[number]; ?>" /> This is a text input element which gets its value from the data posted back to itself. If no data is posted back then this is NULL. This ensures that following the post the original data inputted is still present in the text box. <?php if(isset($view->result)) : ?> <p><?php echo $view->result; ?></p> <?php endif; ?> This code tests to see if the property result within the primitive object $view has been set. If so the result of the calculation will be displayed as shown below:Dave Parkinson
  • PHP5 Page 41 With a web application of this nature we often want to check that the data input by the user is valid. This can easily be done in the following manner. We can test the value a user inputs using the PHP function is_numeric which returns TRUE if the value is a number or a numeric string, FALSE otherwise. This can be done by altering the function convert within the Model as follows: public function convert() { if (is_numeric($this->number)) { if ($this->unit == miles to km) { $result = $this->number * 1.609; } elseif ($this->unit == km to miles) { $result = $this->number * 0.621; } else { $result = error; } } else { $result = false; } return $result; } This code now tests to see if the user enters a numeric value and if he does not then it returns a value of FALSE. Within the Controller we can modify the if statement that tests to see if the user has pressed the Submit button as follows: if(isset($_POST[submit])) { $converter = new Converter($_POST[number], $_POST[unit]); $result = $converter->convert(); if (!$result) { $view->result = Not a valid number.; } else { $view->result = Converting . $_POST[number] . from . $_POST[unit] . is . $result . .; } } This code now tests the returned value from the convert method. If it is FALSE it displays a message stating that the user did not enter a valid number. Otherwise it displays the result of the calculation. Change your web application to add error checking.2.11 Exercise 5 – A Simple Calculator Add an additional page to your website and call it calculator. The new application should use the techniques described previously to allow the user to perform a simple calculation. The user should be able to enter two numbers which be added together, subtracted, multiplied or divided, dependent upon which one of the four operators are selected by the user from the drop down list box. On clicking the Submit button the answer should be given on the same web page as shown below:Dave Parkinson
  • PHP5 Page 422.11.1 Using the Debugger in Net Beans With a complex program it can be very useful to run the program in single step mode and look at the values of variables etc. at various stages of the program in order to correct any functional errors. In order to use XDebug as a PHP debugger within Net Beans we must edit the php.ini file within XAMPP. Make the following changes to php.ini: * Locate xamppphpphp.ini and make a copy of the php.ini file for editing. Name it phpcopy.ini * Open the php.ini file with Notepad * Find and uncomment the line zend_extension = "xampphpext php_xdebug.dll". * Find and uncomment the line xdebug.remote_host=localhost. Change the value of the setting from localhost to 127.0.0.1. * Find and uncomment the line xdebug.remote_enable = 0. Change 0 to 1. * Find and uncomment the line xdebug.remote_handler = "dbgp". * Find and uncomment the line xdebug.remote_port = 9000. * Save php.ini. * Run the XAMPP Control Panel Application and restart the Apache server. Full details of how to enable XDEBUG can be found at: http://www.netbeans.org/kb/docs/php/configure-php-environment- windows.html#installAndEnableXDebug One of the biggest problems with PHP development (compared to other languages) wasDave Parkinson
  • PHP5 Page 43 the inability to add break-points and “step through” code. The PHP guru Derick Rethans felt that PHP was missing such a useful tool, so decided to create one himself. In this module we will only be scratching the surface of the ability of Xdebug, however it is an invaluable tool to have in your arsenal. Once installed, you can add break-points by clicking on the line numbers at the left hand side of the editor. The line will then turn red to show that a break-point has been added. To begin the debug session, you need to make sure that the project youre currently developing is set as the “main project”, and then click on the “debug” icon. Once it has started debugging, you get a new set icons at the top. These are: stop debugging, continue, step over, step into, step out and run to cursor. Depending on your Netbeans configuration, the application might automatically break at the beginning of each file, if this is the case, just press the “continue” icon. It will then stop at the line you have put your break-point on. And you will know that because the line turns green. Below the editor, there is a set of tabs. If you visit the tab called “Variables” it will show you the state of all variables within the scope of that of the break point (including local variables, object variables and superglobals). It tells you the variable name, the data type of the variable and the value at that point.Dave Parkinson
  • PHP5 Page 44 You can also hover your mouse over variables in the code and it will tell you what the current state of them is. From this point onwards you can use the debugging icons to control how the far through the code the program should run, or just continue through the rest of the code (until the next break-point if there is one). Try the debugger within your Calculator program.2.11.2 var_dump Function var_dump( ) displays information about variables in a simple, readable format. This function is very useful when debugging , providing a simple and easy way to display the current contents of one or more variables. For simple scalar variables (such as booleans, integers, strings, and doubles), the type of the variable is printed, followed by an opening bracket, the value contained in the variable, and a closing bracket. Arrays are printed as a list of keys and values, and have their typearray) printed at the top of the list. Objects are handled in a fashion similar to that of arrays. The class of which the object is an instance is displayed, followed by the typeobject). After this, a list of the objects member variables is printed. For example the following code: <?php $b = 3.1; $c = true; var_dump($b, $c); ? will output to the screen float(3.1) bool(true)Dave Parkinson
  • PHP5 Page 452.12 Maintaining Information on the Web When you are creating an interactive web site it is often useful to be able to maintain information entered by the user over a period of time. One way of achieving this is to use cookies, which can save small bits of information over time on the user‟s computer. Although cookies provide an easy way to maintain information over time they do have limitations, they cannot be used to save objects and arrays, and the user can turn them off in his computer web browser To combat some of these shortcomings, PHP provides a built in object: the Session object. The Session object is designed to maintain state for each visitor to your web site for the duration of the visit. The session object has the advantage over cookies in that they are able to save arrays and objects. There is, however, one major problem with Session objects. Since they save the information on your web server, if they are overused, they can lead to performance problems on your web server.2.12.1 Using Cookies Within the client-server model, when a client wants to view a particular HTML or PHP page he first requests the page and then once the page is found it is returned to him. At this point the conversation between the client and the server is over. The web server does not keep information on what clients it has spoken to recently, or what requests were made. For this reason Web sites are often referred to as stateless (an application is said to have state if it persists information for each user). A web site does not have to be stateless, it can use cookies to persist information over lengthy periods of time. Cookies are small bits of information, such as strings and numeric values, stored on a clients computer for a specified period of time. When cookies are created on the clients computer, the developer needs to specify when they expire. After a cookie expires it will automatically remove itself from the clients computer. When a web site writes a cookie to a clients computer, only that web site can later read the cookie‟s value. It is the browsers responsibility to keep track of which web site created the cookie, and only allow cookies to be read by the proper web sites. It is important to note that all modern browsers provide users with an option not to accept cookies on their computers; however they do accept cookies by default. Cookies are a means of saving small bits of information over time on the user‟s computer in the form of key/value pairs. Although cookies provide an easy way to maintain information over time they do have limitations, the major one being that the user can turn them off in his computer web browser.Dave Parkinson
  • PHP5 Page 46 You can set cookies using the setcookie( ) function. Cookies are part of the HTTP header, so setcookie( ) must be called before any output is sent to the browser (i.e. before the <html> tag). For example :- setcookie(„firstname‟, „Dave‟); This will send a cookie to the browser with a name of firstname and a value of Dave. To retrieve a value from a cookie, you use the superglobal $_COOKIE. For example, to retrieve the cookie set above into a variable you would use :- $name = $_COOKIE[„firstname‟]; You can set the cookie parameters using the setcookie ( ) function. This function also contains an expiration argument allow you to set the time for which the cookie is valid. If it is not set the cookie will only remain valid until the user closes his browser. Normally the expiration time is determined by adding a particular number of minutes or hours to the current moment, retrieved using the time ( ) function. For example the following statement sets the expiration time to be 1 hour from the current moment. setcookie(„firstname‟, „Dave‟ , time()+ 3600); Although a cookie will delete itself automatically when the expiration time is met there may be instances when you wish to delete the cookie manually. This can be done as follows :- setcookie(„firstname‟, „‟);2.12.2 Using Session Variables PHP supports sessions. The Session object stores data types on the web server and is accessible through any PHP page on your web site. The Session is used to maintain state only for the duration of a users visit to your web site. When each new user comes to your web site, memory on the Web server is allocated to store the Session object for that user. This memory is released if the user does not visit your web site for a certain period of time (e.g. the default for most web servers is 10 minutes, but it can be set for a shorter or longer period). Each PHP page that uses sessions must start with the statement :- session_start( ); Because sessions use cookies to define the user, session_start( ) must be called before any output is sent to the browser (i.e. before the <HTML> tag). Once the session has been registered values can be set as follows :- $_SESSION[„name‟] = „Dave‟;Dave Parkinson
  • PHP5 Page 47 To read the value of your Session variable into a variable in another PHP page on you site you do the following :- $somevariable = $_SESSION[„name‟]; The Session object uniquely identifies visitors via cookies. This means Session variables will not persist across PHP pages if the user has cookies disabled. Although a session will delete itself automatically when the session expires there may be instances when you wish to delete the session, or individual session variables, manually. This can be done as follows. To delete a session variable you can use the unset ( ) function. unset($_SESSION[„name‟]; To delete all the session data use :- session_destroy( );2.12.3 Exercise 6 – Writing and Reading Cookies & Session Variables Add an additional page to your website and call it cookies. The new page should ask you to enter your name and age. The PHP page should look as follows when viewed by the client :- Your application should use the following MVC structure: The Model (class.cookies.php) should include a class called Cookies which contains methods to set the cookie, get the cookie and delete the cookie e.g.Dave Parkinson
  • PHP5 Page 48 <?php class Cookies { public function setCookie($key, $value) { if (strlen($value) == 0) { $return = false; } else { setcookie($key, $value); $return = true; } return $return; } public function getCookie($key) { if (isset($_COOKIE[$key])) { $return = $_COOKIE[$key]; } else { $return = false; } return $return; } public function deleteCookie($key) { if (isset($_COOKIE[$key])) { setcookie($key, ); $return = true; } else { $return = false; } return $return; } } Note that this class does not contain a constructor, it is just a collection of methods related to cookies that could be used on any page of your web site. The Model (class.sessions.php) should include a class called Sessions which contains methods to set the session variable, get the session variable and delete the session variable <?php class Session { public function __construct() { session_start(); } public function setSession($name, $value) { if (strlen($value) == 0) { $return = false; } else { $_SESSION[$name] = $value; $return = true; }Dave Parkinson
  • PHP5 Page 49 return $return; } public function getSession($name) { if (isset($_SESSION[$name])) { $return = $_SESSION[$name]; } else { $return = false; } return $return; } public function deleteSession($name) { if (isset($_SESSION[$name])) { unset($_SESSION[$name]); $return = true; } else { $return = false; } return $return; } } Note that in this case a constructor is required to call the session_start( ) function. The Controller (cookies.php) is responsible for controlling what happens when the web page is loaded and when the Submit button is pressed. When the web page is loaded it calls the view to display the input form. When the submit button is pressed the controller should set the „name‟ cookie to the value typed in the textbox and should set the „age‟ cookie to the value of age typed in the textbox. It should then post to a new page called cookiesreturn.php. <?php $view = new stdClass(); $view->pageTitle = Cookies and Sessions; require_once(Models/class.cookies.php); require_once(Models/class.sessions.php); $cookies = new Cookies(); $session = new Session(); if (isset($_POST[submit])) { $cookies->setCookie(name, $_POST[name]); $session->setSession(age, $_POST[age]); header(location: cookiesreturn.php); } require_once(Views/cookies.phtml); The View (cookies.phtml) is responsible for displaying the information on the web page. It has the following structure:Dave Parkinson
  • PHP5 Page 50 <?php require(template/header.phtml) ?> <p>Welcome to this site. Please enter your name and age below.</p> <form action="<?php echo $_SERVER[PHP_SELF]; ?>" method="post"> <div> Name: <input type="text" name="name" /><br /> Age: <input type="text" name="age" /><br /> <input type="submit" name="submit" value="submit" /> </div> </form> <?php require(template/footer.phtml) ?> The page cookiesreturn is used to display the data held in the cookie and the session variable. It has the following MVC structure: The Controller (cookiesreturn.php) is responsible for reading the values of the cookie and session variable and passing the information to the view <?php $view = new stdClass(); $view->pageTitle = Cookies and Sessions; require_once(Models/class.cookies.php); require_once(Models/class.sessions.php); $cookies = new Cookies(); $session = new Session(); $view->name = $cookies->getCookie(name); $view->age = $session->getSession(age); require_once(Views/cookiesreturn.phtml); The View (cookiesreturn.phtml) displays the values of the cookie and the session variable on the screen. <?php require(template/header.phtml) ?> <p>Hello <?php echo htmlentities($view->name); ?>, Welcome to this website, you passed this value in a cookie</p> <p>Your age is: <?php echo htmlentities($view->age); ?>. You passed this value in a session variable</p> <?php require(template/footer.phtml) ?>Dave Parkinson
  • PHP5 Page 512.12.4 Query String If you only need to maintain state for the duration of the users visit to your site you can easily use cookies. However if the client has turned off cookies in his browser this method will not work. If this is the case, and all you need to persist is simple data types, you can pass the information in the HTTP headers using a querystring. The $_GET superglobal variable can process information attached to the URL of the PHP page if it is formatted in name/value pair, with each name and value separated by an equals sign (=), and each name/value pair separated from one another by an ampersand (&). (Note that unlike using POST to pass information, the information sent in this manner is visible to others and there are limitations on the amount of data that can be sent) In order to pass this information to another web page within my site all I need to do is append the information onto the URL for the next web page. For example :- <a href=”mynextpage.php?name=Dave&age=21”>Click for next page</a> On the next page of the web site I can recover the information passed in the query string using the Request object as follows :- $strVar1 = $_GET[‘name’]; $strVar2 = $_GET[‘age’]; this will load the name and age information into two variables. The advantage of using the this method is that it will always work regardless of how the user configures his browser settings. Note that however as soon as the client leaves your web site all the information is lost.2.12.5 Exercise 7 – Passing data between PHP pages Add an additional page to your website and call it querystring. Create a webpage (querystring.php) containing a table with the following information: When the user clicks on a buy link he should be sent to a new page (purchase.php) which should show the correct information depending on which “buy” link is selected. For example if you choose the Panasonic DVD:Dave Parkinson
  • PHP5 Page 52 For each of the links to the “buy” page (purchase.php) you should add the Item information and the Cost of the item to the query string associated with the link Hints: 1. In order to create a two page web site we will need to create two Controllers (querystring.php and purchase.php along with their corresponding Views). Note that this particular example will not require a Model. querystring.php Contains the require_once statement to load the View (querystring.phtml) querystring.phtml Contains the HTML required to display the table and the data within it (see below) <?php require(template/header.phtml) ?> <table class="datatable"> <thead> <tr> <th>Item</th><th>Description</th><th>Cost</th><th>Purchase</th> </tr> </thead> <tbody> <tr> <td>Sony TV</td> <td>32" LCD Widescreen</td> <td>&pound;950</td> <td> <a href="purchase.php?item=SonyTV&amp;cost=950">buy</a> </td> </tr> <tr> <td>Panasonic DVD</td> <td>DVD Player</td> <td>&pound;80</td> <td> <a href="purchase.php?item=PanasonicDVD&amp;cost=80">buy</a> </td> </tr> <tr> <td>Philips Video</td> <td>VHS Video Recorder</td> <td>&pound;110</td> <td> <a href="purchase.php?item=PhilipsVideo&amp;cost=110">buy</a> </td> </tr> </tbody> </table> <?php require(template/footer.phtml) ?>Dave Parkinson
  • PHP5 Page 53 purchase.php Obtains data from the querystring (e.g. $_GET[item] )and populates the variables item and cost within the primitive object called view. Contains the require_once statement to load the View (purchase.phtml) purchase.phtml Outputs the information contained in $view->item and $view->cost to a table on the screen. Provides return link to querystring.phpDave Parkinson
  • PHP5 Page 54 Chapter 3 : MySQL3.1 Introduction MySQL (www.mysql.com) is the world‟s most popular relational database (it is free to most users, however you should pay for a licence if you are making money from the sales or incorporation of the MySQL product). MYSQL is developed and supported by MySQL AB, a company based in Sweden, now a subsidiary of Sun Microsystems. MySQL runs directly on the web server and hence provides a far higher performance than an Access database. MySQL has been known to handle databases as large as 60,000 tables containing more than 5 billion records. MySQL databases run on the web server, either a remote database or a version of MySQL running on your local PC. In either case you need a program to manage the database (add tables and data). The most popular program for managing a MySQL database is phpMyAdmin.3.2 Creating a database using phpMyAdmin MySQL is a database engine. In order to create individual databases and populate them with tables and data with must use a program that provides an interface to MySQL (e.g. phpMyAdmin). phpMyAdmin is an open source tool written in PHP intended to handle the administration of MySQL over the World Wide Web. It can perform various tasks such as creating, modifying or deleting databases, tables, fields or rows; executing SQL statements; or managing users and permissions. It also provides the capability of exporting your database in SQL so it can be imported into another MySQL database. It is included with mostDave Parkinson
  • PHP5 Page 55 providers of MySQL databases and is also included on the locally hosted version of MySQL installed using XAMPP. You can open phpMyAdmin from within XAMPP by clicking on the Admin button next to MySQL as shown below: This will open phpMyAdmin in your default browser as shown below: You can then create a new database called test:Dave Parkinson
  • PHP5 Page 56 Now create a table called mytable containing five fields: Set up the following field names and also set the field types as shown below: Set the index fields for the id field to PRIMARY (makes the id field the primary key). Also set the id field to auto increment. Select Insert to add a record: Add a number of records to populate the database as shown below:Dave Parkinson
  • PHP5 Page 573.3 Using PHP with MySQL In order to interact with a MySQL using PHP we use PHP Data Objects (PDO). Many PHP programmers learned how to access databases by using either the mysql or mysqli extensions. Since PHP 5.1, there‟s been a better way. The PHP Data Objects (PDO) extension defines a lightweight, consistent interface for accessing databases in PHP. Each database driver that implements the PDO interface can expose database-specific features as regular extension functions. Note that you cannot perform any database functions using the PDO extension by itself; you must use a database-specific PDO driver to access a database server. PDO provides a data-access abstraction layer, which means that, regardless of which database youre using, you use the same functions to issue queries and fetch data When you want to retrieve information from a database, you need to use a three-step process. 1. Establish a connection to the database 2. Query the database, asking the database for the information you require 3. Close the database connection3.3.1 Setting up and tearing down the connection Interaction with the MySQL database is bookended by connection setup and tear-down, consisting of connecting to the server and selecting a database, and closing the connection, respectively. In order to interact with the MySQL server using an object oriented interface you must first instantiate the PDO class via its constructor $dbh = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass); The terms host, user, and pass and dbname apply to the MySQL database you are trying to access. For example if the database is set up on localhost as described earlier the connection statement would be :-Dave Parkinson
  • PHP5 Page 58 $host = localhost; $dbname = test; $user = root; $pass = ; $dbh = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass); Note that for the „ root‟ username the password is „blank‟. Once a database has been successfully connected you can then execute database queries against it. Executing queries such as selecting, inserting, updating and deleting information is covered later. Once you have finished with the database you should close the connection as follows: $dbh = null;3.4 Interacting with the Database The vast majority of your queries will revolve around creation, retrieval, update and deletion tasks, collectively known as CRUD. In order to interact with the database we need to use Structured Query Language.3.4.1 Structured Query Language Structured Query Language, or SQL (pronounced sequel), is an efficient language used by developers to retrieve, add, delete, or modify information in a relational database. Nearly all modem databases communicate via this standard language, so its essential that you learn the basics of SQL. The SELECT Statement The SELECT statement is probably the most common SQL statement. Its basic purpose is to grab a set of data from a database table. The syntax for the SELECT statement is as follows: SELECT selectlist FROM tablename [WHERE searchCondition] [ORDER BY orderbyExpression [ASC | DESC ]] The structure follows basic English. selectlist is generally a comma-delimited list of the columns you want to return. For example, surname , firstname would return the values in these two columns. Additionally, an asterisk (*) can be used to return all of the columns from a particular table. tablename is the name of the table to grab the data from. An example of a simple SELECT statement to get all the data from the table in the database created earlier is: SELECT * FROM mytableDave Parkinson
  • PHP5 Page 59 Note that you shouldnt use SELECT * because often it returns more information than you need. This can result in decreased performance. Instead, explicitly specify the columns you need to return. This will take a bit longer when coding, but your code will enjoy performance benefits. For example if we only wanted to return the data in the surname and firstname columns we should use : SELECT surname, firstname FROM mytable SELECT statements always return all the rows in your database (unless qualified with a WHERE clause). You can use the WHERE clause to specify additional criteria for the returned data. A WHERE clause can generally be any logical statement, similar to an if statement in regular programming languages. For example:- SELECT * FROM mytable WHERE firstname=Chris SELECT * FROM mytable WHERE firstname=Chris AND surname=Smith The first statement returns only records where the firstname field value is "Chris". The second statement returns only the records where firstname field value is "Chris" and the surname field is equal to "Smith". To use wildcards for your SQL WHERE clause criteria, you can use the LIKE keyword followed by wildcard operators. The LIKE keyword accepts the following operators. % A string of zero or more characters _ Exactly one character [ ] A specific character in the given set For example :- 1. SELECT * FROM mytable WHERE firstname LIKE %s% 2. SELECT * FROM mytable WHERE firstname LIKE _hris 3. SELECT * FROM mytable WHERE firstname LIKE [abcd]hris The SQL statement on line 1 returns any rows where the firstname contains an s somewhere in the value. The % operator means a string of zero or more characters. The SQL statement on line 2 returns any records where the first name contains anyone letter, followed by the string "bris". The SQL statement on line 3 returns any records where the first name contains a string that begins with any of the letters a, b, c, or d, followed by the string "bris". The ORDER BY clause specifies the order in which the data is returned, such as alphabetical order. Without this clause, theres no way to know in what order the database will return records. Even though they may have been entered alphabetically during data entry, that doesnt mean the records will be returned the same way. The ORDER BY clause lets you specify which columns to order the data by, and how. If used with columnsDave Parkinson
  • PHP5 Page 60 containing string characters, it converts those characters into their ASCII equivalents and sorts based on those numbers. For example :- SELECT * FROM mytable ORDER BY firstname ASC This statement returns all records sorted alphabetically by first name. Likewise, specifying DESC sort order instead of ASC returns reverse-alphabetic order. You can specify multiple columns delimited by commas in the ORDER BY clause as well, each with its own sort order. SQL will use the additional columns if the first one contains any duplicate data. For example, the following statement would order the data by name unless two names were identical when it would order by first name. SELECT * FROM mytable ORDER BY Name, firstname ASC You can also use SELECT statements to return data from more than one table at once. This is done with a comma-delimited list of table names for the tablename argument. The INSERT Statement Another common SQL statement is the INSERT statement, which is used to insert new rows into a database table. Its basic syntax is as follows: INSERT [INTO] tablename [column list)] VALUES (DEFAULT | NULL | expression) This statement is similar in syntax to SELECT. For example :- INSERT INTO mytable (firstname, surname, address, phone) VALUES (Chris,Payne,135 Ash Street,8006596598) This statement inserts a new row with the field values specified in the VALUES clause. The data type you supply in VALUES must match the data type in the corresponding column or you will receive an error. Also, if you specify a column, you must specify a value or youll get another error. The UPDATE Statement The UPDATE statement updates existing rows in a database table. You can specify a WHERE Clause with this statement to update only a subset of the values in a database table. The syntax is as follows: UPDATE tablename SET column name = (DEFAULT | NULL | expression) [WHERE searchCondition] If you leave off the WHERE clause, the specified column(s) are updated in every row in the database. Be very careful with this statement, because its easy to ruin your data! An example of the use of the UPDATE statement is :- UPDATE mytable SET address = 136 Ash Street, phone = 0161 2954476Dave Parkinson
  • PHP5 Page 61 WHERE firstname = Chris AND surname = Payne This statement changes the Address record where the firstname is "Chris" and the surname is "Payne”. You can specify only the columns you need in the column name list, and the WHERE clause is exactly the same as the SELECT statement. The DELETE Statement The DELETE statement deletes rows from a database. The syntax is : DELETE FROM tablename [WHERE searchCondition] The DELETE statement is very simple. The only thing to remember is the WHERE clause, which is very important. If you dont specify this clause, the DELETE statement will delete all the rows in the entire table, normally a disastrous occurrence. Again, the WHERE clause is exactly the same as for the SELECT statement. For example, the following deletes only records with the firstname "Chris": DELETE FROM mytable WHERE firstname = Chris3.5 Exercise 8 - Reading data from a MySQL Database In order to read from a database the following actions must be performed :- 1. Connect to MySQL 2. Select the database 3. Perform SQL Query 4. Retrieve and Display Query Results The complete code to read data from the table called mytable within a database called test that we created earlier is shown below. Add an additional page to your website and call it database. That web page should display the contents of your database table. The web page should look as follows when viewed by the client (initially it only displays the surnames as an unordered list) :-Dave Parkinson
  • PHP5 Page 62 Your application should use the following MVC structure: The Model should include a class called Database (class.database.php) which contains methods to connect to the database. The Model also contains an abstact class called tableAbstract (class.tableAbstact.php) which other classes can inherit and contains generic functionality required by any database table class (these two classes could be used with any PHP application). Another class within the model, personTable (class,personTable.php), works in conjunction with the tableAbstract class to retrieve specific data required by this application. As the Database class will be returning an array of data it is easier to access and manipulate this data if it is in an object. The Model should also include a class called Person (class.person.php) that places information from the array obtained in the database class and places it in an object. The Person class (class.person.php) contains the following code: <?php class Person { protected $id, $surname, $firstname, $address, $phone; public function __construct($dbrow) { $this->id = $dbrow[id]; $this->surname = $dbrow[surname]; $this->firstname = $dbrow[firstname]; $this->address = $dbrow[address]; $this->phone = $dbrow[phone]; } public function getId() { return $this->id; } public function getSurname() { return $this->surname; } public function getFirstname() { return $this->firstname; } public function getAddress() { return $this->address; } public function getPhone() { return $this->phone; } } This code is self explanatory. It has a number of properties that match the items in the database table. When the object is instantiated using the constructor, it sets the values of these properties from the row within the database table. It also provides a number of methods to read the properties. Before we code the Database class we need to discuss Singleton’s.Dave Parkinson
  • PHP5 Page 63 What is a Singleton? - There are times in programming which we do not want to create multiple instances of an object. A good example is of a database connection object. If there is already an instance of a database connection object in existence, there is no point in creating another connection. To solve this problem we use singletons. Static Methods and Properties Normally, if we want to invoke methods or get properties from a class we need to create an instance of the class (as an object) and call the method from the object such as: $myObject = new MyClass(); $myObject->myMethod(); $myObject->myProperty; This looks familiar as it is what we have already been using. Sometimes we want to be able to use methods and properties without the need for instantiating an object. To do this we use static methods and properties. These are called using a slightly different syntax to methods and properties from an object. Instead of the arrow ( -> ) a double colon is used ( :: ). As there is no object created, these are called directly from the class. MyClass::myStaticMethod(); MyClass::myStaticProperty; Static methods/properties are written in the same way as normal methods/properties except they have the keyword "static" in front of them. Also, as there is no object, the keyword "this" is no longer applicable. Instead, the word "self" is used to refer to the class. protected static $myStaticProperty; public static function myStaticMethod { return self::$myStaticProperty; } Static methods/properties also follow the same encapsulation (public, private and protected) rules as normal methods/properties. A public method and property can be accessed from anywhere, a private can only be accessed by code within the class and a protected by code within the class or inherited class. The Singleton Design Pattern Static methods are used in singletons to control instances of itself. To stop any other piece of code creating an instance of the object, a singleton has a private constructor. This means that only code within the class itself (or object) can call the construction of the object. The object is then stored as a static property within the class. The static method then checks the state of the property, and decides whether a new object is needed to be created. By convention the static method is called getInstance. Class MyClass { protected static $instance = null; protected $myProperty; //standard object property public static function getInstance() { if(self::$instance === null) { //checks if object exists $instance = new self(); //if not creates a new instanceDave Parkinson
  • PHP5 Page 64 } return $instance; } private function __construct() { //constructor stuff here } } So, from this point onwards the rest of the code does not need to know whether an instance of the class exists or not. We get the instance (or create the instance if one does not exist) by calling. $myObject = MyClass::getInstance(); Using the above techniques, the Database class (class.database.php) contains the following code: class Database { protected static $instance = null; protected $dbh; public static function getInstance() { $username = username; // connection info $password = password; $host = localhost; $dbname = myDatabase; if(self::$instance === null) { //checks if the object exists // creates new instance if not, sending in connection info self::$instance = new self($username, $password, $host, $dbname); } return self::$instance; } private function __construct($username, $password, $host, $database) { $this->dbh = new PDO("mysql:host=$host;dbname=$database", $username, $password); // creates the database handler with connection info } public function getDbh() { return $this->dbh; // returns the database handler to be used elsewhere } public function __destruct() { $this->dbh = null; // destroys the database handler when no longer needed } }Dave Parkinson
  • PHP5 Page 65 The tableAbstract class (class.tableAbstract.php) contains the following code: <?php require_once Models/class.database.php; abstract class TableAbstract { protected $name; protected $primaryKey = id, $dbh, $db; public function __construct() { $this->db = Database::getInstance(); $this->dbh = $this->db->getDbh(); } public function readtbl() { $sql = SELECT * FROM .$this->name; $results = $this->dbh->prepare($sql); $results->execute(); return $results; } public function fetchByPrimaryKey($key) { $sql = SELECT * FROM .$this->name. WHERE .$this->primaryKey. = :id LIMIT 1; $results = $this->dbh->prepare($sql); $results->execute(array(:id => $key)); return $results->fetch(); } } The constructor __construct( ) for this class instantiates the object and gets the database connection handler. The function readtbl( ) returns all the data in the table $name. It initially creates a variable $sql and initialises this with the SQL Query: Select * from ‘mytable’ It then actions the query and returns the results of query as a PDO data object ($results) The function fetchByPrimaryKey( ) fetches a specific row of data from the database table. We will be using this function later. These are general methods that can be used to access data from any database. Within our application we require specific functions to read, write, edit, delete data from our database. These functions are held in the class personTable (class.personTable.php) Which contains the following code: <?php require_once Models/class.person.php; require_once Models/class.tableAbstract.php; class PersonTable extends TableAbstract {Dave Parkinson
  • PHP5 Page 66 protected $name = parkinson_mytable; protected $primaryKey = id; public function fetchAllPeople( ) { $results = $this->readtbl(); $personArray = array(); while ($row = $results->fetch( )) { $personArray[ ] = new Person($row); } return $personArray; } The function fetchAllPeople returns an object, $personArray, created using the Person class which has been included at the top of this code. It initially uses the readtbl function within the TableAbstract class to returns the table data as a PDO data object ($results) An array ($personArray) is then declared. A while loop then loops through the data table row by row and adds a new Person object to the array $personArray. This array of Person objects is then returned. The Controller (database.php) is responsible for controlling what happens when the web page is loaded. It contains the following code: <?php $view = new stdClass(); $view->pageTitle = Database; require_once(Models/class.personTable.php); $database = new PersonTable(); $view->peopleList = $database->fetchAllPeople(); require_once(Views/database.phtml); On loading the database.php page the constructor for the database class is called to open a database connection. Data from the database query is the loaded into the peopleList property of the view object. The view is then loaded. The View (database.phtml) is responsible for displaying the information on the web page. It has the following structure: <?php require(template/header.phtml) ?> <form action="<?php echo $_SERVER[PHP_SELF]; ?>" method="post"> <h1>Read Database</h1> <ul> <?php foreach ($view->peopleList as $person) : ?> <li> <?php echo $person->getSurname(); ?> </li> <?php endforeach; ?> </ul> </form> <?php require(template/footer.phtml) ?> The view contains a section of PHP code which use the foreach statement to loop through the database table one row at a time, outputting the Surname field to the web page in the form of an unordered list.Dave Parkinson
  • PHP5 Page 67 Try changing this code to output the data from the database in the form of a table as shown below. Try out various different versions of the SELECT statement (using WHERE and ORDER) to change the data retrieved from the database table.3.6 Exercise 9 – Inserting, Updating and Deleting Records in a Database Add an additional page to your website and call it dbedit. The exercise should use the same database as the one used in the previous exercise. The user should enter the data for the database in an web page which allows the user to read from, append to, alter, and delete from the database. For example :-Dave Parkinson
  • PHP5 Page 68 In order to complete this exercise you should first modify the Database class to include the following methods to insert new rows, edit rows and delete rows. Because we are inputting data directly into the database we need to ensure we are not party to an SQL Injection attack. (An attack of this form can occur when user input is not filtered for escape characters and is then passed into an SQL statement. This results in the potential manipulation of the statements performed on the database by the end user of the application). Database abstraction layers like PHPs Portable Data Objects (PDO) are not a new concept, but a lot of developers dont seem to realise the security benefit theyre getting for free by using them - inherent protection against SQL injection. SQL injection is the buffer overflow of the web application world - its been around forever, and every web application developer should know how to write secure code thats not vulnerable to it. For those not in the know, SQL injection is a technique whereby a malicious attacker can exploit inadequate data validation to inject arbitrary SQL code into your applications queries and have it executed as though it is a legitimate query. We wont go too deeply into SQL injection, but heres a simple example: The front page of your application has a login form, which is submitted to a PHP script to validate the users credentials and allow or deny access to the application. The login form submits two variables by POST as follows: username=fred&password=Fr3dRul3z The POSTed data is then used to build an SQL query to validate the credentials, like this:Dave Parkinson
  • PHP5 Page 69 $sql = "SELECT * FROM users WHERE username = ".$_REQUEST[username]." AND password = ".$_REQUEST[password].""; This would result in the SQL query: SELECT * FROM users WHERE username = fred AND password = Fr3dRul3z Assuming a row exists in the database with these credentials, the user would be allowed to log in. An attacker could easily circumvent this authentication scheme by escaping out of the username field into the SQL query by entering nothing into the password field and this into the username field: OR 1==1 -- The resulting SQL query string would look like this: SELECT * FROM users WHERE username = fred OR 1==1 -- AND password = Which would select all users from the database as the condition 1==1 will always be true. The rest of the query is discarded with the comment operator --. The way to avoid this kind of attack is to sanitise the data submitted to the form by escaping everything that could be used to escape the confines of the quotes around the fields (e.g. mysql_real_escape_string() if youre using MySQL). However we are using PDO with prepared statements. When building statements with PDO, instead of building the SQL string manually as demonstrated earlier, we build the statement with placeholders like this: $sql = "INSERT INTO fruits (name, price) VALUES (:name, :price)"; and then execute the query with a data set passed to the abstraction layer as follows: $sth = $dbh->prepare($sql); $sth->execute(array( :name => $data[name], :price => $data[price] )); When the data is handed to PDO like this, it then either passes the data on to the database driver directly, or builds the query internally in a safe manner with any potentially malicious data encoded or escaped. As you can see, this is an easy way around the problem of SQL injection. Having decided that by using PDO we do not need to worry and SQL injection attacks we now can add further methods to insert a rowin the database (inserttbl), edit a row in the database (edittbl), and to delete a row in the database (deletetbl). public function inserttbl($data) { $sql = INSERT INTO mytable (surname, firstname, address, phone) VALUES (:surname, :firstname, :address, :phone); $result = $this->dbh->prepare($sql); $result->execute(array( :surname => $data[surname], :firstname => $data[firstname], :address => $data[address],Dave Parkinson
  • PHP5 Page 70 :phone => $data[phone] )); return $this->dbh->lastInsertId(); } public function edittbl($data) { $sql = UPDATE mytable SET firstname = :firstname, address = :address, phone = :phone WHERE surname = :surname; $result = $this->dbh->prepare($sql); return $result->execute(array( :surname => $data[surname], :firstname => $data[firstname], :address => $data[address], :phone => $data[phone] )); } public function deletetbl($data) { $sql = DELETE FROM mytable WHERE surname = :surname; $result = $this->dbh->prepare($sql); return $result->execute(array( :surname => $data[surname] )); } The view should modified to add the new form elements. The HTML required for the form design shown above is: <?php require(template/header.phtml) ?> <form action="<?php echo $_SERVER[PHP_SELF]; ?>" method="post"> <h1>Database Editor</h1> <table class="inputtable"> <tr> <td class="label">Surname:</td> <td class="inputtd"> <input name="surname" type="text" class="standardwidth" /></td> </tr> <tr> <td class="label"> First Name:</td> <td class="inputtd"> <input name="firstname" type="text" class="standardwidth" /></td> </tr> <tr> <td class="label">Address:</td> <td class="inputtd"> <input name="address" type="text" class="standardwidth" /></td> </tr> <tr> <td class="label">Phone Number:</td> <td class="inputtd"> <input name="phone" type="text" class="standardwidth" /></td> </tr> </table> <br /> <table class="radbuttons"> <tr> <td class="standardwidth"> <input name="op" type="radio" checked="checked" value="rdbase" /> Read from Database</td> <td><input name="op" type="radio" value="cdbase" />Change Entry (enter data in form)</td>Dave Parkinson
  • PHP5 Page 71 </tr> <tr> <td class="standardwidth"> <input name="op" type="radio" value="adbase" />Add to Database</td> <td><input name="op" type="radio" value="ddbase" />Delete Entry (enter name in form)</td> </tr> </table> <br /> <input name="submit" type="submit" value="submit" /> <input name="reset" type="reset" value="reset" /> <br /> </form> <?php if (count($view->peopleList) > 0) { ?> <table class="datatable"> <tr> <th><strong>Surname</strong></th> <th><strong>First Name </strong></th> <th class="standardwidth"><strong>Address </strong></th> <th><strong>Phone</strong></th> </tr> <?php foreach ($view->peopleList as $person) : ?> <tr> <td> <?php echo htmlentities($person->getSurname()); ?> </td> <td> <?php echo htmlentities($person->getFirstname()); ?> </td> <td> <?php echo htmlentities($person->getAddress()); ?> </td> <td> <?php echo htmlentities($person->getPhone()); ?> </td> </tr> <?php endforeach; } ?> </table> <?php require(template/footer.phtml) ?> The view should then show the data from the database in a table as per the previous exercise. The controller should be modified to check which option has been selected and take the required action.3.7 Passing Data from a Database to a PHP Page When designing interactive web sites it is often desirable to display information in a database to the client and have the client select a particular item from the database. For example, on a sales site you may wish the user to identify which item he wishes to purchase by clicking on an active link displayed within the database.3.7.1 Exercise 10 – Passing Information from a MySQL Database Add an additional page to your website and call it passinginfo. Create a new page (passinginfo.php) which reads the information from your previously created table „mytable‟ and displays the surname, firstname and address fields. The finalDave Parkinson
  • PHP5 Page 72 field „phone‟ should contain a link to another page (phone.php). The query string for this link should pass the surname and phone number to this new web page. The table should be displayed as follows: When the user clicks on a phone link he should be sent to a new web page (phone.php) which should show the persons phone number depending on which “phone” link is selected. For example if you choose Walker: HINT – The links to the “phone” page (phone.php) should be generated in the passinginfo.phtml by using the surname and phone from the item object to generated a link with a query string as an extra column in the table. The code generate the link and pass the information required via the query string is given below: <a href="phone.php?surname=<?php echo $person->getSurname();?>&amp;phone=<?php echo $person->getPhone();?>">phone</a> What are the security problems associated with this example? How could you overcome these problems? Hint: consider use of the function fetchByPrimaryKey( ) in the TableAbstract class.3.8 Exercise 11 – Displaying Pictures from a MySQL Database A common feature on Web Sites is the ability to upload and display pictures on your web page. Pictures cannot be stored directly in a database. In order to display a picture on a web site we must upload the picture to a known location on the web server (in this case we will load it onto the images directory), and we must know the name of the file to display (this can be stored in a table within your MySQL Server database).Dave Parkinson
  • PHP5 Page 73 In order to store pictures in our database we must first edit our database table (mytable) to add an extra column as shown below: Add an additional field to your database table and name in photo. Add a few images (.jpg) to the images directory in your project and put the name of these images in your database table as shown below. Add an additional page to your website and call it dbphoto which reads the information from „mytable‟ and displays the surname, firstname, address fields, phone and the picture associated with each entry. To display the table we need to take the following steps: 1. Modify the model (class.person.php) to add an additional function getPhoto( ) 2. Make a copy of the View (database.phtml) and name it dbphoto.phtml. Modify this View to add an extra column to the table and display the file specified in the database table in this column as shown below: <img src="images/<?php echo $person->getPhoto(); ?>" alt="no picture" /> 3. Create a new controller (dbphoto.php) and add the following code: <?php $view = new stdClass(); $view->pageTitle = Database Photos; require_once(Models/class.personTable.php); $database = new PersonTable(); $view->peopleList = $database->fetchAllPeople(); require_once(Views/dbphoto.phtml); Test your application as shown below:Dave Parkinson
  • PHP5 Page 74 In order to add new entries to the database from within the web application we will need to be able to upload pictures form a local PC to the web server. The application can be modified as follows to achieve this: 1. Modify the View (dbphoto.phtml) to change the form action as follows: <form action="<?php echo $_SERVER[PHP_SELF]; ?>" method="post" enctype="multipart/form-data"> Then add the following code after the table has been displayed: Choose File:<br /> <input type="file" name="filetoupload" value="" /><br /> <input type="submit" name="submit" value="Upload File" /><br /> 2. Add a new Model (class.fileupload.php) containing the following: <?php class Fileupload { protected $filename, $filetoupload; public function __construct($filetoupload) { $this->filetoupload = $filetoupload; } public function upload() { if (is_uploaded_file($this->filetoupload[tmp_name]) ); { if ($this->filetoupload[type] == image/jpeg || $this->filetoupload[type] == image/pjpeg) { $result = move_uploaded_file($this->filetoupload[tmp_name], getcwd() . /images/ . $this->filetoupload[name]); } else { $result = false; } } return $result; } public function getFilename() { return $this->filetoupload[name]; } }Dave Parkinson
  • PHP5 Page 75 3. Modify the controller (dbphoto.php) as follows: <?php $view = new stdClass(); $view->pageTitle = Database Photos; $view->message=; require_once(Models/class.personTable.php); require_once(Models/class.fileupload.php); if (isset($_POST[submit])) { $fileupload = new Fileupload($_FILES[filetoupload]); $result = $fileupload->upload(); if (!$result) { $view->message = Error uploading file.; } else { $view->message = $fileupload->getFilename() . has been uploaded.; } } $database = new PersonTable(); $view->peopleList = $database->fetchAllPeople(); require_once(Views/dbphoto.phtml); Test your application. Once the Upload File button is pressed the file will be uploaded to the „images‟ directory on the web site and a message including the uploaded filename will be displayed on the web page. If a error occurs an error message will be displayed.Dave Parkinson