php essentials

102
PHP Essentials 1 PHP Essentials

Upload: prasath-ramachandiran

Post on 26-Jan-2015

3.143 views

Category:

Education


1 download

DESCRIPTION

 

TRANSCRIPT

Page 1: PHP Essentials

PHP Essentials 1

PHP Essentials

Page 2: PHP Essentials

PHP Essentials 2

About This Book

This book is the PDF version of the online book “PHP Essentials”     at http://www.techotopia.com/index.php/PHP_Essentials

Techotopia  is a library of free on­line IT books covering a wide range of topics including operating systems, programming, scripting, system administration, databases, networking and much more.   The   IT   Essentials   series   of   books   are   designed   to   provide   detailed   information   that   is accessible to both experienced and novice readers. Each on­line book contains everything that is needed to gain proficiency in the corresponding technology subject area.

Compiled as PDF by R. Prasath <prasath.ram8   @gmail.com   >

Copyright 2007 Techotopia. All Rights Reserved.

Page 3: PHP Essentials

PHP Essentials 3

Table of Contents1. About PHP essentials........................................................................................................................7

Intended Audience..........................................................................................................................72. The History of PHP..........................................................................................................................8

The Creation of PHP.......................................................................................................................8PHP 3 Hits the Big Time................................................................................................................8PHP 4 ­ Optimization, Scalability and More..................................................................................9PHP 5 ­ Object Orientation, Error Handling and XML .................................................................9How Popular is PHP?......................................................................................................................9

3. An Overview of PHP......................................................................................................................10How Does PHP Work?..................................................................................................................10

4. Creating a Simple PHP Script.........................................................................................................13The PHP Code Delimiters.............................................................................................................13Testing the PHP Installation..........................................................................................................13Embedding PHP into an HTML File ...........................................................................................15Embedding HTML into a PHP Script...........................................................................................16

5. Commenting PHP Code..................................................................................................................17PHP Single Line Comments.........................................................................................................17PHP Multi­line Comments............................................................................................................18

6.  An Introduction to PHP Variables.................................................................................................19Naming and Creating a Variable in PHP.......................................................................................19Assigning a Value to a PHP Variable............................................................................................19Accessing PHP Variable Values...................................................................................................20Changing the Type of a PHP Variable..........................................................................................21Checking Whether a Variable is Set..............................................................................................21Understanding PHP Variable Types..............................................................................................22The PHP Integer Variable Type....................................................................................................22The PHP Float Variable Type.......................................................................................................22The PHP Boolean Variable Type..................................................................................................23The PHP String Variable...............................................................................................................23Extracting and Writing String Fragments.....................................................................................24Creating PHP heredoc Strings .....................................................................................................25

8. PHP Constants................................................................................................................................26Defining a PHP Constant..............................................................................................................26Checking if a PHP Constant is Defined........................................................................................26Using a Variable as a Constant Name ..........................................................................................27Predefined PHP Constants ...........................................................................................................28

PHP Script and Environment Related Constants......................................................................28PHP Mathematical Constants ......................................................................................................28

9. PHP Operators................................................................................................................................29PHP Assignment Operators..........................................................................................................30PHP Arithmetic Operators............................................................................................................30PHP Mathematical Operators........................................................................................................31

Page 4: PHP Essentials

PHP Essentials 4

PHP Comparison Operators..........................................................................................................32PHP Logical Operators.................................................................................................................33PHP Increment and Decrement Operators ...................................................................................34PHP String Concatenation Operator.............................................................................................34Concatenation of Numbers and Strings in PHP ...........................................................................35PHP Execution Operator ­ Executing Server Side Commands ....................................................36

10. PHP Flow Control and Looping....................................................................................................37PHP Conditional Statements.........................................................................................................37

The PHP if ... else Statements ..................................................................................................38PHP Looping Statements..............................................................................................................39PHP for loops................................................................................................................................39PHP while loops...........................................................................................................................40

PHP do ... while loops...............................................................................................................41PHP switch Statements.................................................................................................................42Breaking a Loop ..........................................................................................................................44

Breaking Out of Nested Loops .................................................................................................4411.  PHP Functions..............................................................................................................................45

What is a PHP Function?..............................................................................................................45How to Write a PHP Function......................................................................................................45Returning a Value from a PHP Function......................................................................................45Passing Parameters to a PHP Function ........................................................................................46Calling PHP Functions .................................................................................................................46Passing Parameters by Reference..................................................................................................47Returning Values by Reference ....................................................................................................48Functions and Variable Scope ......................................................................................................49

12.  PHP Arrays..................................................................................................................................50Create a PHP Array.......................................................................................................................50Accessing Elements in a PHP Array.............................................................................................51Creating an Associative Array .....................................................................................................51Accessing Elements of an Associative Array ...............................................................................51Creating Multidimensional PHP Arrays ......................................................................................52Accessing Elements in a Multidimensional PHP Array ..............................................................52Using PHP Array Pointers ...........................................................................................................53Changing, Adding and Removing PHP Array Elements .............................................................53Looping through PHP Array Elements.........................................................................................54Replacing Sections of an Array ...................................................................................................55Sorting a PHP Array ....................................................................................................................55Sorting Associative Arrays ..........................................................................................................56Getting Information About PHP Arrays & other Array Functions ..............................................56

13. Working with Strings and Text in PHP.........................................................................................56Changing the Case of a PHP String .............................................................................................56Converting to and from ASCII Values .........................................................................................57Printing Formatted Strings in PHP ..............................................................................................58

PHP printf Formatting Specifiers .............................................................................................58

Page 5: PHP Essentials

PHP Essentials 5

Finding the Length of a PHP String ............................................................................................60Converting a String into a PHP Array .........................................................................................60Removing Leading and Trailing Whitespace from a PHP String ................................................61Comparing Strings in PHP............................................................................................................61String Comparison Functions Return Value ................................................................................62Accessing and Modifying Characters in String ...........................................................................62Searching for Characters and Substrings in a PHP String ...........................................................63Extracting and Replacing Substrings in PHP ..............................................................................63Replacing All Instances of a Word in a PHP String ....................................................................64

14. PHP, Filesystems and File I/O.......................................................................................................65Opening and Creating Files in PHP .............................................................................................65Closing Files in PHP ....................................................................................................................66Writing to a File using PHP .........................................................................................................66Reading From a File using PHP ...................................................................................................67Checking Whether a File Exists ...................................................................................................68Moving, Copying and Deleting Files with PHP ..........................................................................68Accessing File Attributes .............................................................................................................68PHP Output Buffering .................................................................................................................69

15. Working with Directories in PHP.................................................................................................70Creating Directories in PHP ........................................................................................................70Deleting a Directory ....................................................................................................................70Finding and Changing the Current Working Directory ...............................................................70Listing Files in a Directory ..........................................................................................................71

16. An Overview of HTML Forms.....................................................................................................71Creating HTML Forms ................................................................................................................71HTML Text Object .......................................................................................................................72HTML TextArea Object ...............................................................................................................73The HTML Button Object ...........................................................................................................73HTML Check Boxes ....................................................................................................................74HTML Radio Buttons ..................................................................................................................75HTML Drop­down / Select Object ..............................................................................................76HTML Password Object ..............................................................................................................77

17. PHP and HTML Forms.................................................................................................................77Creating the Form ........................................................................................................................78Processing Form Data Using PHP ...............................................................................................78Processing Multiple Selections with PHP ...................................................................................80

18.  PHP and Cookies ­ Creating, Reading and Writing.....................................................................81The Difference Between Cookies and PHP Sessions ...................................................................81The Structure of a Cookie ............................................................................................................81Cookie Expiration Setting ............................................................................................................82Cookie path Setting ......................................................................................................................82Cookie domain Setting .................................................................................................................82Cookie Security Setting ...............................................................................................................82

Page 6: PHP Essentials

PHP Essentials 6

Creating a Cookie in PHP ............................................................................................................82Reading a Cookie in PHP ............................................................................................................83Deleting a Cookie ........................................................................................................................83

19. Understanding PHP Sessions........................................................................................................83What is a PHP Session? ...............................................................................................................83Creating a PHP Session ...............................................................................................................84Creating and Reading PHP Session Variables .............................................................................84Writing PHP Session Data to a File .............................................................................................85Reading a Saved PHP Session .....................................................................................................86

20. PHP Object Oriented Programming.............................................................................................86What is an Object? .......................................................................................................................87What is a Class? ...........................................................................................................................87How is an Object Created from a Class? .....................................................................................87What is sub­classing?....................................................................................................................87Defining a PHP Class ..................................................................................................................87PHP Class Constructors and Destructors .....................................................................................88Creating Members in a PHP Class ...............................................................................................88Defining and Calling Methods .....................................................................................................89Subclassing in PHP ......................................................................................................................91PHP Object Serialization .............................................................................................................92Getting Information about a PHP Object .....................................................................................94

21. Using PHP with MySQL..............................................................................................................94Creating a MySQL User Account ................................................................................................94Creating and Select MySQL Database ........................................................................................95Creating a MySQL Database Table .............................................................................................95Inserting Data into a MySQL Database Table .............................................................................96Connecting with PHP to a MySQL Server ..................................................................................96Selecting Records from a MySQL Database Using PHP ............................................................97Adding Records to MySQL Database using PHP ........................................................................98Modifying and Deleting MySQL Records using PHP .................................................................99Using PHP to get Information about a MySQL Database ...........................................................99

22. PHP and SQLite..........................................................................................................................100Creating an SQLite Database with PHP ....................................................................................100Using PHP to Add Records to an SQLite Database ...................................................................101Using PHP to Select Records from an SQLite Database ...........................................................101

Page 7: PHP Essentials

PHP Essentials 7

1. About PHP essentialsAny attempt to gauge the popularity of PHP on the internet results in statistics which prove 

difficult for the human mind to comprehend. As of April 2007 there were an estimated 20 million unique  web   domains   actively   using  PHP   to  generate   and   deliver   content.   While   it   is   hard   to conceptualize 20 million web servers using PHP, it is not hard to infer from this number that PHP has taken the web design and development community by storm since humble beginnings in 1995. 

The purpose of this book is bring the power and ease of use of PHP to anyone with a desire to  learn PHP, and in doing so,  join the tens of thousands of web developers who have already discovered the flexibility and productivity that comes with using PHP. 

The book is intended to cover all aspects of PHP. It begins by covering the history of PHP before providing a high level overview of how PHP works and why it is so useful to web developers. It then moves on to cover each area of PHP in detail, from the basics of the scripting language through  to  object  oriented programming,   file  and  filesystem handling  and MySQL and SQLite database  access.   In   addition,   chapters   are   also  provided  covering   the  creation  and handling  of HTML   based   forms   and   maintaining   state   using   cookies   and   PHP   sessions.   All   topics   are accompanied by extensive real world examples intended to bring theory to life. 

Intended Audience

It is anticipated that the typical reader already has some web based experience at least in terms of understanding the concepts of a web server and creating HTML based content. While prior programming and scripting experience will be beneficial to the reader, this book is designed such that even the non­programmer can quickly get up to speed with PHP.

Page 8: PHP Essentials

PHP Essentials 8

2. The History of PHPEvery once in a while a person faces a particular problem or requirement to which there 

appears to be no existing solution.  Faced with this problem the person decides to create a solution to provide the needed functionality. 

Having developed the solution to their problem it then occurs to them that others may need to solve the same problem, and they decide to make their solution freely available to others who, in turn, can use and improve on it.   Within a short period of time many people adopt the technology and work on it,  adding new features   they feel  will  be useful.  The solution soon grows beyond expectations in terms of features and is adopted by more people than the original creator could ever have imagined. 

The Creation of PHP

The first version of what came to be known as PHP was created in 1995 by a man named Rasmus Lerdof.  Rasmus, now an engineer at Yahoo!, needed something to make it easier to create content on his web site, something that would work well with HTML, yet give him power and flexibility beyond what HTML could offer him.   Essentially, what he needed was an easy way to write scripts that would run on his web server both to create content, and handle data being passed back to the server from the web browser.  Using the Perl language, he created some technology that gave   him   what   he   needed   and   decided   to   call   this   technology  "Personal   Home   Page/Forms Interpreter". The technology provided a convenient way to process web forms and create content. 

The  name  "Personal  Home  Page/Forms   Interpreter"  was   later   shortened   to  PHP/FI  and eventually renamed to represent "PHP: Hypertext Preprocessor". The name is said to be recursive because the full name also includes the acronym "PHP" ­ an odd geeky joke that is common in technology circles when people have trouble naming things.   GNU is another recursive name that represents "GNU's Not Unix". 

PHP/FI   version  1.0  was   never   really   used  outside  of   Rasmus'   own  web   site.  With   the introduction of PHP/FI 2.0 this began to change. When PHP 3 was released in 1997, adoption of PHP exploded beyond all belief. 

PHP 3 Hits the Big TimeBy the time 1997 arrived the number of web sites on the internet was growing exponentially 

and most of these web sites were being implemented using the Apache web server.  It was around this time that Andy Gutmans and Zeev Suraski launched the PHP 3 project, a project designed to take PHP to the next level.   One of the key achievements of the PHP 3 project was to implement PHP as a robust Apache Module. 

PHP 3 was implemented using a modular approach that made it easy for others to extend functionality, and also introduced the first elements of object­orientation that would continue to evolve through subsequent releases. 

The combination of PHP 3 and Apache quickly lead to the widespread adoption of PHP, and it is commonly estimated that, at its peak adoption level, PHP3 was used to power over 10% of all web sites on the internet. 

Page 9: PHP Essentials

PHP Essentials 9

PHP 4 ­ Optimization, Scalability and MoreWith PHP 4 Andi Gutmans and Zeev Suraski once again re­architected PHP from the ground up. PHP 4 was built upon a piece of technology called the Zend Engine. The move to the Zend Engine brought about a number of key improvements in PHP: 

• Support   for   other   web   servers   (Microsoft's  Internet   Information   Server   (IIS)   being   of particular significance). 

• Improved memory  handling   to   avoid  memory   leaks   (one  of   the  most  difficult   types  of problems to isolate in a program). 

• Improved   efficiency   and  performance  to   support   large   scale,   complex,   mission   critical enterprise application development using PHP. 

In addition PHP 4 also built on the earlier Object Oriented Programming features of PHP 3 with the introduction of classes. 

PHP 5 ­ Object Orientation, Error Handling and XML The  main,   though   far   from only,   feature  of  PHP 5   is   the   improved   support   for  Object 

Oriented Programming (OOP).     In addition,  PHP 5 introduced some features common in other languages such as Java like try/catch error and exception handling. 

PHP 5 also introduced new extensions aimed at easing the storage and manipulation of data. Significant   new   features   include   SimpleXML   for   handling   XML   documents,   and   SQLite,   an embedded basic and easy to use database interface. 

How Popular is PHP?A   quick   review   of   some   statistics   gives   a   very   clear   indication   of   the   phenomenally 

widespread use of PHP. A company called Netcraft specializes in recording data about the types of web servers  and web server  modules   that  are  used on  the   internet.  As of  April  2007 Netcraft reported that PHP was used on over 20,000,000 distinct web domains. 

A web survey by SecuritySpace also lists PHP as the most widely deployed Apache module. It is safe to say that PHP has taken the internet by storm. 

Page 10: PHP Essentials

PHP Essentials 10

3. An Overview of PHP

What Exactly is PHP?

PHP is  an  intuitive,  server  side scripting  language.  Like any other  scripting  language  it allows developers to build logic into the creation of web page content and handle data returned from a  web browser.    PHP also contains  a  number  of  extensions   that  make  it   easy   to   interact  with databases, extracting data to be displayed on a web page and storing information entered by a web site visitor back into the database. 

PHP consists of a scripting language and an interpreter.  Like other scripting languages, PHP enables web developers to define the behavior and logic they need in a web page.  These scripts are embedded into the HTML documents that are served by the web server.  The interpreter takes the form of a module that integrates into the web server, converting the scripts into commands the computer then executes to achieve the results defined in the script by the web developer. 

How Does PHP Work?To develop an understanding of how PHP works it is helpful to first explore what happens 

when a web page is served to a user's browser. 

When a user visits a web site or clicks on a link on a page the browser sends a request to the web server hosting the site asking for a copy of the web page. The web server receives the request, finds the corresponding web page file on the file system and sends it back, over the internet, to the user's browser.

Typically   the  web server  doesn't  pay any attention   to   the  content  of   the   file   it  has   just transmitted to the web browser.  As far as the web server is concerned the web browser understands the content of the web page file and knows how to interpret and render it so that it appears as the web designer intended. 

Now let's consider what kind of web page content a web browser understands. These days a web page is likely to consist of HTML, XHTML and JavaScript. The web browser contains code that tells it what to do with these types of content. For example, it understands the structure HTML in terms of rendering the page and it has a JavaScript interpreter built in that knows how to execute the instructions in a JavaScript script. A web browser, however, knows absolutely nothing about any PHP script that may be embedded in an HTML document. If a browser was served a web page containing PHP it would not know how to interpret that code. 

Given that a web browser knows nothing about PHP in a web page, then clearly something has to be done with any PHP script in the page before it reaches the browser. This is where the PHP pre­processing module comes in. The PHP module is, as mentioned previously, integrated into the web server. The module tells the web server that when a page is to be served which contains PHP script (identified by special markers) that it is to pass that script to the PHP pre­processing module and wait for the PHP module to send it some content to replace that script fragment. The PHP processing module understands PHP, executes the PHP script written by the web developer and, based on the script instructions, creates output that the browser will understand. The web server substitutes the content provided by the PHP pre­processor module in place of the PHP script in the web page and sends it to the browser where it is rendered for the user to view. 

Page 11: PHP Essentials

PHP Essentials 11

To help understand this concept let's take a quick look at a before and after scenario. The following HTML contains some PHP script that is designed to output an HTML paragraph tag: 

<html><head><title>A PHP Example</title></head><body>

<?php echo '<p>This line of HTML was generated by a PHP script embedded into an HTML document</p>';?>

</body></html>

The   above   example   looks   very   much   like   standard   HTML   until   you   reach   the   part surrounded by <?php and ?>.   These are markers that designate where the embedded PHP script begins and ends.  When the web server finds this it sends it to the PHP module. The PHP module interprets it, converts it to HTML and sends it back to the web server. The web server, in turn, sends the following to the browser: 

<html><head><title>A PHP Example</title></head><body>

<p>This line of HTML was generated by a PHP script embedded into an HTML document</p>

</body></html>

Once loaded into the browser, it is rendered just like any other web page. The fact that the web page originally contained PHP is completely transparent to the web browser. 

The  above  example   is   certainly  an  oversimplification  of   the  power  of  PHP.  Some  may question why one would use PHP to output some static text that could have been achieved more easily using an HTML tag.  The fact is, however, HTML only makes sense if you know beforehand exactly what needs to be displayed in the web page.   Imagine instead, that you are developing an online banking application.  One of the pages you need to display must contain the customer's bank account  number combined with  the current  balance.  Obviously  this   information  is  going  to  be different for each customer. In this  scenario you would develop an HTML page that essentially serves as a template for the page, and then embed PHP into the page to extract the account and balance information from a database. Once processed by the PHP module integrated into the web server, this customer specific content will then appear in the HTML page in place of the PHP script when the page is loaded into the browser. 

Page 12: PHP Essentials

PHP Essentials 12

Why is PHP so Useful?

In terms of web page content we have two extremes. At one extreme we have HTML which is completely static.  There is very little that can be done with HTML to create dynamic content in a web page.  At the other extreme we have scripting languages like JavaScript.  JavaScript provides a powerful mechanism for creating interactive and dynamic web pages. 

When talking about JavaScript it is important to understand that it is, by design, a client side scripting language. By this we mean that the script gets executed inside the user's browser and not on the web server on which the web page originated. Whilst this is fine for many situations it is often the case that by the time a script reaches the browser it is then either too late, or inefficient, to do what is needed. A prime example of this involves displaying a web page which contains some data from a database table. Since the database resides on a server (either the same physical server which runs the web server or on the same network as the web server connected by a high speed fiber network connection) it makes sense for any script that needs to extract data from the database to be executed on the server, rather than waiting until it reaches the browser. It is for this kind of task that PHP is perfectly suited. It is also fast and efficient (because the script is executed on the server it gets to take advantage of multi­processing, large scale memory and other such enterprise level hardware features. 

In addition to the advantages of being a server side scripting language PHP is easy to learn and use. The fact that PHP works seamlessly with HTML makes it accessible to a broad community of web designers. 

Perhaps one of the most significant advantages of PHP to some is the ease with which it interacts with the MySQL database to retrieve and store data.

Page 13: PHP Essentials

PHP Essentials 13

4. Creating a Simple PHP ScriptIn   the  previous   chapter  we   looked   at  how PHP works.  No   technology  book  would  be 

complete without including the obligatory simple example, and PHP Essentials is no exception to this rule. 

In this chapter we will look at constructing the most basic of PHP examples, and in so doing we   will   take   two   approaches   to   creating   PHP   powered  web   content.   Firstly   we   will   look   at embedding PHP into an  HTML page. Secondly, we will look at a reverse example whereby we embed the HTML into the PHP. Both are perfectly valid approaches to using PHP. 

The PHP Code Delimiters

The first thing to understand is the need to use  PHP code delimiters to mark the areas of PHP code  within   the  web  page.    By  default,   the  opening  delimiter   is  <?php  and   the   closing delimiter is ?>.   You can insert as many or as few blocks of PHP into a web page as you need as long as each block is marked by the opening and closing delimiters. 

<?php

echo '<p>This is a PHP script</p>';

?>

Testing the PHP Installation

Before embarking on even the simplest of examples, the first step on the road to learning PHP is to verify that the PHP module is functioning on your web server. To achieve this, we will create a small PHP script and upload it to the web server. To do this start up your favorite editor and enter the following PHP code into it:

<?php

phpInfo();?>

This PHP script calls the built­in PHP phpInfo()  function, the purpose of which to output information about the PHP pre­processing module integrated into your web server. 

Save this file as phpInfo.php and upload it to a location on your web server where it will be accessible via a web browser. Once you have done this open a browser and go to the URL for this file.

If you do not see this information it is possible you do not have the PHP module integrated into your web server. If you use a web hosting company, check with them to see if your particular hosting package includes PHP support (sometimes PHP support is only provided with premium hosting  packages   so  you  may  need   to   upgrade).   If   you   run  your   own web   server   consult   the documentation   for   your   particular   type   of   server   (Apache,   Microsoft   IIS   etc)   for   details   on integrating the PHP module. There are vastly superior resources available on the internet to assist in installing PHP than we could never match in this book. 

Page 14: PHP Essentials

PHP Essentials 14

Embedding PHP into an HTML File As you may have realized, by testing the PHP module on your web server you have already 

crafted your first PHP script. We will now go on to create another script that is embedded into an HTML page. Open your editor and create the following HTML file: 

<html>

<head>

<?phpecho '<title>My First PHP Script</title>';?>

</head><body>

<?php echo '<p>This content was generated by PHP</p>';?>

<p>And this content is static HTML</p></body></html>

Save this file as example.php and upload it to your web server. When you load this page into your browser you should see something like the following: 

Page 15: PHP Essentials

PHP Essentials 15

Embedding HTML into a PHP Script

In the previous example we embedded some PHP Script into an HTML web page. We can reverse this by putting the HTML tags into the PHP commands. The following example contains a PHP script which is designed to output the HTML necessary to display a simple page. As with the previous examples, create this file, upload it to your web server and load it into a web browser: 

<?php

echo "<html>\n";echo "<head>\n";echo "<title>My Second PHP Example</title>\n";echo "</head>\n";echo "<body>\n";echo "<p>Some Content</p>\n";echo "</body>\n";echo "</html>\n";?>

When you load this into your browser it will be as if all that was in the file was HTML, and if you use the view page source feature of your browser the HTML is, infact, all you will see. This is because the PHP pre­processor simply created the HTML it was told to create when it executed the script:

<html>

<head><title>My Second PHP Example</title></head><body><p>Some Content</p></body></html>

Page 16: PHP Essentials

PHP Essentials 16

5. Commenting PHP CodeWhen programming in any language the process of adding comments involves writing notes 

alongside the code to describe what the code does and how it works. The comments are ignored by the PHP pre­processor when executing a script and are purely for human consumption. 

Commenting of code is often neglected by software developers.  Sometimes this is because the code is being developed to meet a looming deadline and there is no time to adequately comment it. Often there is a tendency on the part of the developers to believe that they will remember how the code works six months or a year from now. Another common excuse for not commenting is that the code is so well written as to be completely self­explanatory. 

Excuses aside, there is much to be gained from included helpful and concise comments with the PHP code that powers your web site. Firstly, you will be amazed at how puzzling a section of code can be even a few months after you have written it. It is not unusual for a developer to revisit some old code they once wrote and express amazement that they actually wrote it. It is important to remember that there is a good chance you will have to continue to maintain your PHP scripts long after they are written. 

Another important reason for commenting your code is to ensure that others who may follow in your footsteps to maintain or add functionality to your creation will also benefit from reading your comments. There are few things worse in the software development business than having to traverse the steep learning curve caused by the complexity of somebody else's uncommented code. 

Now that we have established that commenting code is worthwhile, we can take a look at the mechanisms provided by PHP to achieve this goal. PHP provides two commenting mechanisms ­ one for single line comments, and another for multi­line comments. PHP borrows its commenting conventions from other languages such as C, C++ and Java, so if you are familiar with these languages there will be no surprises here. 

PHP Single Line Comments

Comments that reside on a single line are prefixed with the two forward slash characters in PHP (i.e. //). 

The following example contains a single line comment:

<?php // This is a single line comment?>

The single line comment can be on a line of its own, or it can be appended to the end of a line of code: 

<?php echo "This is a test line"; // Output a line of text?>

In the above example the PHP pre­processor will execute the echo statement and then ignore everything after the // single line comment marker. 

Single line comment markers are also useful for temporarily removing lines of code from the 

Page 17: PHP Essentials

PHP Essentials 17

execution flow (particularly useful during debugging sessions).  For example, the following change to our previous example will cause the PHP pre­processor to ignore the entire echo command during execution: 

<?php // echo "This is a test line";?>

PHP Multi­line CommentsMulti­line comments  are wrapped in  /* and */  delimiters.  The /*  marks the start  of   the 

comment block and the */ marks the end. The following example demonstrates the use of multi­line commenting in PHP: 

<?php

/* This a multi-line block of comments*/

?>

Multi­line comments are useful when you have notes you want to make in the code that will take up more than one line. The ability to mark blocks of lines as comments avoids the necessity of placing the single line comment marker at the start of each comment line. 

Another useful application of multi­line comments is to comment out blocks of  PHP code temporarily. It is quite common to have written some PHP script and then wonder if you can re­write it so that it is perhaps more efficient or reliable. In this situation you can comment out the old script fragment so that it is no longer executed and write some new code. If it turns out your new code is worse than the original (which happens from time to time) you can simply remove the new code and uncomment the old to bring it back into the execution flow. 

Page 18: PHP Essentials

PHP Essentials 18

6.  An Introduction to PHP VariablesWhen working with data values in PHP, we need some convenient way to store these values 

so that we can easily access them and make reference to them whenever necessary. This is where PHP variables come in. 

Naming and Creating a Variable in PHPBefore learning how to declare a variable in PHP it is first important to understand some 

rules about variable names (also known as variable naming conventions).  All PHP variable names must be pre­fixed with a $.  It is this prefix which informs the PHP pre­processor that it is dealing with a variable. The first character of the name must be either a letter or an underscore (_). The remaining characters must comprise only of letters, numbers or underscores. All other characters are deemed to be invalid for use in a variable name. 

Let's look at some valid and invalid PHP variable names:

$_myName  // valid$myName // valid$__myvar // valid$myVar21 // valid$_1Big // invalid - underscore must be followed by a letter$1Big // invalid - must begin with a letter or underscore$_er-t // invalid contains non alphanumeric character (-)

Variable names in PHP are case­sensitive. This means that PHP considers $_myVariable to be a completely different variable to one that is named ''$_myvariable”. 

Assigning a Value to a PHP VariableValues   are   assigned   to   variables   using   the   PHP  assignment   operator.   The   assignment 

operator is represented by the = sign. To assign a value to a variable therefore, the variable name is placed on the left of the expression, followed by the assignment operator. The value to be assigned is   then  placed   to   the   right  of   the  assignment  operator.  Finally   the   line,   as  with  all  PHP code statements, is terminated with a semi­colon (;). 

Let's begin by assigning the word "Circle" to a variable named myShape: 

$myShape = "Circle";

We have now declared a variable with the name myShape and assigned a string value to it of "Circe". We can similarly declare a variable to contain an integer value: 

$numberOfShapes = 6;

The above assignment creates a variable named numberOfShapes and assigns it a numeric value of 6. Once a variable has been created, the value assigned to that variable can be changed at any time using the same assignment operator approach:

Page 19: PHP Essentials

PHP Essentials 19

<?php

$numberOfShapes = 6; // Set initial values$myShape = "Circle";

$numberOfShapes = 7; // Change the initial values to new values$myShape = "Square";

?>

Accessing PHP Variable ValuesNow that we have learned how to create a variable and assign an initial value to it we now need to look at how to access the value currently assigned to a variable. In practice, accessing a variable is as simple as referencing the name it was given when it was created. 

For example, if we want to display the value which we assigned to our numberOfShapes variable we can simply reference it in our echo command: 

<?phpecho "The number of shapes is $numberOfShapes.";?>

This will cause the following output to appear in the browser: 

The number of shapes is 6. 

Similarly we can display the value of the myShape variable: 

<?phpecho "$myShape is the value of the current shape.";?>

The examples we have used for accessing variable values are straightforward because we have always had a space character after the variable name. The question arises as to what should be done if we need to put other characters immediately after the variable name. For example: 

<?phpecho "The Circle is the $numberOfShapesth shape";?>

What we are looking for in this scenario is output as follows: 

The Circle is the 6th shape. 

Unfortunately PHP will see the th on the end of the $numberOfShapes variable name as being part of the name. It will then try to output the value of a variable called $numberOfShapesth, which does not exist. This results in nothing being displayed for this variable: 

The Circle is the shape. 

Fortunately we can get around this issue by placing braces ({ and }) around the variable name to 

Page 20: PHP Essentials

PHP Essentials 20

distinguish the name from any other trailing characters: 

<?phpecho "The Circle is the ${numberOfShapes}th shape";?>

To give us the desired output: 

The Circle is the 6th shape.

Changing the Type of a PHP VariableAs we mentioned at   the beginning  of   this  chapter,  PHP supports  a  number  of  different 

variable types (specifically integer, float, boolean, array, object, resource and string). We will look at these types in detail in the next chapter (Understanding PHP Variable Types). First we are going to look at changing the type of a variable after it has been created. 

PHP is what is termed a loosely typed language. This contrasts with programming languages such as Java which are strongly typed languages. The rules of a strongly typed language dictate that once a variable has been declared as a particular type, its type cannot later be changed. In Java, for example, you cannot assign a floating point number to a variable that was initially declared as being a string. 

Loosely typed languages such as PHP (and JavaScript), on the other hand, allow the variable type to be changed at any point in the life of the variable simply by assigning a value of a different type to it. For example, we can create a variable, assign it an integer value and later change it to a string type by assigning a string to it:

<?php

$myNumber = 6; // variable is of integer type

$myNumber = "six"; // variable has now changed to string type

?>

The process of dynamically changing the type of a variable is known as automatic type conversion.

Checking Whether a Variable is SetWhen working with variables it is often necessary to ascertain whether a variable actually 

has a value associated with it or not at any particular point in a script. A mechanism is provided with PHP to provide this ability through the isset() function. To test whether a variable has a value set simply call the  isset()  function passing through the name of the variable as an argument (see PHP Functions for details of passing through arguments to functions). The following code example tests to see if a variable has a value or not and displays a message accordingly: 

<?php

$myVariable = "hello";

if (isset($myVariable))

Page 21: PHP Essentials

PHP Essentials 21

{ echo "It is set.";} else{ echo "It is not set.";}?>

Understanding PHP Variable TypesIn this chapter we will look at the PHP integer, string, float and boolean variable types. 

Since the array and object types are slightly more complex entities we will devote subsequent chapters to them later in the book (see PHP Arrays and PHP Object Oriented Programming). 

The PHP Integer Variable Type

Integer variables are able to hold a whole number in the range of ­2147483648 to 2147483647. Negative values can be assigned by placing the minus (­) sign after the assignment operator and before the number. If the value assigned to an integer type variable moves outside the supported range, either via assignment or mathematical calculation, the variable type is automatically converted to a floating point type. 

The following examples assign integers to variables: 

<?php

$myInteger = 10;

$myNegative = -13457231;

?>

Integer values can be specified in Octal by prefixing the value with a zero '0': 

$myoctInteger = 0456;

Similarly, hexadecimal values are pre-fixed with 0x:

$myHexInteger = 0x5EF3;

The PHP Float Variable TypeFloating point variables contain numbers that require the use of decimal places. In addition, 

float variables can store whole numbers up to higher values than the integer variable type (such as 1.067,   0.25,   423454567098,   84664435.9576).  Floating  point   variable   creation   and   initialization examples are as follows: 

Page 22: PHP Essentials

PHP Essentials 22

<?php

$myFloat = 9234.98;

$myOtherFloat = 9547894367.987483701

?>

The PHP Boolean Variable TypePHP boolean type variables hold a value of true or false and are used to test conditions such 

as whether some part of a script was performed correctly. We will look at using boolean values in greater detail when we look at  PHP Flow Control and Looping, with particular regard to the  if statement. It is useful to know that the true and false values are actually represented internally by PHP boolean values 1 and 0 respectively, though it is important to be aware that boolean 1 and 0 are not the same as integer values 1 and 0. 

The PHP String VariableThe string variable type is used to hold strings of characters such as words and sentences. In 

addition   to  providing  mechanisms  for  creating  and changing entire   string  variable  values,  PHP allows you to extract and change parts of a string value. 

A string can be assigned to variable either by surrounding it in single quotes (') or double quotes ("). If your string itself contains either single or double quotes you should use the opposite to wrap the string: 

<?php

$myString = "A string of text";

$myString2 = 'Another string of text';

$myString3 = "This string contains 'single quotes'";

$myString4 = 'This string contains "double quotes"';

?>

You can also escape quotes in your string by preceding them with a backslash (\), especially useful if your string contains both single and double quotes of its own that would otherwise confuse the PHP pre-processor:

<?php

$myString3 = 'This string contains \'single quotes\'';

$myString4 = "This string contains \"double quotes\" and \'single quotes\'";

?>

Page 23: PHP Essentials

PHP Essentials 23

Double   quoted   strings   also   allow   the   insertion   of   special  control   sequences  that   are interpreted to have special meaning for the PHP pre­processor (such as a tab or new line). The following table outlines the various control sequences and their respective descriptions: 

Control Sequence Description

\n New line

\r Carriage Return

\t Tab

\\ Backslash Character

\" Double quotation mark

\$ Dollar sign (prevents text from being treated as a variable name)

\034 Octal ASCII value

\x0C Hexadecimal ASCII Value

As an example, we can declare a string variable which contains a tab and a new line character as follows: 

<?php$myString = "This is a line of Text\nandthis is another line with a tab here \t for us.";?>

Extracting and Writing String FragmentsOnce  we  have  defined   a   string  variable  we   can   extract   or  make   changes   to   individual 

characters in the string using what is termed {x} notation, where  x  represents the index into the string of the character we wish to view or change. Before we look at an example, it is important to keep in mind that the index into the string is zero based. By this we mean that the first character of the string is in position 0, not position 1. For example, to change the first and last characters of a string variable: 

<?php

$myString = "My Bug";

$myString{0} = "m";$myString(5] = "s";

echo $myString;?>

The result of the above script will change the string from: 

My Bug 

to: 

my Bus

Page 24: PHP Essentials

PHP Essentials 24

Creating PHP heredoc Strings The PHP  heredoc  string syntax allows  free form  text to be used without having to worry 

about escaping special characters such as quotes and backslashes. The content of the heredoc string is wrapped with <<<EOD and EOD; markers. 

The only rules are that the closing  EOD;  must be at the  beginning  of the last line, and the  only content on that line, as follows:

<?php

$myString = <<<EODThis is some free form text. It can span mutliplelines and can contain otherwise troublesome characters like\ and " and ' without causing any problems.EOD;

echo $myString;

?>

Page 25: PHP Essentials

PHP Essentials 25

8. PHP ConstantsConstants are particularly useful for defining a value that you frequently need to refer to that 

does not ever change. For example, you might define a constant called INCHES_PER_YARD that contains the number of inches in a yard. Since this is a value that typically doesn't from one day to the next it makes sense to define it as a constant. Conversely, a value that is likely to change, such as the Dollar to Yen exchange rate is best defined as a variable. 

PHP constants are said to have global scope. This basically means that once you have defined a constant it is accessible from any function or object in your script. 

In addition, PHP provides a number of built­in constants that are available for use to make life easier for the PHP developer.

Defining a PHP ConstantRather than using the assignment operator as we do when defining variables, constants are 

created using the define() function. Constants also lack the $ prefix of variable names. 

The define function takes two arguments, the first being the name you wish to assign to the constant, and the second the value to assign to that name. 

Constant names are case sensitive. Although it is not a requirement, convention carried over from other programming languages suggests that constants should be named in all upper case characters. The following example demonstrates the use of the define() function to specify a constant: 

<?phpdefine('INCHES_PER_YARD', 36);?>

Once defined the constant value can be accessed at any time just by referring to the name. For example, if we define a string constant as follows: 

<?phpdefine('WELCOME_MESSAGE', "Welcome to my World");?>

we can subsequently access that value anywhere in our script. For example, to display the value:

echo WELCOME_MESSAGE;

Checking if a PHP Constant is DefinedIt can often be useful to find out if a constant is actually defined. This can be achieved using 

the PHP defined() function. The defined() function takes the name of the constant to be checked as an argument and returns a value of true or false to indicate whether that constant exists. 

For example, let's assume we wish to find out if a constant named MY_CONSTANT is defined. We can simply call the defined() function passing through the name, and then test the result using an if .. else statement (see PHP Flow Control and Looping for more details on using if .. else): 

Page 26: PHP Essentials

PHP Essentials 26

<?phpdefine ('MY_CONSTANT', 36);

if (defined('MY_CONSTANT')){ echo "Constant is defined";}else{ echo "Constant is not defined";}?>

Using a Variable as a Constant Name It is not always the case that you want to hard­code a constant name into a script at the point 

you wish to access it. For example, you may have a general purpose script that you wish to perform tasks on any number of different constants, not just one that you happen to have typed in the name for. The best way to resolve this issue is store the name of the constant in a variable. How then, would you access the value assigned to that constant? The answer is to use the PHP  constant() function. The  constant()  function takes the name of the constant as an argument and returns the value of the constant which matches that name. 

The key point to understand here as that the argument passed through to constant() can be a string variable set to the name of the constant. 

As always an example helps a great deal in understanding a concept. In the script below we define a constant called MY_CONSTANT. Next, we create a string variable called constantName and assign it a value of MY_CONSTANT (i.e. a string that matches the constant name). We can then use this new variable as the argument to constant() to obtain the constant value of MY_CONSTANT: 

<?phpdefine ('MY_CONSTANT', "This is a constant string.");$constantName = 'MY_CONSTANT';

if (defined ( $constantName )){ echo constant($constantName);}else{ echo "$constantName constant is not defined.";}?>

The above script will display the constant value if it exists by using the value of the $constantName variable constant name key.

Page 27: PHP Essentials

PHP Essentials 27

Predefined PHP Constants As we mentioned briefly at  the start  of  this  chapter, PHP provides a number of built­in 

constants that can be of significant use to the PHP web developer. In this section we will look at some of the more useful constants available. 

PHP Script and Environment Related ConstantsThe following constants provide information about the script which is currently executing, 

and also the environment in which the PHP web server module is running. These are of particular use when debugging scripts: 

Constant Name Description

__LINE__ Contains the number of the line in the current PHP file (or include file) which is being currently being executed by the PHP pre­processor.

__FILE__ Contains the name of the file or include which contains the currently executing line of PHP code.

__FUNCTION__ Contains the name of the PHP function which is currently executing

__CLASS__ Contains the class which is currently in use

__METHOD__ Contains the name of the method in the current class which is currently executing

PHP_VERSION Contains the version of PHP that is executing the script

PHP_OS Contains of the name of the Operating System hosting the PHP Pre­processor

PHP_EOL Contains the Newline character for the host OS (differs between UNIX/Linux and Windows for example)

DEFAULT_INCLUDE_PATH The default path where PHP looks for include files

PHP Mathematical Constants PHP provides a number of useful mathematical constants that can be used to save both

programming time when writing a script, and processing time when performing calculations in a script. The following table provides a list of the mathematical constants available in PHP:

Constant DescriptionM_E Value of e 

M_EULER Value of Euler's constant 

M_LNPI The natural logarithm of PI 

M_LN2 The natural logarithm of 2 

M_LN10 The natural logarithm of 10 

M_LOG2E Value of base­2 logarithm of E

M_LOG10E The base­10 logarithm of E 

Page 28: PHP Essentials

PHP Essentials 28

M_PI The value of PI

M_PI_2 The value of PI/2

M_PI_4 The value of PI/4

M_1_PI The value of 1/PI

M_2_PI The value of 2/PI

M_SQRTPI The square root of PI

M_2_SQRTPI The value 2/square root of PI

M_SQRT2 The square root of 2

M_SQRT3 The square root of 3

M_SQRT1_2 The square root of 1/2

9. PHP OperatorsOperators   in  PHP,   and  any  other    programming   language  for   that  matter,   enable  us   to 

perform tasks on variables and values such as assign, multiply, add, subtract and concatenate them. Operators take the form of symbols (such as + and ­) and combinations of symbols (such as ++ and +=). 

Operators in PHP work with operands which specify the variables and values that are to be used  in   the particular  operation.  The number  and  location  of   these operands   in   relation   to   the operators (i.e. before and/or after the operator) depends on the type of operator in question. Let's take, for example, the following simple expression: 

1 + 3;

In this expression we have one operator (the '+') and two operands (the numbers 1 and 3). The '+' operator adds the values of two operands (resulting in a value of 4). 

Operators can be combined to create complete expressions: 

$myVar = 1 + 3;

In the above example, the assignment operator (=) assigns the result of the addition to the operand represented by the variable $myVar. After evaluating this expression the value of 4 will have been assigned to the variable $myVar. 

In this chapter of PHP Essentials we will explore each type of operator and explain how they are used in relation to their operands. 

Page 29: PHP Essentials

PHP Essentials 29

PHP Assignment OperatorsWe briefly   covered   the  basic  PHP assignment  operator   in   the  An  Introduction   to  PHP 

Variables chapter. We will now look at this and other assignment operators in more detail. 

The  assignment operator  is used to assign a value to a variable and is represented by the equals   (=)   sign.   The   assignment   operator   can   also   be   combined   with   arithmetic   operators   to combine   an   assignment  with   a  mathematical   operation   (for   example   to  multiply  one  value  by another and assigning the result to the variable) and also to perform string concatenations. 

The following table lists the seven assignment operators available in PHP, together with descriptions and examples of their use: 

Operator Type Description Example

= Assignment Sets the value of the left hand operand to the value of the right $myVar = 30;

+= Addition­AssignmentAdds the value of left hand operand to the value of the right hand operand and assigns result to left hand operand

$myVar = 10;$myVar += 5;

­= Subtraction­Assignment

Subtracts the value of right hand operand from the value of the left hand operand and assigns result to left hand operand

$myVar = 10;$myVar ­= 5;

*= Multiplication­AssignmentMultiplies the left hand operand by value of the right hand operand assigning result to left hand operand

$myVar = 10;$myVar *= 5;

/= Division­AssignmentDivides the left hand operand by value of the right hand operand assigning result to left hand operand

$myVar = 10;$myVar /= 5;

%= Modulo­AssignmentSets the value of the left hand operand to the remainder of the value after being divided by the right hand operand

$myVar = 10;$myVar %= 5;

.= Concatenation­Operand

Sets the value of the left hand operand to a string containing a concatenation of its value appended with the string in the right hand operand

$sampleString="My color is ";$sampleString .= "blue"; 

PHP Arithmetic OperatorsAs the name suggests PHP arithmetic operators provide a mechanism for performing mathematical operations: 

Page 30: PHP Essentials

PHP Essentials 30

Operator Type Description Example

= AssignmentSets the value of the left hand operand to the value of the right

$myVar = 30;

+= Addition-AssignmentAdds the value of left hand operand to the value of the right hand operand and assigns result to left hand operand

$myVar = 10;$myVar += 5;

-= Subtraction-Assignment

Subtracts the value of right hand operand from the value of the left hand operand and assigns result to left hand operand

$myVar = 10;$myVar -= 5;

*= Multiplication-AssignmentMultiplies the left hand operand by value of the right hand operand assigning result to left hand operand

$myVar = 10;$myVar *= 5;

/= Division-AssignmentDivides the left hand operand by value of the right hand operand assigning result to left hand operand

$myVar = 10;$myVar /= 5;

%= Modulo-AssignmentSets the value of the left hand operand to the remainder of the value after being divided by the right hand operand

$myVar = 10;$myVar %= 5;

.= Concatenation-Operand

Sets the value of the left hand operand to a string containing a concatenation of its value appended with the string in the right hand operand

$sampleString="My color is ";$sampleString .= "blue";

PHP Mathematical OperatorsAs the name suggests PHP arithmetic operators provide a mechanism for performing mathematical operations: 

Operator Type Description Example

+ Addition Calculates the sum of two operands $total = 10 + 20; 

­ Subtraction Calculates the difference between two operands $total = 10 ­ 20; 

* Multiplication Multiplies two operands $total = 10 * 20; 

/ Division Divides two operands $total = 10 / 20; 

% Modulus Returns the remainder from dividing the first operand by the second $total = 20%10; 

$var = 1 + 2; // Sets variable $var to the sum of 1 + 2

$var = 3 % 7; // Sets variable $var to the modulus of 3 and 7

$var = 10;

Page 31: PHP Essentials

PHP Essentials 31

$var2 = $var / 2; // Sets variable $var2 to the value of 10 divided by 2

PHP Comparison OperatorsThe comparison  operators  provide   the ability   to  compare one value against  another  and 

return either a true or false result depending on the status of the match. For example, you might use a comparison operator to check if a variable value matches a particular number, or whether one string is identical to another. PHP provides a wide selection of comparison operators for just about every comparison need. 

The comparison operators are used with two operands, one to the left and one to the right of the operator. The following table outlines the PHP comparison operators and provides brief descriptions and examples: 

Operator Type Description Examples

== Equal to Returns true if first operand equals second

$myVar = 10; if ($myVar == 10)echo 'myVar equals 10';

!= Not equal toReturns true if first operand is not equal to second

$myVar = 10; if ($myVar != 20)echo 'myVar does not equal 10';

<> Not equal to Returns true if first operand is not equal to second

$myVar = 10; if ($myVar <> 20)echo 'myVar does not equal 10';

=== Identical to Returns true if first operand equals second in both value and type

$myVar = 10;$myString="10"; if ($myVar === $myString)echo 'myVar and myString are same type and value';

!==Not identical to

Returns true if first operand is not identical to second in both value and type

$myVar = 10;$myString="10"; if ($myVar !== $myString)echo 'myVar and myString are not same type and value';

< Less thanReturns true if the value of the first operand is less than the second

$myVar = 10; if ($myVar < 20)echo 'myVar if less than 20';

> Greater than Returns true if the value of the first operand is greater than the second

$myVar = 10; if ($myVar > 5)echo 'myVar if greater than 5';

<= Less than or equal to

Returns true if the value of the first operand is less than, or equal to, the second

$myVar = 10; if ($myVar <= 5)echo 'myVar is less than or equal to 5';

Page 32: PHP Essentials

PHP Essentials 32

>= Greater than or equal to

Returns true if the value of the first operand is greater than, or equal to, the second

$myVar = 10; if ($myVar >= 5)echo 'myVar is greater than or equal to 5';

PHP Logical OperatorsLogical Operators are also known as Boolean Operators because they evaluate parts of an 

expression and return a true or false value, allowing decisions to be made about how a script should proceed. The logical operators supported by PHP are listed in the following table: 

Operator Type Description Examples

&& AND Performs a logical "AND" operation. if (($var1 < 25) && ($var2 > 45))

|| OR Performs a logical "OR" operation. if (($var1 < 25) || ($var2 > 45))

xor XOR Performs a logical "XOR" (exclusive OR) operation.

if (($var1 < 25) xor ($var1 > 45))

The first step to understanding how logical operators work is to construct a sentence rather than to look at a script example right away. Let's assume we need to check some aspect of two variables named $var1 and $var2. Our sentence might read: 

If $var1 is less than 25 AND $var2 is greater than 45 display a message. 

Here the logical operator is the "AND" part of the sentence. If we were to express this in PHP we would  use   the  comparison  operators  we covered earlier   together  with   the  && logical operator: 

if (($var1 < 25) && ($var2 > 45))echo 'Our expression is true';

Similarly, if our sentence was to read: 

If $var1 is less than 25 OR $var2 is greater than 45 display a message. 

Then we would replace the "OR" with the PHP equivalent ||: 

if (($var1 < 25) || ($var2 > 45))echo 'Our expression is true';

Another useful logical operator is the Exclusive Or (XOR) operator. The XOR operator returns true if only one of the expressions evaluates to be true. For example: 

If $var is EITHER less than 25 OR greater than 45 display a message 

We represent XOR with the keyword xor: 

if (($var1 < 25) xor ($var1 > 45))echo 'Our expression is true';

The final Logical Operator is the NOT operator which simply inverts the result of an expression. The ! character represents the NOT operator and can be used as follows: 

Page 33: PHP Essentials

PHP Essentials 33

(10 > 1) // returns ''true''

!(10 > 1) // returns ''false'' because we have inverted the result with the logical NOT

PHP Increment and Decrement Operators When programming in any language it is not uncommon to need to increment or decrement the value stored in a variable by 1. This could be done long hand: 

$myVar = $myVar-1;

A much quicker way, however, is to use the PHP increment and decrement operators. These consist of the operators  ++  (to increment) and  ­­  (to decrement) combined with an operand (the name of the variable to which the change is to be applied). 

There are  two ways of  using these operators,  pre  and  post.  The  pre  mode performs the increment or decrement before performing the rest of the expression. For example, you might want to increment the value of a variable before it is assigned to another variable, or used in a calculation. In the post mode the increment or decrement is performed after the expression has been performed. In this instance, you might want the value to be decremented after it has been assigned or used in a calculation. 

Whether a pre or post is used depends on whether the operator appears before (for pre), or after (for post) the variable name in the expression.  For example ­­$myVariable or $myVariable++. 

The following table outlines the various forms of pre and post increment and decrement operators, together with examples that show how the equivalent task would need to be performed without the increment and decrement operators. 

Operator Type Description Equivalent

++$var PreincrementIncrements the variable value before it is used in rest of expression

$var = 10;$var2 = $var + 1;

­­$var Predecrement Decrements the variable value before it is used in rest of expression

$var = 10;$var2 = $var ­ 1;

$var++ Postincrement Increments the variable value after it is used in rest of expression

$var = 10;$var2 = $var;$var = $var + 1;

$var­­ PostdecrementDecrements the variable value after it is used in rest of expression

$var = 10;$var2 = $var;$var = $var ­ 1;

PHP String Concatenation OperatorThe PHP String concatenation operator is used to combine values to create a string. The 

concatenation operator is represented by a period/full stop (.) and can be used to build a string from other strings, variables containing non­strings (such as numbers) and even constants: 

Page 34: PHP Essentials

PHP Essentials 34

We will start with the operator in its simplest form concatenating two strings: 

echo 'My favorite color is ' . 'blue.';

The above example will display a string that is the result of second string appended to the end of the first string: 

=> My favorite color is blue. 

The string concatenation operator can also be used with variables. In the following example the value of the $myString variable is appended to the end of the string: 

$myString = "red";

echo 'My favorite color is ' . $myString;

We can also reference constants (see PHP Constants for details on using constants in PHP) when using concatenation: 

define (MY_COLOR, "Green");

echo 'My favorite color is ' . MY_COLOR;

The above example will result in the following output: 

My favorite color is Green 

Concatenation of Numbers and Strings in PHP We mentioned at the beginning of this section that it is also possible to mix numbers and strings in a concatenation operation to create strings. For example we can include the number 6 in our string as follows: 

echo 6 . ' is my lucky number';

The above example will create output as follows: 

6 is my lucky number

We can also perform a calculation and have the result included in the concatenation: 

echo 6 + 5 . ' is my lucky number'

In this example the mathematical operation will be evaluated before the concatenation, thereby producing: 

11 is my lucky number 

It is important to note an issue when dealing with strings and numbers. While the above works fine because we began the expression with the addition, something very different happens when we have the addition after the string: 

Page 35: PHP Essentials

PHP Essentials 35

echo 'My Lucky number is ' . 6 + 5;

The above will produce unexpected results (typically it will output just the number 5). The reason for this is because we have asked PHP to take a string (My Lucky number is ), append the number 6 to it (to produce My Lucky number is 6) and then finally arithmetically add the number 5 to the string (which doesn't make a lot of sense). To resolve this issue we need to tell the PHP pre­processor to perform the addition (6 + 5) before performing the concatenation. We can achieve this by surrounding the addition expression in parentheses. Therefore the modified script: 

echo 'My Lucky number is ' . (6 + 5);

This will now produce the desired output: 

My Lucky number is 11 

Through  the  use  of  parentheses  around  the  addition  expression  we have changed  the  operator precedence for that expression. 

PHP Execution Operator ­ Executing Server Side Commands All   of   the   operators   we   have   looked   at   so   far   are   similar   to   those   available   in   other 

programming   and   scripting   languages.   With   the   execution   operator,   however,   we   begin   to experience the power of PHP as server side scripting environment. The execution operator allows us to execute a command on the operating system that hosts your web server and PHP module and then capture the output. 

You can do anything in an execution operator that you could do as if you were sitting at a terminal window on the computer (within the confines of the user account under which PHP is running). Given this fact, it should not escape your attention that there are potential security risks to this, so this PHP feature should be used with care. 

The execution operator consists of enclosing the command to be executed in back quotes (`). The following example runs the UNIX/Linux uname and id commands to display information about the operating system and user account on which the web server and PHP module are running (note that these command will not work if you are running a Windows based server): 

<?phpecho `uname -a` . '<br>';echo `id`;?>

This results in the following output in the browser window: 

Linux techotopia 2.6.9­42.0.10.ELsmp #1 SMP Tue Feb 27 10:11:19 EST 2007 i686 i686 i386 GNU/Linux 

uid=48(apache) gid=48(apache) groups=48(apache) 

On a Windows system you could run the dir command to get a listing of files in the current web server directory: 

<?php

Page 36: PHP Essentials

PHP Essentials 36

echo `dir`;?>

10. PHP Flow Control and LoopingOne of the main reasons for using scripting languages such as PHP is to build logic and 

intelligence into the creation and deployment of web based data. In order to be able to build logic into PHP based scripts, it is necessary for the script to be able to make decisions and repeat tasks based on specified criteria. 

For example, it may be necessary to repeat a section of a script a specified number of times, or perform a task only if one or more conditions are found to be true (i.e. only let the user log in if a valid password has been provided). 

In programming terms this is known as flow control and looping. In the simplest terms this involves some standard scripting structures provided by languages such as PHP to control the logic and overall behavior of a script. Each of these structures provides a simple and intuitive way to build intelligence into scripts. These PHP structures can be broken down into a number of categories as follows: 

Conditional Statements 

• if statements • if ... else ... statements 

Looping Statements 

• while loops • do ... while loops 

switch Statements 

In this chapter we will explore each of these categories in turn and create some examples that demonstrate how to implement these mechanisms. 

PHP Conditional StatementsJust about everything in life revolves around decisions. We wouldn't get very far through the 

day if we weren't able to decide what to wear, what to eat and which roads to traverse on the way to work. Similarly computers would be of little use without some innate ability to evaluate choices and make decisions. If all we were able to do was provide a computer with a set of instructions that simply followed one after the other with no ability to make choices based on specific criteria, none of the software we have today would exist. 

Conditional statements provide the core of building decision making into scripting languages such  as  PHP.  Conditional   statements   essentially  control  whether  a  part  of   a   script   is  executed depending the result of a particular expression (i.e. whether an expression returns a boolean true or false value). The two types of conditional structures provided by PHP (and most other programming languages) are if and if ... else. 

Page 37: PHP Essentials

PHP Essentials 37

The PHP if StatementThe basic building block of conditional coding is the  if  statement. The first line of an  if 

statement consists of the if statement followed by the expression to be evaluated in parentheses. For example: 

$myVar = 10;if ($myVar < 2)

In the above example if the value of the $myVar variable is evaluated to be less than 2 the expression will be evaluated as being true, otherwise it will be evaluated to be false 

The second step in constructing an if statement involves specifying the action to be taken when the expression is evaluated to be true. This is achieved by placing the lines of script to be executed in open and closing braces after the if statement: 

if ($myVar < 2){ echo 'The value of myVar is less than 2'; $myVar++;}

Note that if there is only one line of script to be performed if the if expression is true then the braces are optional: 

if ($myVar < 2) echo 'The value of myVar is less than 2';

Whilst this is perfectly valid PHP it is strongly recommended, for the purposes of consistent scripting style, that the braces be used even for a single line of script after the 'if' statement. This makes the script easier to read and avoids a common mistake of later adding new commands that are conditional on the if statement and forgetting to add the braces. 

The PHP if ... else Statements The if statement above allows you to specify what should happen if a particular expression 

evaluates to  true. It does not, however, provide the option to specify something else that should happen in the event that the expression evaluates to be false. This is where the if ... else construct comes into play. 

The syntax for if ... else is the same as for the if statement with the exception that the else statement can be used to specify alternate action: 

<?php$customerName = "Graham";

if ($customerName == "Simon"){

Page 38: PHP Essentials

PHP Essentials 38

echo 'Hello Simon!';} else { echo 'You are not Simon! Where is Simon?';}?>

As shown in the above example the script following the  if  statement is executed when the expression is evaluated to be true (i.e. the $customerName variable contains the string "Simon") and the script after the else  statement is executed when the $customerName value does not match the string "Simon". 

if ... else structures can be taken a step further to implement if ... else ... if structures. For example: 

<?php$customerName = "Graham";

if ($customerName == "Simon"){ echo 'Hello Simon';}else if ($customerName == "Graham"){ echo 'Hello Graham';}else { echo 'You are not Simon or Graham.';}?>

PHP Looping StatementsIt is generally accepted that computers are great at performing repetitive tasks an infinite 

number of times, and doing so very quickly. It is also common knowledge that computers really don't do anything unless someone programs them to tell them what to do. 

Loop statements are the primary mechanism for telling a computer to perform the same task over and over again until a set of criteria are met. This is where for, while and do ... while loops are of use. 

PHP for loopsSuppose you wanted to add a number to itself ten times. One way to do this might be to write the following PHP script: 

<?php$myVar = 10;

$myVar += $myVar;$myVar += $myVar;$myVar += $myVar;$myVar += $myVar;

Page 39: PHP Essentials

PHP Essentials 39

$myVar += $myVar;$myVar += $myVar;$myVar += $myVar;$myVar += $myVar;$myVar += $myVar;$myVar += $myVar;

?>

Whilst this is somewhat ungainly and time consuming to type, it does work. What would happen, however, if there was a requirement to perform this task 100 times or even 10,000 times. Writing a script to perform this as above would be prohibitively time consuming. This is exactly the situation the for loop is intended to handle. 

The syntax of a PHP for loop is as follows: 

for ( initializer; conditional expression; loop expression ){ // PHP statements to be executed go here}

The initializer typically initializes a counter variable. Traditionally the variable $i is used for this purpose. For example: 

$i = 0 

This sets the counter to be the value $i and sets it to zero. 

The conditional expression specifies the test to perform to verify whether the loop has been performed the required number of times. For example, if we want to loop 1000 times: 

$i < 1000 

Finally, the loop expression specifies the action to perform on the counter variable. For example to increment by 1: 

$i++ 

Bringing this all together we can create a for loop to perform the task outlined in the earlier in this section: 

<?php$j = 10;

for ($i=0; $i<10; $i++){ $j += $j;}?>

As with the if statement, the enclosing braces are optional if a single line of script is to be executed, but their use is strongly recommended. 

Page 40: PHP Essentials

PHP Essentials 40

PHP while loopsThe PHP for  loop described previously works well when you know in advance how many 

times a particular task needs to be repeated in a script. Clearly, there will frequently be instances where code needs to be repeated until a certain condition is met, with no way of knowing in advance how many repetitions are going to be needed to meet that criteria. To address this PHP, provides the while loop. 

Essentially, the while loop repeats a set of tasks until a specified condition is met. The while loop syntax is defined follows: 

<?phpwhile (condition){ // PHP statements go here}?>

In the above syntax, condition is an expression that will return either true or false and the //  PHP statements go here comment represents the PHP to be executed while the expression is true. For example: 

<?php$myCount = 0;$j = 10;

while ( $myCount < 100 ){ $myCount = $myCount + $j;}?>

In the above example the while expression will evaluate whether $myCount is less than 100. If   it   is  already  greater   than  100  the  code   in   the  braces   is   skipped  and   the   loop  exits  without performing any tasks. If $myCount is not greater than 100 the code in the braces is executed and the loop returns to the while statement and repeats the evaluation of $myCount. This process repeats until $myCount is greater than 100, at which point the loop exits. 

PHP do ... while loopsYou can think of the do ... while loop as an inverted while loop. The while loop evaluates an 

expression before executing the code contained in the body of the loop. If the expression evaluates to false on the first check then the code is not executed. The do .. while loop, on the other hand, is provided for situations where you know that the code contained in the body of the loop will always need to be executed at least once. For example, you may want to keep stepping through the items in an array until a specific item is found. You know that you have to at least check the first item in the array to have any hope of finding the entry you need. The syntax for the  do ... while  loop is as follows: 

<?phpdo{

Page 41: PHP Essentials

PHP Essentials 41

PHP statements} while (conditional expression)?>

In the do ... while example below the loop will continue until $i equals 0: 

$i = 10;do{ $i--;} while ($i > 0)

PHP switch StatementsThe if ... else conditional construct described earlier in this chapter works well if you need to 

check a value against a few different criteria (for example checking the value of a string against a couple of possible candidates): 

<?php

$customerName = "Edward";

if ($customerName == "Carl"){ echo 'Hello Carl!';} else if ($customerName == "Fred"){ echo 'Hello Fred!';} else{ echo 'Who are you?';}?>

This  can  quickly become cumbersome,  however,  when a need  arises   to  evaluate  a   large number  of   conditions.  A much easier  way  to  handle   such  situations   is   to  use   the  PHP  switch statement, the syntax for which is defined as follows: 

switch (''value''){ case "match1": PHP statements break;

case "match2": PHP statements break;

case "match3":

Page 42: PHP Essentials

PHP Essentials 42

PHP statements break;

case "match4": PHP statements break;

case "match5": PHP statements break;

default: PHP statements break;}

There  can  be  any number  of  case  statements   ­  basically  as  many as  you need   to   fully compare   the  value  in   the  switch  statement  against   the possible  options   (represented by  match1 through to match5 in the above example) specified by the case statements. When a match is found the PHP statements corresponding to the matching case are executed. Note the break; statement in each case ­ this is important. Without the break; all the cases after the matching case will also be executed when a match is found. 

The default statement specifies the action that should be taken if no match is found. The following provides an example of the switch statement in action: 

<?php$carModel = "Edge";

switch ($carModel){ case "Caravan" : print "Manufactured by Dodge"; break;

case "Supra" : print "Manufactured by Toyota"; break;

case "Edge" : print "Manufactured by Ford"; break;

case "540i" : print "Manufactured by BMW"; break;

case "Prelude" : print "Manufactured by Honda"; break;

default : print "Unknown Model of Car"; break;}?>

Page 43: PHP Essentials

PHP Essentials 43

Breaking a Loop Occasionally   it   is  necessary   to  exit   from a   loop before  it  has  met  whatever  completion 

criteria were specified. To achieve this, the break  statement must be used. The following example contains a loop that uses the break statement to exit from the loop when i = 100, even though the loop is designed to iterate 1000 times: 

for ($i = 0; $i < 1000; $i++){ if ($i == 10) { break; }}

Breaking Out of Nested Loops One problem that can arise using the break statement involves breaking from a loop that is 

nested inside another loop. In the following example the break will break out of the inner loop, but not the outer loop: 

for ($i = 0; $i < 1000; $i++){ for ($x = 0; $x < 100; $x++) { if ($x == 10) { break; } })

In the above example the break will break out of the inner loop when $x is equal to 10 but the outer for loop will continue to run. This is fine if that is the desired behavior, but is a problem if the outer loop needs to also be broken at this point. This problem can be resolved using the break statement followed by the number of loops you from which you wish to break out. The syntax for this type of break is: 

break n; 

where  n  represents the number of loop levels from which to break. With this knowledge we can modify our previous example to break out of both loops using a break 2; statement: 

<?phpfor ($i = 0; $i < 1000; $i++){ for ($x = 0; $x < 100; $x++) { if ($x == 10)

Page 44: PHP Essentials

PHP Essentials 44

{ break 2; } })?>

11.  PHP FunctionsIn the world of programming and scripting there are two ways to write code. One way is to 

write long, sprawling and monolithic sections of script. Another is to break the scripts up into tidy, self contained modules that can be re­used without having to re­invent the same code over and over again. Obviously the latter is highly preferable to the former, and the fundamental building block of this approach to writing PHP scripts is the function. 

What is a PHP Function?Functions  are  basically  named  scripts   that  can  be  called  upon  from any other   script   to 

perform a specific task. Values (known as arguments) can be passed into a function so that they can be used in the function script, and functions can, in turn, return results to the location from which they were called.

How to Write a PHP FunctionThe first step in creating a PHP function is to provide a name by which you will reference 

the function. Naming conventions for PHP functions are the same as those for variables in that they must  begin  with  a   letter  or  an  underscore  and must  be  devoid  of  any  kind  of  white   space  or punctuation. You must also take care to ensure that your function name does not conflict with any of the PHP built in functions. 

PHP functions are created using the function keyword followed by the name and, finally, a set of parentheses. The body of the function (the script that performs the work of the function) is then enclosed in opening and closing braces. 

The following example function simply outputs a string when it is called: 

<?phpfunction sayHello(){ print "Hello";}?>

Returning a Value from a PHP FunctionA single value may be returned from a PHP function to the script from which it was called. The

Page 45: PHP Essentials

PHP Essentials 45

returned value can be any variable type of your choice.

The return keyword is used to return the value:

<?phpfunction returnTen (){ return 10;}?>

The above example returns the value of 10 to the calling script. 

Passing Parameters to a PHP Function Parameters (or arguments as they are more frequently known) can be passed into a function. 

There are no significant restrictions of the number of arguments which can be passed through to the function. 

A function can be designed to accept parameters by placing the parameter names inside the parentheses of the function definition. There are no specific rules on the names that can be given to these arguments other than those applying to variable names in general. In the following examples we will use $arg1 and $arg2 as argument variable names. These variables can then be accessed using the assigned names from within the function body as follows: 

<?phpfunction addNumbers ($arg1, $arg2){ return $arg1 + $arg2;}?>

In   the   above   example   the  addNumbers()  function   accepts   two  parameters   as   arguments assigned to variables arg1 and arg2 respectively, adds them together and returns the result. 

Calling PHP Functions PHP   functions   are   called   by  using   the   name   declared  when   the   function   was  defined, 

together with any values that need to be passed through as parameters. The following example both defines and then calls our addNumbers() function: 

<?phpfunction addNumbers ($arg1, $arg2){ return $arg1 + $arg2;}

$var1 = 10;$var2 = 20;print addNumbers( $var1, $var2); ?>

When loaded into a browser the print statement will display the result returned by the addNumbers() function, in this case the number 30. 

Page 46: PHP Essentials

PHP Essentials 46

Passing Parameters by ReferenceIn   the  above example  we only passed  the  values  contained  in  $var1 and $var2  into  the 

addNumbers()   function.  Had we made any changes  to   these values   in  the function  the original variables would have remained unchanged. Suppose we change our script so that the function adds 10 to each of the parameters passed in. If we then check the values of the $var1 and $var2 variables after the call to the function we will see they have not been changed: 

<?phpfunction addNumbers ($arg1, $arg2){ $arg1 += 10; $arg2 += 10; return $arg1 + $arg2;}

$var1 = 10;$var2 = 20;

echo "Before var1 = $var1, var2 = $var2 <br>";addNumbers ($var1, $var2);echo "After var1 = $var1, var2 = $var2 <br>";

?>

The output from the above script will read:

Before var1 = 10, var2 = 20After var1 = 10, var2 = 20

If we wanted the script to work on the actual variables themselves, and change the values of those variables then we do something called passing by reference. This has the effect of passing a reference to the actual variable rather than simply passing the value assigned to the variable. We specify that we are passing by reference by prefixing the variable names in our function definition with an '&' character. If we modify our previous script so that variables are passed by reference: 

<?phpfunction addNumbers (&$arg1, &$arg2){ $arg1 += 10; $arg2 += 10; return $arg1 + $arg2;}

$var1 = 10;$var2 = 20;

echo "Before var1 = $var1, var2 = $var2 <br>";addNumbers ($var1, $var2);echo "After var1 = $var1, var2 = $var2 <br>";?>

In the above example we are now passing by reference, so any changes to the variables passed to the function are changes to the values contained in those variables. In this case the output will read: 

Page 47: PHP Essentials

PHP Essentials 47

Before var1 = 10, var2 = 20After var1 = 20, var2 = 30

Note   that   in   the above examples  we have used variable  names $arg1 and $arg2 for   the function arguments and  $var1  and  $var2  for the script fragment that calls the function. It is also valid to use the same names for both the variables and the arguments. For example, the following is valid syntax: 

<?phpfunction addNumbers ($var1, $var2){ $var1 += 10; $var2 += 10; return $var1 + $var2;}

$var1 = 10;$var2 = 20;

echo "Before var1 = $var1, var2 = $var2 <br>";addNumbers ($var1, $var2);echo "After var1 = $var1, var2 = $var2 <br>";

?>

Similarly, the same variable names can be used when passing by reference: 

<?phpfunction addNumbers (&$var1, &$var2){ $var1 += 10; $var2 += 10; return $var1 + $var2;}

$var1 = 10;$var2 = 20;

echo "Before var1 = $var1, var2 = $var2 <br>";addNumbers ($var1, $var2);echo "After var1 = $var1, var2 = $var2 <br>";?>

Although  the  variables  and arguments   in   the  first  example  (where   the  variables  are  not passed  by   reference)   share   the   same  name   it   is   important   to  note   that   they  are   still   separate, independent variables. In other words, modifying  $var1  within the function does not change the value assigned to the $var1 variable declared outside the function. The ability to have two variables with the same name in this context is the result of something called variable scope, a topic that will be covered later in this chapter. 

Returning Values by Reference In addition to passing arguments into a PHP function by reference, it   is also possible to 

Page 48: PHP Essentials

PHP Essentials 48

return a   result  by  reference.  To achieve  this,   the   function  name must  be  prefixed  with   the   '&' character in the function definition and, also at the point at which it  is called. In the following example the addNumber() function returns the result by reference: 

<?phpfunction &addNumbers ($arg1, $arg2){ $arg1 += 10; $varg2 += 10; return $arg1 + $arg2;}

$myVar = &addNumbers (20, 10);

?>

Functions and Variable Scope Now that we have covered PHP functions it is time to address an issue relating to variable 

scope. When a variable is declared outside of a function it is said to have global scope. That is, it is accessible to any part of the PHP script in which it  is declared. Conversely, when a variable is declared inside a function it is said to have  local  scope, in that it is only accessible to the script contained in the body of the function. 

This means that you can have a global variable and a local variable with the same name containing different values. In the following example the $myString variable is declared in both local and global scope with different string values: 

<?phpfunction showString (){ $myString = "local string"; echo "myString = $myString <br>";}

$myString = "global string";echo "myString = $myString <br>";showString();?>

When executed this will produce the following output:

myString = global stringmyString = local string

Clearly this will be a problem if you ever need to access a global variable in a function with a conflicting local variable name. Fortunately PHP provides the  GLOBALS  array which provides access to all global variables from within functions. If, therefore, we wanted to access the global version of  $myString from within   the  showString()  function,  which contains  a   local  version  of $myString, we could modify our script as follows: 

<?php

Page 49: PHP Essentials

PHP Essentials 49

function showString (){ $myString = "local string"; echo "myString = $myString <br>"; $globalString = $GLOBALS['myString']; echo "Global myString = $globalString <br>";}

$myString = "global string";echo "myString = $myString <br>";showString();?>

This would result in the following output: 

myString = global stringmyString = local stringGlobal myString = global string

12.  PHP Arrays

PHP Arrays provide a way to group together many variables such that they can be referenced and   manipulated   using   a   single   variable.   An   array   is,   in   many   ways,   a   self­contained   list   of variables. 

Once an array has been created items can be added, removed and modified, sorted and much more. The items in an array can be of any variable type, and an array can contain any mixture of data types ­ it is not necessary to have each element in the array of the same type. 

Elements of an array are accessed using a key. There are two types of array, and the type of key   that   is  used   to   access   an  array  element  dictates   the  array   type.   In  a  numerical  key  array, elements are accessed by specifying the numerical position of the item in the array. The first item in an array is element 0, the second is element 1 and so on. The second type of array is the associative array where a name is given to each element, and that name is used to access the corresponding array element. 

Create a PHP ArrayArrays are created using the  array()  function. The array()  function takes zero or more arguments and returns the new array which is assigned to a variable using the assignment operator (=). If arguments are provided they are used to initialize the array with data. 

PHP arrays grow and shrink dynamically as items are added and removed so it is not necessary to specify the array size at creation time as it is with some other programming languages. 

We can create an empty array as follows: 

Page 50: PHP Essentials

PHP Essentials 50

<?php $colorArray = array();?>

Alternatively,   we   can   create   an   array   pre­initialized   with   values   by   providing   the   values   as arguments to the array() function:

<?php $colorArray = array("Red", "Yellow", "Green", "Blue", "Indigo");?>

Accessing Elements in a PHP ArrayThe elements in a PHP numerical key type array are accessed by referencing the variable 

containing the array, followed by the index into array of the required element enclosed in square brackets ([]).  We can extend our previous example to display the value contained in the second element of the array (remember that the index is zero based so the first element is element 0): 

<?php $colorArray = array("Red", "Yellow", "Green", "Blue", "Indigo"); echo $colorArray[1];?>

The above echo command will output the value in index position 1 of the array, in this case the string "Yellow". 

Creating an Associative Array As described  earlier,   an  associative  array  assigns  names   to  positions   in   the  array.  This 

provides a more  human friendly  way to access array elements than the numerical key approach outlined above. Once again, the array() function is used to create the array, with optional arguments to pre­initialize the array elements. In the case of associative arrays, the arguments are of the form key=>value where key is the name by which the element will be referenced, and value is the value to be stored in that position in the array. 

Suppose we are creating an array to store bank customer information. We can assign a key name to each element in the array as follows: 

<?php$customerArray = array('customerName'=>'John Smith', 'customerAddress'=>'1 The Street', 'accountNumber'=>'123456789');?>

Accessing Elements of an Associative Array Now that we have created an associative array and assigned names to each element we can 

use those names to access the corresponding array values. We can, therefore, extend our previous example to extract the customer name from our $customerArray: 

Page 51: PHP Essentials

PHP Essentials 51

<?php $customerArray = array('customerName'=>'John Smith', 'customerAddress'=>'1 The Street', 'accountNumber'=>'123456789');

echo $customerArray['customerName'];?>

The result will be the customer name "John Smith" appearing in the browser window. 

Creating Multidimensional PHP Arrays A multidimensional PHP array is nothing more than an array in which each array element is 

itself an array. A multidimensional array can, therefore, be thought of as a table, where each element in the parent array represents a row of the table and the elements of each child array represent the columns of the row. 

The following PHP script provides an example of a multidimensional array where the books array is assigned an array for each element containing title and author information for each book: 

<?php $books = array(); $books[0] = array('title'=>'JavaScript in 24 Hours', 'author'=>'Moncur'); $books[1] = array('title'=>'JavaScript Unleashed', 'author'=>'Wyke'); $books[2] = array('title'=>'Network+ Second Edition', 'author'=>'Harwood');?>

Accessing Elements in a Multidimensional PHP Array To understand accessing elements of a multidimensional array it helps to continue to use the 

table analogy we started in the last section. Assuming a multidimensional array, we need to first specify the array row that we wish to access. Secondly, we need to specify the column in that row. To access an element, therefore we specify the array name and then follow it with the desired row and column of the array, each enclosed in square brackets ([]). 

For example, suppose we wish to access the author of the second book in our $books array: 

<?php $books = array(); $books[0] = array('title'=>'JavaScript in 24 Hours', 'author'=>'Moncur'); $books[1] = array('title'=>'JavaScript Unleashed', 'author'=>'Wyke'); $books[2] = array('title'=>'Network+ Second Edition', 'author'=>'Harwood');

echo $books[1]['author'];?>

The echo will output "Wyke" which is in the author column of the second row of the array. 

Page 52: PHP Essentials

PHP Essentials 52

Using PHP Array Pointers PHP arrays maintain an internal pointer that records the current element. This pointer can be 

changed using the  next,  previous,  reset  and  end  functions. The  reset  and  end  functions move the pointer to the first and last elements of the array respectively. The next function moves the pointer on to the next array element. The prev moves the pointer to the previous array element. The next and prev  functions   return   false   when   it   is   not   possible   to   move   any   further   in   the   corresponding direction. 

Each function takes the name of the array in which the pointer adjustment is to take place as an argument: 

<?php $colorArray = array("Red", "Yellow", "Green", "Blue", "Indigo");

echo 'The last element is ' . end($colorArray) . '<br>'; echo 'The previous element is ' . prev($colorArray) . '<br>'; echo 'The first element is ' . reset($colorArray) . '<br>'; echo 'The next element is ' . next($colorArray) . '<br>';?>

The above example will display the following output: 

The last element is IndigoThe previous element is BlueThe first element is RedThe next element is Yellow

Changing, Adding and Removing PHP Array Elements An array element can be changed by assigning a new value to it using the appropriate index key. For example, to change the first element of an array: 

$colorArray = array("Red", "Yellow", "Green", "Blue", "Indigo");

$colorArray[0] = "Orange";

A new item can be added  to   the end of  an array using the  array_push()  function.  This function takes two arguments, the first being the name of the array and the second the value to be added: 

$colorArray = array("Red", "Yellow", "Green", "Blue", "Indigo");

array_push($colorArray, "White");

A new element can be inserted at the start of the array using the array_shift() function which takes the array name and the value to be added as arguments: 

$colorArray = array("Red", "Yellow", "Green", "Blue", "Indigo");

array_shift($colorArray, "White"); // Add White to start of array

Page 53: PHP Essentials

PHP Essentials 53

The last item added to an array can be removed from the array using the array_pop() function. The following example removes the last element added: 

$colorArray = array("Red", "Yellow", "Green", "Blue", "Indigo");

array_push($colorArray, "White"); // Add White to end of array

array_pop($colorArray); // Remove White from the end of the array

The first item in the array can be removed using the array_unshift() function: 

$colorArray = array("Red", "Yellow", "Green", "Blue", "Indigo");

array_shift($colorArray, "White"); // Add White to start of array

array_unshift($colorArray) // Remove White from the start of the array

Looping through PHP Array ElementsIt is often necessary to loop through each element of an array to either read or change the 

values contained therein. There are a number of ways that this can be done. 

One such mechanism is to use the foreach loop. The foreach loop works much like a for or while loop and allows you to iterate through each array element. There are two ways to use foreach. The first assigns the value of the current element to a specified variable which can then be accessed in the body of the loop. The syntax for this is: 

foreach ($arrayName as $variable)

For example:

$colorArray = array("Red", "Yellow", "Green", "Blue", "Indigo");

foreach ($colorArray as $color) { echo "$color <br>"; }

This will result in the following output:

RedYellowGreenBlueIndigo

For associative arrays the foreach keyword allows you to iterate through both the keys and the values using the following syntax: 

foreach ($arrayName as $keyVariable=>$valueVariable)

For example:

$customerArray = array('customerName'=>'John Smith',

Page 54: PHP Essentials

PHP Essentials 54

'customerAddress'=>'1 The Street', 'accountNumber'=>'123456789');

foreach ($customerArray as $key=>$value) { echo "Key = $key <br>"; echo "Value = $value <br>"; }

This will result in the following output:

Key = customerNameValue = John SmithKey = customerAddressValue = 1 The StreetKey = accountNumberValue = 123456789

Replacing Sections of an Array Entire  blocks  of   array   element   can  be  modified  using   the  array_splice()  function.  The 

array_splice() function takes two mandatory and two optional arguments. The first argument is the name of the array on which the function is to work. The second argument specifies the index into the array where the splice is to take effect. The optional third argument specifies the end point of the splice (if the third argument is omitted the end of the array is assumed). The final argument is an optional array containing elements to be used to replace the removed items. 

The   following   example   creates   and   initializes   an   array,   then   creates   an   array   of   replacement elements before using the splice function: 

$myArray = array ('One', 'Two', 'Three', 'Four', 'Five');

$myReplacements = array ('Six', 'Seven', 'Eight');

$extract = array_splice ($myArray, 2, 4, $myReplacements);

The above example uses the array_splice() function to replace the Three, Four and Five with the Six, Seven and Eight from the $myReplacements array.

Sorting a PHP Array An array can be sorted using the  sort  function. A number of different sorts are possible 

using the  sort  function. The function takes two arguments. The first argument is the name of the array.   The   second   indicates   the   sort   algorithm   to   use.   The   available   algorithms   are SORT_NUMERIC,   SORT_STRING   and   SORT_REGULAR.   If   no   sort   type   is   specified, SORT_REGULAR is used. 

Similarly array items can be sorted in descending order using the rsort function. 

For example we can sort our array of color names: 

$colorArray = array("Red", "Yellow", "Green", "Blue", "Indigo");sort($colorArray, SORT_STRING);

Page 55: PHP Essentials

PHP Essentials 55

It is also possible to perform a Natural Sort using the natsort function. 

Sorting Associative Arrays Associative arrays can be sorted in two ways, either by key or by value. To sort by key use 

ksort and krsort (reverse sort). To sort by value use the asort and arsort functions. The syntax and options for these functions are as outlined for the sort and rsort functions above.

Getting Information About PHP Arrays & other Array Functions There are number of useful functions which can be used to obtain information about PHP 

arrays and also some functions that have not been covered in detail in this chapter. The following table lists these functions and provides descriptions: 

Function Description

print_r Prints the elements of an array to the output stream

array_keys Returns an array containing all the keys in an associative array

array_search Returns the key for given value in the array if value exists

array_values Returns an array containing all the values in an array

in_array Returns true or false depending on whether specified value is in array

array_merge Merge two or more arrays into a single array

array_reverse Reverse the order of elements in an array

shuffle Sorts the array elements into random order

13. Working with Strings and Text in PHPGiven that PHP is essentially a vehicle for the deployment of web content, and that much 

web content  is text based,  it  should come as no surprise  that PHP includes a range of features designed to ease the task of manipulating text and strings. 

In this chapter we will explore a number of the functions and techniques provided by PHP to enable you, as a web developer, to perform tasks such as changing the case of a string, replacing one part of a piece of text with another piece of text, searching text and much more. 

Changing the Case of a PHP String PHP provides a number of functions that enable changes to be made to the case of text 

contained in a string. These functions all take the string to be modified as an argument and return the modified string. It is important to note that these functions are nondestructive, that is to say they do not make any change to the original string, they simply return a completely new string containing the modification leaving the original string unaltered. The returned string can be assigned to a new variable or used directly in another function (such as a print or echo): 

Page 56: PHP Essentials

PHP Essentials 56

<?php$myString = "This is a test string.";

$newString = strtoupper($myString); // Assign converted string to a new variable

echo strtolower($myString); // Use retruned string in a eacho statement?>

If a change to the original string is required (as opposed to assigning the modified version to a new variable) the returned string can simply be assigned to the original variable: 

<?php$myString = "This is a test string.";

$myString = strtoupper($myString); // Assign converted string to the orignal variable

?>

The PHP string functions designed to change the case of a string are listed below with descriptions: 

• strtolower() ­ Converts entire string to lowercase 

• strtoupper() ­ Converts entire string to uppercase 

• ucfirst() ­ Converts the first letter of the sentence to uppercase 

• ucwords() ­ Converts the first letter of every word to uppercase

Converting to and from ASCII Values PHP provides the ability to work with ASCII (American Standard Code for Information Interchange) values. ASCII maps numerical character codes to standard, human readable characters. There are 127 ASCII characters representing the letters of the alphabet (including upper and lower case), numbers and various punctuation marks. There is also an extended character set which contains 255 characters. 

PHP provides two functions for the purpose of converting to and from ASCII codes: 

• ord() ­ Takes a character as an argument and returns the ASCII code corresponding to that character. 

• chr() ­ Takes an ASCII code as an argument and returns the character equivalent. 

The following example converts a character to an ASCII code and then reverts it back to the character: 

<?php$character = 'A';

$asciicode = ord($character);

echo "The ASCII code for $character is " . $asciicode . '<br>';

Page 57: PHP Essentials

PHP Essentials 57

$char = chr($asciicode);

echo "The character for ASCII code for $asciicode is " . $char . '<br>';

?>

When executed the above code will produce the following output:

The ASCII code for A is 65The character for ASCII code for is A

Printing Formatted Strings in PHP Those familiar  with other  programming  languages such as C and C++ will  probably be 

familiar with the concept of formatting strings and the printf() function. The printf function allows strings to be constructed that contain variables and provides a number of formatting options for those variables. 

Essentially, printf allows you to specify a string and define how particular variables are to be embedded in that string. fprintf() takes two or more arguments and takes the following form: 

fprintf ( "String", variable1, variable2, ... ); 

The String represents the string that is to be displayed and contains the formatting specifiers. The variables  specify the variables that are to be substituted in place of the respective formatting rules.

PHP printf Formatting Specifiers 

The formatting specifiers begin with a '%' character following by a letter to indicate the type of variable to be displayed. For example, a string is represented by %s. Optional rules can be placed between the '%' and the type letter to control formatting. 

The following table lists  the variable types and the corresponding letter to use when constructing the formatting rule: 

Specifier Description%% Displays a percent sign

%b A integer represented as a binary number

%c A character based on the ASCII value

%d A signed decimal number

%e Scientific notation (for example 1.2e+2)

%u An unsigned decimal number

%f A floating­point number

%F Floating­point number

Page 58: PHP Essentials

PHP Essentials 58

%o An octal number

%s A String

%x Hexadecimal number in lowercase letters

%X Hexadecimal number in uppercase letters

Before we look at the formatting options we first need to see some of the above rules in action. Let's begin by embedding a string variable into a PHP printf function call:

<?php$myColor = "Green";

printf("My favorite color is %s.", $myColor);

?>

In the above example the %s will be replaced by the value of $myString to create a string which reads: 

My favorite color is Green. 

We can now consider creating printf statements which combine a number of different formatting rules: 

<?php$myColor = "Green";$myNumber = 12;

printf("My favorite color is %s and my lucky number is %d.", $myColor, $myNumber);

?>

In the above example the %s will be replaced by the value of $myString and the %d will be replaced by the decimal value of $myNumber to create a string which reads: 

“My favorite color is Green and my lucky number is 12. “

Suppose we wanted to express our lucky number as a hexadecimal value (as all good software engineers do). All we would need to do is replace the %d with a %x: 

$formatted = printf ("My favorite color is %s and my lucky number is %x.", $myString);

thereby generating the following output:

My favorite color is Green and my lucky number is c. 

Finally we need to look at the formatting options which may be specified after the '%' character. 

• + ­ Forces both + or ­ in front of numbers. By default, only negative numbers display their 

Page 59: PHP Essentials

PHP Essentials 59

polarity. 

• n ­ Specifies what to use as padding (represented by n). Used in conjunction with the width specifier and defaults to space. Eg: %'_20s specified that '_' should be used as padding. 

• ­ Left­justifies the value 

• [0­9] Specifies the minimum width to be used by the variable ­ used in conjuction with the padding character 

• .[0­9] Specifies the number of decimal digits or maximum string length 

As always, some examples will hopefully help to clarify these options: 

To limit a floating point number to 2 decimal places: 

<?php

$myColor = "Green";$myNumber = 12.2089987;printf("My number is %.2f.", $myNumber);

?>

To pad the formatting with '_' characters to a width of 12 characters: 

<?php

$myNumber = 12.2089987;printf("My number is %'_12f.", $myNumber);

?>

resulting in the following output: 

My number is ___12.208999. 

Finding the Length of a PHP String The length of a PHP string can be obtained using the strlen() function. The strlen() function takes the string to be measured as an argument and returns the length value: 

<?php

$myString = "This is a short string";

$strLength = strlen ($myString);

echo "The string length is $strLength.<br>";

?>

Converting a String into a PHP Array Any string in PHP can be converted into a PHP array (see the PHP Arrays chapter for an overview 

Page 60: PHP Essentials

PHP Essentials 60

of arrays). This is achieved using the PHP explode() function. The explode() function takes three arguments and returns an array: 

• delimiter ­ the character that is to be used as the break point between array elements. For example a space character or a comma. 

• string ­ the string that is to be converted into an array. 

• divisions ­ (Optional). Specified the maximum number of array elements the string should be broken up into. When the limit is reach the final array element contains the remainder of the string. 

The following example shows the explode() function in use: 

<?php$myString = "This is a short string";

$myArray = explode(" ", $myString);

print_r($myArray);?>

The above example will result in the following output, which shows each word in the sentence assigned to an array element:

Array ( [0] => This [1] => is [2] => a [3] => short [4] => string )

Removing Leading and Trailing Whitespace from a PHP String The leading and trailing whitespace can be removed from a string using the PHP trim() 

function. Whitespace characters are defined by PHP to be space, tab, newline, carriage return, NULL and vertical tab characters. 

The trim() command takes the string to be trimmed as an argument and returns a modified version of the string. The function is non­destructive, in that it does not modify the original string. 

The following example trims the whitespace from the specified string: 

<?php$string = " This is a string with lots of whitespace ";

echo "Before trim [$string]";

$trimmedString = trim($string);

echo "After trim [$trimmedString]";

?>

Comparing Strings in PHPIn developing web applications it is extremely common to need to compare two strings. PHP 

Page 61: PHP Essentials

PHP Essentials 61

provides a number of functions that make it easy to perform a number of different string comparison tasks: 

• strcmp()  ­  Accepts   two strings  as  arguments,  performs a case­sensitive comparison and returns a value depending on the match. 

• strcasecmp ­ Accepts two strings as arguments, performs a case­insensitive comparison and returns a value depending on the match. 

• strncmp()  ­ Accepts three arguments ­ the two strings to be compared and the number of characters   to   be   included   in   the   comparison.   Performs   a   case­sensitive   comparison   of specified number of characters from each string and returns a value depending on the result of the match. 

• strncasecmp() ­ Accepts three arguments ­ the two strings to be compared and the number of characters to be included in the comparison. Performs a case­insensitive comparison of specified number of characters from each string and returns a value depending on the result of the match. 

String Comparison Functions Return Value The string comparison functions  perform an ASCII  based comparison of  each character.   If   the ASCII codes of the two strings match then the functions return 0. If the first string has an ASCII value  less   than   the second a  negative number  is   returned.   If   it   is  greater  a  positive number   is returned. 

Accessing and Modifying Characters in String The individual characters in a string can be accessed and modified by their position in a string. To achieve this, simply place the position of the required character in braces {} after the string variable name. Keep in mind that indexes are zero based, so the first character in a string in index position 0, not position 1. 

For example to access the 2nd character in a string: 

<?php

$myString = "abcdefghijklmn";

$myChar = $myString{1};

echo "2nd Char = $myChar";

?>

The above example will result in the following output: 

2nd Char = b 

Similarly the character position can be assigned a new value using the assignment operator: 

Page 62: PHP Essentials

PHP Essentials 62

<?php$myString = "abcdefghijklmn";

echo "Before change = $myString";

$myString{1} = 'B';

echo "Before change = $myString";?>

The result from the above output will read as follows: 

Before change = abcdefghijklmnBefore change = aBcdefghijklmn

Searching for Characters and Substrings in a PHP String PHP provides the ability to find the position of a specified sequence of characters (better 

known as a substring) within a string via the strpos() and strrpos() functions. 

The strpos() function finds the first occurrence a substring and takes two mandatory and one optional argument. The first argument is the string in which the search should be performed, and the second the substring for which to search. The optional third argument tells PHP the point in the string to initiate the search. The function returns boolean false if no match is found, otherwise it returns the index into the string of the occurrence. 

Note   that   if   a   string  begins  with   the   substring   there  will   be   some  confusion   since   the function will return 0, which could equally be interpreted as a failure to find a match. The key point to understand here is that a failure to find a match will return a boolean zero. A match starting at position zero will return a numeric 0. To resolve this issue it is best to ensure that you are comparing like variable types. You may recall from the PHP Operators chapter about comparing variables to ensure  they are of  the same type  and  value using  the === and !== operators.  We can use this technique to verify we are getting boolean false, and not an integer 0: 

<?phpif (strpos("Hello World", "Hello") !== false) echo 'Match found';?>

Similarly, the strrpos() function returns the position of the last occurrence of the substring. 

Extracting and Replacing Substrings in PHP A   sub­section   of   any   PHP   string   can   be   extracted   and   replaced   using   the  substr()  and substr_replace() functions. 

The substr() function takes two arguments which represent the source string and the start index. An optional third argument specifies the length of the substring (if no length is specified the end of the string is assumed). The function returns the requested substring:

Page 63: PHP Essentials

PHP Essentials 63

<?php

$myString = "There is a cat in the tree.";

$subString = substr ($myString, 11, 3);

echo "subString = $subString <br>";

?>

The above example will extract the word cat from the string. 

The substr_replace()  function takes up to four arguments. The first is the source string on which the replace is to be performed. The second argument is the replacement string. The third specifies  the index offset  of  the start  of  the replacement.  The optional fourth argument defines number of characters from the offset point to include in the replacement (useful if your replacement text is shorter than the original text being replaced). 

We can now extend our example to replace some text in our string: 

<?php

$myString = "There is a cat in the tree.";

echo "Original String = $myString<br>";

$myString = substr_replace ($myString, "dog", 11, 3);

echo "New String = $myString<br>";

?>

The above example will result in the following output: 

Original String = There is a cat in the tree.New String = There is a dog in the tree. 

It is perfectly valid to replace one substring with another of different length. It is also possible to simply remove a substring by simply passing in an empty replacement string to the substr_replace() function. 

Replacing All Instances of a Word in a PHP String All   the   instances  of  a  word   in  a   string  can  be   replaced  using   the  PHP  str_replace()  function. str_replace()  takes  three required and one optional argument.  The first  argument  represents  the string to be replaced, the second the replacement value and the third the target string. The optional fourth argument is a reference to a variable where the results of the replacement will be stored for subsequent inspection. 

A simple example is as follows: 

<?php$myString = "There is a cat in the tree, and I think it is my cat!";

Page 64: PHP Essentials

PHP Essentials 64

echo "Original String = $myString<br>";

$myString = str_replace ("cat", "dog", $myString);

echo "New String = $myString<br>";?>

Resulting in the following output: 

Original String = There is a cat in the tree, and I think it is my cat!New String = There is a dog in the tree, and I think it is my dog! 

If  the search and replacement values are arrays of words then each word in the search array is replaced by the corresponding value in the replacement array. For example: 

<?php$myString = "There is a cat in the tree, and I think it is my cat!";

echo "Original String = $myString<br>";

$myString = str_replace (array("is", "cat", "tree"), array("was", "dog", "car"), $myString);

echo "New String = $myString<br>";?>

The above example results in the following output: 

Original String = There is a cat in the tree, and I think it is my cat!New String = There was a dog in the car, and I think it was my dog! 

A case insensitive search and replace can similarly be performed using the eregi_replace() function which takes the same arguments as str_replace() 

14. PHP, Filesystems and File I/O

One of the benefits of PHP being a server side scripting environment is that it gives the web developer easy access to the filesystem of the server on which the web server is running. This gives us the ability to create, open, delete, read and write to files. We can also traverse the directory hierarchy of the server systems to do things like get directory listings and create new sub­directories 

(see Working with Directories in PHP). 

Opening and Creating Files in PHP Existing files are opened, and new files created using the PHP fopen() function. The fopen() 

function accepts two arguments and returns a file handle which is subsequently used for all future read and write interactions with that file. The first argument is the name (including the path) of the file to open. This path is relative to the server filesystem root, not your web server root. The second argument is an attribute indicating the mode in which to open the file (create, read only, write only etc). The following table lists the various file open attributes together with a brief description of each: 

Page 65: PHP Essentials

PHP Essentials 65

Mode Description

r Read only access. Pointer is positioned at start of file.

r+ Read and write access. Pointer is positioned at start of file.

wWrite only access. Pointer is positioned at start of file. File is created if it does not already exist.

w+Read and write access. Pointer is positioned at start of file. File is created if it does not already exist.

aWrite only access. Pointer is positioned at end of file. File is created if it does not already exist.

a+Read and write access. Pointer is positioned at end of file. File is created if it does not already exist.

xCreate and open for write only. Pointer is positioned at start of file. Return false if file already exists.

x+Create and open for read and write. Pointer is positioned at start of file. Return false if file already exists.

Closing Files in PHP Once  a   file  has  been  opened   it   can  be  closed  using   the  fclose()  function.  The  fclose() 

function takes a single argument ­ the file handle returned by the fopen function when the file was first opened. 

Given this information we can write a script to open a file. For the purposes of this example we will create a new file in the /tmp directory of our web server. We will open the file in w+ mode so that it will be created if it does not already exist and provide both read and write access. We will then close the file using fclose(): 

<?php$fileHandle = fopen('/tmp/php_essentials.txt', 'w+') OR die ("Can't open file\n");

fclose ($fileHandle);?>

Writing to a File using PHP Having created and opened the file the next task is to write data to the file. We can do this 

using the PHP fwrite() and fputs() functions. These are essentially the same function so either can be used. 

fwrite() takes two arguments, the file handle returned from the original fopen() call and the string to be written. We can, therefore, extend our example to write a string to our file: 

<?php

$fileHandle = fopen('/tmp/php_essentials.txt', 'w+') OR die ("Can't open file\n");

$result = fwrite ($fileHandle, "This line of text was written by PHP\n");

Page 66: PHP Essentials

PHP Essentials 66

if ($result){ echo "Data written successfully.<br>";} else { echo "Data write failed.<br>";}

fclose($fileHandle);?>

After running the above script you should find a file exists on your server containing the line This line of text was written by PHP. 

Reading From a File using PHP Data can be read from a file using the PHP fread() function. fread() accepts two arguments, the file  handle and the number of bytes to be read from the file: 

<?php$fileHandle = fopen('/tmp/php_essentials.txt', 'w+') OR die ("Can't open file\n");

fwrite ($fileHandle, "This line of text was written by PHP\n");

fclose($fileHandle);

$fileHandle = fopen('/tmp/php_essentials.txt', 'r') OR die ("Can't open file\n");

$fileData = fread ($fileHandle, 1024);

echo "data = $fileData";

fclose($fileHandle);

?>

The above example should generate the following output: 

data = This line of text was written by PHP

Note the use of the "OR die()" syntax in the above example. The reason for this is to call the die() function if the specified file cannot be opened. The purpose of the built­in PHP die() function is to display a message (specified within the parentheses) and then exit the script. This prevents the remaining PHP code from executing and attempting to read from a file which could not be opened. 

It   is   also  possible   to   read   and  output   the   contents  of   an   entire   file  with   the  readfile() function. This function reads the entire contents of a file and outputs that content. Assuming you don't need to do anything but output the contents of a file then readfile() is an easy solution because it does all the work for you. You do not need to open the file, read the data, close the file and display the data. All you need to do is call readfile() passing in the file path as an argument and it does the rest. 

Page 67: PHP Essentials

PHP Essentials 67

Checking Whether a File Exists The  file_exists  function  can  be  used  at   any   time   to   find   if   a   file   already  exists   in   the 

filesystem. The function takes a single argument ­ the path to the file in question and returns a boolean true or false value depending on the existence of the file. 

Moving, Copying and Deleting Files with PHP Files can be copied using the  copy()  function, renamed using the  rename()  function and deleted using the unlink() function. For example we can perform a number of tasks on our example file: 

<?php

if (file_exists('/tmp/php_essentials.txt){ copy ('/tmp/php_essentials.txt, '/tmp/php_essentials.bak'); // Copy the file

rename ('/tmp/php_essentials.bak', '/tmp/php_essentials.old'); // Rename the file

unlink ('/tmp/php_essentials.old'); // Delete the file}?>

Accessing File Attributes PHP provides access to a wide range of file attributes such as when the file was created, whether the file is readable or writeable and the current file size. 

The PHP stat() and fstat() functions provide a wealth of information about a file. The information is so copious that the results are returned as an associative array. The functions take a single argument. stat() takes a string defining the path to the file. fstat() takes a file handle returned from an fopen() function call. 

The following table outlines the array values returned by both functions: 

Key Descriptiondev Device number

ino Inode number

mode Inode protection mode

nlink Number of links

uid User ID of owner

gid Group ID of owner

rdev Inode device type

size Size in bytes

atime Last access (Unix timestamp)

mtime Last modified (Unix timestamp)

Page 68: PHP Essentials

PHP Essentials 68

ctime Last inode change (Unix timestamp)

blksize Blocksize of filesystem IO (platform dependent)

blocks Number of blocks allocatedWith reference to the above table we can now extract some information about a file on the file system of our server: 

<?php

$results = stat ("/tmp/php_essentials.txt");

echo "File size is $results[size]<br>";echo "File last modifed on $results[mtime]<br>";echo "File occupies $results[blocks] filesystem blocks<br>";?>

It   is  also  possible   to  check  the  status  of  a   file   in   terms  of   read  and  write  access.  The is_readable()  and  is_writable()  functions take the path to file as an argument and return  true  or false. The is_link() function can similarly be used to identify whether the file is a symbolic link to another file. 

PHP Output Buffering Output  buffering   in  PHP is  a  mechanism whereby content   that  would  normally be  sent 

directly to the output stream is initially held in a buffer until the buffer is flushed. This provides control over when output is presented to the user (perhaps in situations where there is a delay in gathering some data from a database for example). 

Output   Buffering   is   initiated   using   the  ob_start()  function.  ob_start()  can   be   called   with   no arguments but does support three optional arguments: 

• callback function ­ specifies a user defined function to be called before the buffer is flushed 

• bytes ­ an integer representing the number of bytes to be buffered before the callback is triggered. Set to null to disable this feature 

• delete buffer ­ Boolean value specifying whether buffer should be deleted after  ob_end() call. 

The contents of the buffer are flushed using the  ob_flush()  function. It is also to possible to both flush and stop future buffering using the ob_end_flush() function. 

It is also possible to delete all buffer content without flushing with a call to the ob_clean() function. 

Finally the contents of the buffer may inspected at any time using the  ob_get_contents()  function which returns a string containing the buffer content. 

<?php

ob_start(); //start bufferingecho "This content will be buffered"; // write some content to the bufferob_end_flush(); // flush the output from the buffer ?>

Page 69: PHP Essentials

PHP Essentials 69

15. Working with Directories in PHPNow that we have spent some time looking at how to work with files in PHP (see  PHP, 

Filesystems and File I/O) it is now time to look at how to work with file system directories. PHP provides a number of functions that can be used to perform tasks such as identifying and changing the current directory, creating new directories, deleting existing directories and listing the contents of a directory. 

Creating Directories in PHP A new directory can be created in PHP using the mkdir() function. This function takes a path 

to the directory to be created. To create a directory in the same directory as your PHP script simply provide the directory name. To create a new directory in a different directory specify the full path when calling mkdir(). 

A second, optional argument allows the specification of permissions on the directory (controlling such issues as whether the directory is writable): 

<?php$result = mkdir ("/path/to/directory", "0777");?>

Deleting a Directory Directories are deleted in PHP using the rmdir() function. rmdir() takes a single argument, 

the name of the directory to be deleted. The deletion will only be successful if the directory is empty. If the directory contains files or other sub­directories the deletion cannot be performed until those files and sub­directories are also deleted. 

Finding and Changing the Current Working Directory It is unlikely that a web application will be able to perform all of its file related tasks in a 

single directory. For this reason, it is vital to be able to both find out the current working directory, and change to another directory from within a PHP script. 

The current working directory can be identified using the getCwd() function: 

<?php$current_dir = getCwd();

echo "Current directory is $current_dir";?>

The current working directory can be changed using the chdir() function. chdir() takes as the only argument the path of the new directory: 

<?php

$current_dir = getCwd();

echo "Current directory is $current_dir <br>";

Page 70: PHP Essentials

PHP Essentials 70

chdir ("/tmp");

$current_dir = getCwd();

echo "Current directory is now $current_dir <br>";?>

Listing Files in a Directory The files in a directory can be read using the PHP scandir()  function.  scandir()  takes two 

arguments. The first argument is the path the directory to be scanned. The second optional argument specifies how the directory listing is to be sorted. If the argument is 1 the listing is sorted reverse­alphabetically. If the argument is omitted or set to 0 the list is sorted alphabetically: 

<?phpchdir ("/tmp");

$current_dir = getCwd();

echo "Current directory is now $current_dir";

$array = scandir(".", 1);

print_r($array);?>

16. An Overview of HTML FormsA large part of developing a web based application  involves handling interaction with user 

via their  web browsers. One of the most common tasks in this area of  web development  involves presenting the user with forms to collect information, and then processing that information. 

Web forms  are typically created using the  HTML  <FORM> element together with various u  ser interface    objects (such as text fields, toggle buttons and push buttons). 

Before   exploring   the   interaction  between  PHP and   the  HTML form elements   it   is   first important to have a basic understanding of HTML forms. The purpose of this chapter, therefore, is to provide this basic grounding before moving on to the more PHP specific areas of building a form. If you are already familiar with HTML forms feel free to move on to PHP and HTML Forms. 

Creating HTML Forms HTML forms are used to collect data from users. Users essentially enter data into forms by 

filling in text fields, selecting toggles and making choices from selection objects. When the user has filled in the data it is transmitted to the server for processing. 

HTML   forms   are   specified   using   the   <form>   element.   The   form   element   contains   an attribute that specifies the script on the server to which the gathered data is to be sent. Data can be sent to the server using one of two methods, GET or POST. With GET, all the data is passed to the server embedded in the URL. POST is typically used for larger volumes of data. 

Page 71: PHP Essentials

PHP Essentials 71

The various <input> elements are then specified within the body of the <form>. 

With this information in mind we can create a simple HTML form containing a text field input and a submit button as follows: 

<html><head><title>Simple HTML Form</title></head><body><form action="submit.php" method="post"><input type="text" name="customerName" value="Default text here" /><input type="submit" name="submit_button" value="Press to Submit" />

</form></body></html>

HTML Text Object The most common form object is the Text object. The Text object places a single line text field into the form into which the user can type information. 

The syntax for creating a text object within a Form is as follows: 

<input   type="TEXT" name="objectname"   id="object   id"  value="current  value"  size="30"  event  handling> 

• type ­ specifies that the type of object is a TEXT object. 

• name ­ represents the name by which this object may be reference in JavaScript. 

• id  ­ the id used when accessing Form object elements using the  getElementById() method (described later in this chapter) 

• value ­ primes the text object with an initial value (optional). 

• size ­ specifies the maximum number of characters that can be entered into the Text field. 

event handling  specifies what JavaScript action to take when a particular event on the object is triggered. Events that can be triggered by the Text object are: 

• onFocus ­ triggered when the text field gains focus (typically when the cursor is moved into the field to begin typing). 

• onBlur ­ triggered when the text field loses focus (typically when the user clicks somewhere outside the text area). 

• onChange ­ triggered when the contents of the text area is changed by the user and focus is lost. 

• onSelect ­ triggered when the user highlights text in the text field. 

In addition to events, the Text object also has a number of JavaScript methods that can be accessed to perform such tasks as selecting text and changing focus: 

Page 72: PHP Essentials

PHP Essentials 72

• focus() ­ Sets focus and sets the cursor on the text field 

• blur() ­ Removes focus from the field (the opposite of focus()) 

• select()  ­  Selects the text in the field so that when the user types all the existing text is replaced. 

HTML TextArea Object The TextArea object is created using the <textarea> tag and differs from the Text object in 

that it allows multiple lines of text to be entered by the user. Additional attributes allow control over such issues as the size of the TextArea defined in terms of row and columns, whether the text should wrap or not and whether the TextArea should be read­only. 

There are two options for the  wrap  attribute,  virtual  and  physical. When set to  virtual  the TextArea object will wrap text at the end of each line as it is entered by the user but the actual text stored in the value will not contain any carriage returns unless the user specifically enters one while typing. The  physical  setting also wraps automatically as text is entered, but this time a carriage return is also inserted into the text. 

The following is an example of using the TextArea object with pre­set dimensions and wrapping enabled: 

<textarea name="myTextArea" rows="10" cols="60" wrap="virtual">Some default text here</textarea>

In the above example you will see some text before the closing </textarea> tag. If provided, this represents the text to be displayed by default in the TextArea object. 

The HTML Button Object Next   to   the  Text  object   the  HTML Button   is  probably   the   second  most   commonly  used  GUI component when developing HTML forms. There are three types of Button object available. As with the Text object, the Button uses the <input> tag. The  type=  attribute is then used to define which type of button is to be created. The three different types are: 

• type="BUTTON" ­ The basic button which performs no action by default unless an event handler is assigned to it. 

• type="SUBMIT"  ­  The submit button. When pressed this button causes the data in the Form to be sent to the server using the settings defined in the enclosing <Form> tag. If the onsubmit  attribute on the enclosing  <form>  tag has been specified this will be executed before the form data is submitted (useful for JavaScript form data validation). 

• type="RESET" ­ The reset button. When pressed causes the fields in the Form to be either cleared, or reset to the defaultValue (if one has been specified). 

Page 73: PHP Essentials

PHP Essentials 73

A submit button can be created as follows: 

<form name="registerForm" method="GET" action="/subscribe.php">

<input type="TEXT" name="myName" value=""/> <input type="TEXT" name="myPhone" value=""/> <input type="SUBMIT" name="buttonName" value="Click here to submit information">

</form>

When the submit button is pressed in the above example the data in the two Text fields will be submitted to the subscribe.php script specified in the <form> tag. 

The generic "BUTTON" type can be defined as follows: 

<form name="registerForm" method="GET" action="register.php">

<input type="TEXT" name="myName" value=""/> <input type="TEXT" name="myPhone" value=""/> <input type="BUTTON" name="buttonName" value="Product codes" onClick="showCodes()">

</form>

In this case we have configured the button to call a JavaScript function when it is pressed. This function could, for example, pop up a window containing a description or product code list. To learn about JavaScript we recommend reading JavaScript Essentials. 

HTML Check Boxes The   Check   Box   object   creates   a   small   square   which   changes   between   a   checked   and 

unchecked state when clicked. Check Boxes are ideal for providing the user with a "Yes" or "No" choice. 

The Check Box object uses the <input> tag as follows: 

<form action="" name="orderForm"><input type="CHECKBOX" name="mailListBox" checked>Add me to the mailing List.</form>

The checked attribute states whether the box should be checked by default when it is first created. 

The current setting of a CheckBox can be obtained in JavaScript by accessing the checked property of the object. For example: 

if (document.orderForm.mailListBox.checked){ addToMailingList();}

Page 74: PHP Essentials

PHP Essentials 74

You can also change the state of a Check Box by explicitly setting the checked property: 

document.orderForm.mailListBox.checked = false;

The Check Box object has one JavaScript event, onClick, which is triggered when the user clicks on the box, and one method, click(), which simulates a user click when called. 

HTML Radio Buttons The HTML Radio Button takes its name from the buttons on an old style radio. In the old 

days a   radio would have a  number  of  buttons  for  making selections  (such as   frequency band). Depressing one button would cause the currently selected button to pop up, thereby ensuring that only one button was pressed at any one time. HTML Radio Buttons provide a similar functionality for situations where a "one of many" choice is to be presented to the user. 

The syntax for creating a group of Radio Buttons is as follows: 

<form action="" name="orderForm"> <input type="RADIO" name="myColor" value="Red" checked> Red <input type="RADIO" name="myColor" value="Green"> Green <input type="RADIO" name="myColor" value="Blue"> Blue</form>

All three buttons share the same name attribute which acts to tie them together into a group. The value attribute defines the value that is passed through the server to indicate which button is selected when the form is submitted. 

There are number of actions that can be performed using JavaScript when working with Radio Buttons. Firstly, you can find out the number of Radio Buttons in a group by accessing the length property: 

var numButtons = document.orderForm.myColor.length;

Secondly you can change the value of an individual button: 

document.orderForm.myColor[0].checked = true;

Page 75: PHP Essentials

PHP Essentials 75

Note: Programmatically changing the value of one Radio Button in a group using the above technique will not automatically uncheck the currently checked button (as it would if a user really clicked on it). You must, therefore, remember to programmatically change the checked status of the other buttons. 

HTML Drop­down / Select Object The HTML Select object provides a drop down list  of  choices from which the user can 

choose (often referred to as ComboBoxes in other GUI environments). When the drop down list is not visible the current selection is displayed in a text area. Due to the fact that the Select Object supports both single and multiple selection of items in the list it is ideal for both "one of many" and "many of many" selection choices. 

The Select Object uses the <select> tag together with <option> tags representing the choices to be displayed in the drop­down list: 

<select name="carBrands"><option value="Ford" SELECTED>Ford Motor Company<option value="GM">General Motors<option value="Honda">Honda Motor Company</select>

The above example will create a Selection object that appears as follows. The image on the left shows the Select object before the user clicks on it. The image on the right shows the drop­down list as it appears after the object has been clicked: 

  

If the size attribute is specified and set to a value greater than 1 then a scrolled list, instead of a drop down list, will be displayed with a scrollbar for scrolling through the list of options. For example: 

<select name="carBrands" size=5><option value="Ford" SELECTED>Ford Motor Company<option value="GM">General Motors<option value="Honda">Honda Motor Company<ottion value="Toyota">Toyota Motor Company<option value="Ford">Jaguar

Page 76: PHP Essentials

PHP Essentials 76

<option value="Mazda">Mazda<option value="Volvo">Volvo</select>

will produce the following in the browser:

The optional multiple attribute may be added to the <select> tag to enable multiple selection of items from the list. When the Select element is used in multiple selection mode it is important to place [] after the element name so that the PHP script on the receiving end of the submission is able to access the multiple selections via an array: 

<select name="carBrands[]" size=5 multiple>

This is covered in detail in PHP and HTML Forms. 

HTML Password Object The HTML Password object is used to collect information from a user (typically, but limited 

to a password or account number) when the data entered should not visible on the screen. As the user  types  '*'  characters appear   in  the text  field  for each key press,   instead of  the actual   typed character. 

The basic syntax for the Password Object is as follows: 

<input type="PASSWORD" name="objectName" size="10" />

17. PHP and HTML FormsIn this chapter will create a simple HTML form to gather information from the user and then 

create a  PHP script  to process that data once it  has been submitted to the  server.  This chapter assumes an understanding of HTML forms. See the  An Overview of HTML Forms  chapter for a basic overview of this topic. 

Page 77: PHP Essentials

PHP Essentials 77

Creating the Form The first step involves creation of an HTML page to contain our form. The form will be very 

simple in that it will contain only a text area for the user to enter data and a submit button with which to send it to the server. We will use the POST method of transmitting the data to the server and specify "subscribe.php" as the server side script to handle the data: 

<html><head><title>Simple HTML Form</title></head><body><form action="submit.php" method="post">

<input type="text" name="customerName" value="Enter your name here" /> <input type="submit" name="submit_button" value="Press to Submit" />

</form></body></html>

The above HTML code will result in the following when loaded into a web browser: 

Processing Form Data Using PHP 

Now that we have created a form we need to understand how to process the data entered by the user in our server side PHP script. There are two mechanisms for transmitting the data from an HTML form to the server, GET and POST. In our example above we specified POST, but in either case the task of reading this data in our PHP script is equally simple. 

Essentially PHP places the data from the form into an associative array (for information on PHP arrays see  PHP Arrays) which can be accessed from within the server side PHP script. For POST and GET the array variable names are $_POST and $_GET respectively. 

For our example HTML form we can write a simple subscribe.php script to output the content of the $_POST method when the form is submitted it to our web server: 

<?phpecho 'Data submitted:<br>';

Page 78: PHP Essentials

PHP Essentials 78

print_r($_POST);?>

When a name is entered and the submit button pressed the following output is generated by our subscribe.php script: 

Data submitted:Array ( [customerName] => Neil [submit_button] => Press to Submit ) 

You will recall we mentioned this is an associative array, so each element is accessible by a named index key. You may also have noticed that we gave our text input a name value of 'customerName' when we defined it in our form: 

<input type="text" name="customerName" value="Enter your name here" /> 

This name is used as the key into our GET and POST associative arrays so that we can access each data element individually by the name used in the form. Let's extend both our HTML form and PHP scripts to handle more test fields and also include a toggle button: 

<html><head><title>Simple HTML Form</title></head><body><form action="subscribe.php" method="post">Name: <input type="text" name="customerName" value="" /><br>Email: <input type="text" name="emailAddress" value="" /><br>Send Email Newsletter: <input type="checkbox" name="sendNews" checked /><br><input type="submit" name="submit_button" value="Press to Submit" />

</form></body></html>

We can now modify our  subscriber.php  script to read the additional information from the $_POST array variable. Before we do this, however, there is an important issue to address. Data about the sendNews check box will only be included in the POST data if the check box is set. If it is not set then no entry for it will be included in the $_POST array. We need, therefore, to use the array_key_exists() or isset() functions to verify if the check box was set or not. This is considered to be good practice in general for validating array elements in POST or GET arrays: 

<?php

echo "Your name is " . $_POST['customerName'] . "<br>"; echo "Your email address is " . $_POST['customerName'] . "<br>";

if (array_key_exists ('sendNews', $_POST)) { echo "You have requested our newsletter<br>"; } else { echo "You have declined our newsletter<br>"; }

Page 79: PHP Essentials

PHP Essentials 79

?>

Now, when we reload the web page, enter a name and email address and check the toggle, submitting the form gives us the following output: 

Your name is NeilYour email address is [email protected] have requested our newsletter

Processing Multiple Selections with PHP In An Overview of HTML Forms we covered the HTML Select input and described the steps 

required to configure the object for multiple selection. For example, the following HTML fragment creates a Select input in which multiple car types may be selected by the user: 

<select name="carBrands" size=5 multiple><option value="Ford" SELECTED>Ford Motor Company<option value="GM">General Motors<option value="Honda">Honda Motor Company<ottion value="Toyota">Toyota Motor Company<option value="Ford">Jaguar<option value="Mazda">Mazda<option value="Volvo">Volvo</select>

Up until now we have only concerned ourselves with data which only holds one value (the text in a text field for example). Clearly, in this case there is the potential for multiple data values to be associated with a single form element. The way PHP handles this is to place the multiple selections in an array. Before that happens, however, we need to make a small modification to our declaration of the HTML Select element. All we need to do to turn this data into an array is to place [] after the element name: 

<select name="carBrands[]" size=5 multiple>

Now, in our server side PHP script we can extract the selected items from this array: 

print_r($_POST['carBrands']);

Assuming we selected GM and Ford the output would read: 

Array ( [0] => Ford [1] => GM )

Page 80: PHP Essentials

PHP Essentials 80

18.  PHP and Cookies ­ Creating, Reading and WritingWeb servers are typically stateless entities. That is to say they serve up web pages without 

regard to who requested the page and with no knowledge of whether that person has previously requested other pages. This makes it difficult for web based applications to track whether a visitor is new to the site or whether they have visited before and have already logged into a service. Cookies were developed to provide a mechanism to track state in the otherwise stateless world of the web. 

Cookies  essentially  provide a  mechanism to store small  pieces  of  data  on  the  computer systems of the visitors to your site. This enables you to maintain the state of a user's visit to your site so that you can track their movement through the site, or to store information such as their user name and address after they have entered it on one page so that they don't have to keep re­entering it on different pages. 

Before going too far in implementing cookies on your web site it is important to keep in mind that users can disable cookie support in their browsers. You should, therefore, avoid making your site completely dependent on cookies. 

Another   option   for  maintaining   state   is   to   use  PHP  Sessions   (see  Understanding  PHP Sessions  for more information). Cookies and sessions differ in important ways, and which to use depends on your requirements. 

The Difference Between Cookies and PHP Sessions Both cookies and PHP sessions allow you to store data that is accessible across different pages of your web site, but there are differences between the two approaches. 

Cookies are stored on the hard drive of the visitor to your site and are, therefore, visible to other domains you may host and run. They also have a long life and can be configured to persist long after the user has left your site. Cookies are limited in size and quantity (4kb each and a maximum of 20 cookies per domain). 

PHP sessions, on the other hand, are stored on the web server. This means they are not visible to other web servers you may have hosting your domain. They are also not limited in size and can be used for storing secure data, since they are not transmitted to the client browser in the way that cookies are. 

The Structure of a Cookie Cookies allow data to be stored in the form of a name/value pair. Both the name and the value are set at your discretion. For example you might want to write a cookie that stores the user name in the form username=JohnW. The cookie also contains additional information such as an expiration date and a domain. 

The format of a cookie is as follows: 

name=value; expires=expirationDateGMT; path=URLpath; domain=siteDomain

Page 81: PHP Essentials

PHP Essentials 81

Cookie Expiration Setting The optional  expires=  section  specifies   the  date  on  which  the  associated  cookie  should 

expire. The PHP time() function can be used to obtain and manipulate dates for this purpose as we will examine later in this chapter. 

Cookie path Setting The path= setting allows a URL to be stored in the cookie. By default, cookies are accessible 

only to web pages in the same directory as the web page which originally created the cookie. For example,   if   the   cookie   was   created   when   the   user   loaded http://www.techotopia.com/intro/index.html that cookie will be accessible to any other pages in the /intro directory, but not to pages in /navigation. By specifying  path=/navigation  this limitation is removed. 

Cookie domain Setting Similar to the path setting, cookies are only accessible to web pages residing on the server 

domain from which the cookie was originally created. For example, a cookie created by a web page residing   on   www.techotopia.com   is   not,   by   default,   accessible   to   a   web   page   hosted   on www.linuxtopia.org. Access to the cookie from web pages on linuxtopia.org can be enabled with a domain=linxutopia.org setting. 

Cookie Security Setting This setting controls whether the cookie is transmitted using insecure HTTP or secure HTTPS. 

Creating a Cookie in PHP Cookies are created in PHP using the  setcookie()  function.  setcookie()  takes a number of 

arguments. The first argument is the name of the cookie (the name part of the name/value pair described earlier). The second is the value part of the name/value pair. The third argument is the optional expiration date of the cookie. The fourth argument specifies the active path for the cookie. The fifth argument is the domain setting and the sixth is the security setting (0 specifies HTTP and HTTPS and 1 specifies HTTPS only). 

Based on the above information we can create a cookie using the following PHP: 

<?php setcookie('userName', 'JohnW', time() + 4800); echo 'Cookie has been set<br>';?>

The   above   example   creates   a   cookie   on   the   computer   system   of   anyone   who   loads   the   page (assuming   they   have   cookies   enabled   in   their   browser)   containing   the   name   value   pair userName=JohnW'. The cookie will expire 4800 seconds from the time it is created. 

Page 82: PHP Essentials

PHP Essentials 82

Reading a Cookie in PHP Given that you've gone to the trouble of writing a cookie it stands to reason you'll probably 

want   to   read   it   back  at   some point.  This   is   achieved by  accessing   the  $_COOKIE array.  The $_COOKIE array is an associative array whereby the name of the cookie provides the index into the array to extract the corresponding value of the name/value pair (for details of PHP arrays read the PHP Arrays chapter of this book. 

For example we can obtain the value of our userName cookie as follows: 

<?php echo 'Reading cookie<br>';

echo 'userName = ' . $_COOKIE['userName'];?>

The above script should generate the following output: 

Reading cookieuserName = JohnW

Deleting a Cookie Cookies are deleted by calling the setcookie() function with the cookie name, a null for the 

value and an expiration date in the past. Once again the time() function can be used to calculate an expired date: 

<?php setcookie ('userName', '', time() - 4800);?>

19. Understanding PHP SessionsIn the previous chapter (PHP and Cookies ­ Creating, Reading and Writing) we looked at the use of cookies   to   maintain   state.   In   that   chapter   we   also   mentioned   the   use   of   PHP   sessions   as   an alternative to the use of cookies. We also provided an overview of the difference between cookies and PHP sessions. 

In this chapter we will explore the concept of PHP sessions in more detail and provide some examples of how to create and use sessions. 

What is a PHP Session? PHP Sessions allow  web pages  to be treated as a group, allowing variables to be shared 

between different pages. One of the weaknesses of cookies is that the cookie is stored on the user's compute   r   (and by user we mean the person with the browser visiting your web site). This provides the user the ability to access, view and modify that cookie for potentially nefarious purposes. PHP sessions, on the other hand, store only an ID cookie on the user's system which is used to reference the session file on the server.   As such, the user has no access to the content of the session file, 

Page 83: PHP Essentials

PHP Essentials 83

thereby  providing   a   secure   alternative   to   cookies.  PHP  sessions   also  work  when   the  user   has disabled the browser's cookie support. In this situation it includes the session ID information in the web page URLs. 

Creating a PHP Session PHP sessions are created using the session_start()  function which should the first function 

call of the PHP script on your web page (i.e. before any output is written to the output stream). 

The following example demonstrates the creation of a PHP session: 

<?php session_start();?><html><head><title>A PHP Session Example</title></head><body></body></html>

Creating and Reading PHP Session Variables Variables can be assigned to a session using the $_SESSION array. This is a global array 

that is accessible to all the pages on your web site. This is also an associative array (see PHP Arrays for details of using arrays in PHP) and as such it is possible to access array elements using the variable name as an index. 

Session variables can be any type of data such as strings, numbers, arrays and objects. 

Session variables can be defined using a number of mechanisms. Variables can be assigned directly to the $_SESSION array using the assignment operator and variable name: 

<?php $_SESSION['userName'] = 'JohnW';?>

Another option is to use the PHP  session_register()  function.  session_register()  takes two arguments, the string representing the variable name, and the value to be assigned to the variable: 

<?phpsession_register('username', 'JohnW');?>

Session   variables   are   accessed   by   using   the   variable   name   as   an   index   key   into   the $_SESSION array. The session_is_registered() function can also be used to make sure the variable exists before attempting to read the value (which is generally considered to be good practice). For example: 

Page 84: PHP Essentials

PHP Essentials 84

<?phpsession_start();?><html><head><title>Simple HTML Form</title></head><body><?php $_SESSION['userName'] = 'JohnW';

if (session_is_registered('userName')) { echo 'userName = ' . $_SESSION['userName']; }?>

</body></html>

The resulting output from the above page will read: 

userName = JohnW

The same PHP code to read the value can be used on any page on your web server to access the current value of the variable. 

Writing PHP Session Data to a File Session data only stays active on the web server until it expires or the session is deleted. 

Once deleted, all the data associated with the session is lost. A snapshot of the session data can, however,  be  taken at  any  time and written  out   to  a   file.  Once saved,   it   can be  reloaded when required. 

To save a session state the  session_encode()  function is used combined the PHP file I/O functions   (see  PHP,   Filesystems   and   File   I/O  for   details   of   reading   and   writing   files).   The session_encode()  function returns an encoded string containing the session data. Once this string has been obtained it can be written to a file: 

<?phpsession_start();?><html><head><title>Simple HTML Form</title></head><body><?php $_SESSION['userName'] = 'JohnW'; $_SESSION['emailAddress'] = '[email protected]'; $session_data = session_encode(); // Get the session data $filehandle = fopen ('/tmp/php_session.txt', 'w+'); // open a file write session data fwrite ($filehandle, $session_data); // write the session data to file

Page 85: PHP Essentials

PHP Essentials 85

fclose ($filehandle);?>

</body></html>

If you are interested in seeing what the encoded session data looks like you can load it into a text editor. The above example creates the following data in the file: 

userName|s:5:"JohnW";emailAddress|s:16:"[email protected]";

Reading a Saved PHP Session Once session data has been written to a file it can be read back in, decoded and applied to 

the current session. This is achieved using the session_decode() function: 

<?php session_start();?><html><head></head><body><?php

$filehandle = fopen ('/tmp/php_session.txt', 'r'); // open file containing session data

$sessiondata = fread ($filehandle, 4096); // read the session data from file

fclose ($filehandle);

session_decode($sessiondata); // Decode the session data

print_r($sessiondata); // Display the session data?></body></head>

20. PHP Object Oriented ProgrammingPHP provides extensive support for developing object­oriented web applications. The area of 

object oriented programming is, however, large. Entire books can, and indeed have, been dedicated to the subject. As such, a detailed overview of object oriented software development is beyond the scope of PHP Essentials. Instead we will introduce the basic concepts involved in object oriented programming and then move on to explaining the concept as it relates to PHP development. 

Page 86: PHP Essentials

PHP Essentials 86

What is an Object? 

An object is a self­contained piece of functionality that can be easily used, and re­used as the building blocks for a software application. 

Objects consist of data variables and functions (called methods) that can be accessed and called on the object to perform tasks. These are collectively referred to as members. 

What is a Class? Much as a blueprint or architect's drawing defines what an item or a building will look like 

once it has been constructed, a class defines what an object will look like when it is created. It defines, for example, what the methods will do and what the member variables will be. 

How is an Object Created from a Class? The process of creating an object from the class 'blueprint' is called instantiation. Essentially, 

you instantiate an instance of the class and give that instance a name by which you will refer to it when accessing members and calling methods. You can create as many object instances of a class as you desire. Objects are instantiated using the new keyword. For example, to create an instance of a class called bankAccount we would write: 

$accountObject = new bankAccount();

In the above example we now have an object called $accountObjhect of type bankAccount. 

What is sub­classing?It is possible to build classes that are derived from other classes, extending the functionality 

of the parent class to make it specific to a particular requirement. For example you might have a vehicle class which contains the attributes common to all vehicles, and a subclass called car which inherits all the generic vehicle attributes but adds some its own car specific methods and properties. 

Defining a PHP Class Before an object can be instantiated we first need to define the class 'blueprint' for the object. 

Classes are defined using the class keyword followed by braces which will be used to enclose the body of the class: 

<?phpclass bankAccount {}?>

We have now defined a class. The next step is add some functionality to the class. 

Page 87: PHP Essentials

PHP Essentials 87

PHP Class Constructors and Destructors The next step in creating a class is to define what should happen when an object is first 

instantiated using the class, and also when that object is later destroyed. These actions are defined in the constructor and destructor methods of the class. 

The constructor and destructor are really just functions that get called when the object is created and destroyed and are defined in the class body using the function keyword. This needs to be prefixed with the public qualifier. This means the method is accessible to code outside of the object. The default names for the constructor and destructor are  __construct  and  __destruct  respectively. Both methods can take arguments to be used in initializing the object. These are declared in the same way arguments are defined in any function (see PHP Functions for details). 

We can now extend our bankAccount class to include a constructor and destructor: 

<?phpclass bankAccount {

public function __construct($accountNumber, $accountName) { echo 'Object was just instantiated. Number = $accountNumber, Name = $accountName <br>'; }

public function __destruct() { echo 'Object was just destroyed <br>'; }

}?>

When the example is loaded into a browser we should get the following output: 

Object was just instantiated. Number = 123456, Name = Gregory HouseObject was just destroyed 

Creating Members in a PHP Class Class members are essentially variables and methods embedded into the class. Members can be public or private and static or variable. 

public  members  can be accessed from outside   the object.  private  members  can  only be accessed by methods contained in the class. This is the key to what is called  data encapsulation. Object­oriented programming convention dictates that data should be encapsulated in the class and accessed and set only through the methods of the class (typically called getters and setters). 

Members declared as  static  are  immutable,   in that once defined they cannot be changed (much like constants). Members and functions are prefixed with  public,  private  and  static  when declared in the class. The default is public non­static. 

We can now extend out bankAccount class to add member variables to hold the account name and number passed into the constructor. True to the concept of data encapsulation we will be creating methods to access these values later, so will mark them as private. We will also add to our constructor to assign the passed arguments to our new members. When doing so we need to use the $this variable to tell PHP we are setting variables in the current class: 

Page 88: PHP Essentials

PHP Essentials 88

<?phpclass bankAccount {

private $accountNumber; private $accountname;

public function __construct($acctNumber, $acctName) { $this->accountNumber = $acctNumber; $this->accountname = $acctName; }

public function __destruct() { echo 'Object was just destroyed <br>'; }

} $myObj = new bankAccount('123456', 'Gregory House');?>

The next task is to define methods that will give us access to our data.

Defining and Calling Methods We define our own methods in much the same way as we declared the constructor and destructor methods with exception that we get to choose the names. 

To demonstrate this we will add to our class to provide methods to get and set the account number and name: 

<?phpclass bankAccount {

private $accountNumber; private $accountname;

public function __construct($acctNumber, $acctName) { $this->accountNumber = $acctNumber; $this->accountname = $acctName; }

public function __destruct() { echo 'Object was just destroyed <br>'; }

public function setAccountNumber($acctNumber) { $this->accountNumber = $acctNumber; }

public function setAccountName($acctName) { $this->accountName = $acctName; }

public function getAccountName() {

Page 89: PHP Essentials

PHP Essentials 89

return $this->accountName; }

public function getAccountNumber() { return $this->accountNumber; }

}?>

Now that we have defined our getter and setter methods to get and set the account values we can call the methods. This is done by specifying the name of the object on which the methods are being called. This is followed by '­>', and then the name of the method we are calling (including the parentheses containing any arguments required): 

<?phpclass bankAccount {

private $accountNumber; private $accountname;

public function __construct($acctNumber, $acctName) { $this->accountNumber = $acctNumber; $this->accountname = $acctName; }

public function __destruct() { }

public function setAccountNumber($acctNumber) { $this->accountNumber = $acctNumber; }

public function setAccountName($acctName) { $this->accountName = $acctName; }

public function getAccountName() { return $this->accountName; }

public function getAccountNumber() { return $this->accountNumber; }

} $myObj = new bankAccount('123456', 'Gregory House');

$myObj->setAccountNumber('654321');

$accountNumber = $myObj->getAccountNumber();

Page 90: PHP Essentials

PHP Essentials 90

echo "New Account Number is $accountNumber";

?>

The above example sets the account name and number when instantiating the object. It then calls the setAccountNumber()  method of  the object  to change the account number,  followed by a call   to getAccountNumber (to verify the change), thereby producing the following output: 

New Account Number is 654321

Subclassing in PHP Once a class has been defined it is possible to create a new class derived from it that extends 

the functionality of the original class. The parent class is called the  superclass  and the child the subclass. The whole process is referred to as subclassing. 

A subclass of a class can be defined using the extends keyword when declaring the subclass. For example we might choose to create a subclass of our bankAccount class called savingsAccount which defines an interest bearing type of account: 

<?phpclass savingsAccount extends bankAccount {

private $interestRate = 5;

}

The important point to note here is that savingsAccount inherits all the members and methods of bankAccount and adds a new member (the interest rate). 

We can extend the class further by adding a new method to return the interest rate: 

<?phpclass bankAccount {

private $accountNumber; private $accountname;

public function __construct($acctNumber, $acctName) { $this->accountNumber = $acctNumber; $this->accountname = $acctName; }

public function __destruct() { }

public function setAccountNumber($acctNumber) { $this->accountNumber = $acctNumber; }

public function setAccountName($acctName) { $this->accountName = $acctName;

Page 91: PHP Essentials

PHP Essentials 91

}

public function getAccountName() { return $this->accountName; }

public function getAccountNumber() { return $this->accountNumber; }

}

class savingsAccount extends bankAccount {

private $interestRate = 5;

public function getInterestRate() { return $this->interestRate; }

}

$mySaveObj = new savingsAccount('246810', 'Morgan Freeman');

echo "Savings Account Number is " . $mySaveObj->getAccountNumber() . '<br>';

echo "Interest Rate = " . $mySaveObj->getInterestRate() . '<br>';?>

PHP Object Serialization One  of   the   interesting   features  of  object  oriented  programming   is   the   ability   to   take  a 

snapshot of the current state of an object and then save that object to a file, or even transmit it over a network  to  another  process  where   it  will  be   re­activated.  This  concept   is  known  in   the  object oriented world as object serialization. 

All objects have built­in method called __sleep that is called before serialization. If you need your object to perform any housekeeping before being serialized you will need to override this method. 

An object is serialized using the  serialize()  function and unserialized, not surprisingly, using the unserialize() function. As an example we can serialize our bankAccount object: 

<?phpclass bankAccount {

private $accountNumber; private $accountname;

public function __construct($acctNumber, $acctName) { $this->accountNumber = $acctNumber;

Page 92: PHP Essentials

PHP Essentials 92

$this->accountname = $acctName; }

public function __destruct() { }

public function setAccountNumber($acctNumber) { $this->accountNumber = $acctNumber; }

public function setAccountName($acctName) { $this->accountName = $acctName; }

public function getAccountName() { return $this->accountName; }

public function getAccountNumber() { return $this->accountNumber; }

}

$myObj = new bankAccount('246810', 'Morgan Freeman');

$serialized = serialize ($myObj);

echo 'Object is serialized<br>';

$newObj = unserialize ($serialized);

echo 'Object is unserialized<br>';

print_r ($newObj);?>

In the above example the object is serialized, then unserialized to a new object variable. We then use the print_r() function to verify the new object contains everything the old one did resulting in the following output: 

Object is serializedObject is unserializedbankAccount Object ( [accountNumber:private] => 246810 [accountname:private] => Morgan Freeman )

Once we have the serialized data in our $serialized object we can do anything we want with it, such as  write   it   to   a   file   or   send   it   through   a   network   socket   to   another   process  where   it   can  be unserialized and used. 

Page 93: PHP Essentials

PHP Essentials 93

Getting Information about a PHP Object There are number of ways to find out information about classes. 

An   array   of   classes   to   which   your   script   has   access   can   be   obtained   using   the get_declared_classes()  function. The  class_exists()  function can be passed the name of a class to find out if such a class exists. A list of methods in a class can be obtained by passing the class name through to the get_class_methods() function. 

It is also possible to find out if a class has a parent class using the get_parent_class() function which will either return the name of the parent class, or an empty string if no parent exists. 

The  method_exists()  function,   when   passed   an   object   pointer   and   method   name   as arguments, will return a true or false value indicating the existence of the method. 

21. Using PHP with MySQLThere is a TV commercial that shows what would happen to the world if we didn't have 

plastic. In the commercial objects like telephones, chairs and computers disappear before our eyes. The objective is to make us appreciate what would happen to our infrastructure without plastic. A similar analogy can be drawn to the need for databases on the internet. Without databases many of the web sites we rely on would quickly cease to function. It is not an exaggeration to suggest that databases form the heart of the web and the internet as we know it. Without some way to store and retrieve data the usefulness of the internet would be a greatly reduced. 

One of the many advantages of PHP is the seamless way in which it integrates with the  MySQL database. In this chapter we will take a close look at how to access information stored in a MySQL database from a PHP script and present that data to a user's web browser. 

Before   beginning   it   is   important   to   note   that   MySQL   is   an   advanced   Relational   Database Management System (RDBMS), and as such, may be more sophisticated than is needed for every data storage need. In the next chapter (PHP and SQLite) we will look at a more lightweight solution that may meet less demanding needs. 

This chapter assumes that you have MySQL installed and running on your server. There are many resources  on  the  internet   that  can help you achieve this.  The first  place  to  start   is   the  MySQL documentation

Creating a MySQL User Account The first task is to create a MySQL user account we can use for the purposes of this chapter. To set up as user account you will need to log into MySQL using an account that has suitable privileges. If you are unsure about which user account to use speak to your system administrator or refer to the MySQL documentation. In this example we will assume you have the root password: 

Page 94: PHP Essentials

PHP Essentials 94

mysql -p -u rootEnter password:Welcome to the MySQL monitor. Commands end with ; or \g.Your MySQL connection id is 10411 to server version: 5.0.27

Type 'help;' or '\h' for help. Type '\c' to clear the buffer.

mysql>

Having logged into MySQL we can now create a new user called phptest. In the example below we assign the password mypassword. It is advised you use your own password in place of this one: 

mysql> GRANT ALL PRIVILEGES ON *.* TO 'phptest'@'localhost' -> IDENTIFIED BY '3579php' WITH GRANT OPTION;Query OK, 0 rows affected (0.07 sec)

We now have a user account we can use to create a sample database table and can log into MySQL using this account and password: 

$ mysql -p -u phptestEnter password:Welcome to the MySQL monitor. Commands end with ; or \g.Your MySQL connection id is 10476 to server version: 5.0.27

Type 'help;' or '\h' for help. Type '\c' to clear the buffer.

mysql>

Creating and Select MySQL Database The next step is to create a database to store the data we will use in our PHP database example. We will call the database PHPsampleDb as follows: 

mysql> CREATE DATABASE PHPsampleDB;Query OK, 1 row affected (0.00 sec)

We can then select the database using the USE command: 

mysql> USE PHPsampleDB;Database changed

Our database is now created and selected. Next we need to add a table to the database. 

Creating a MySQL Database Table For the purposes of our example we will create a very simple database table. It is going to contain just   three   fields,  a  customer  name,  email  address  and account  number.  We will  call   this   table customer and create it as follows: 

mysql> CREATE TABLE customer (name VARCHAR(30), email VARCHAR(30), -> account VARCHAR(20));

Page 95: PHP Essentials

PHP Essentials 95

Query OK, 0 rows affected (0.01 sec)

Inserting Data into a MySQL Database Table As the final step in setting our sample database we need to add some data to the table. This is achieved using the SQL INSERT command. We will add three initial rows to the table: 

mysql> INSERT INTO customer VALUES ('Gregory House', '[email protected]', '12345678');Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO customer VALUES ('Robert Chase', '[email protected]', '87654321');Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO customer VALUES ('Lisa Cuddy', '[email protected]', '24688642');Query OK, 1 row affected (0.00 sec)

We can now check that these records are set up correctly using the SELECT command: 

mysql> SELECT * FROM customer;+---------------+-----------------+----------+| name | email | account |+---------------+-----------------+----------+| Gregory House | [email protected] | 12345678 || Robert Chase | [email protected] | 87654321 || Lisa Cuddy | [email protected] | 24688642 |+---------------+-----------------+----------+3 rows in set (0.00 sec)

Connecting with PHP to a MySQL Server Now that we have set up our MySQL database and entered some data it is time to look at 

using PHP to connect to the database so that we can start to query the database and add new data. The first step in our PHP script is to connect to our MySQL database server. This is achieved using the   PHP  mysql_connect()  function.   The  mysql_connect()  function   creates   a   connection   to   the database server and returns a database resource handle. The function takes five optional arguments. The first is the address of the server hosting the database.  This defaults to  localhost:3306.  The second argument is the user name to be used to connect to the database. The third argument is the password associated with the user name. 

If a second call is made to mysql_connect() the default behavior is to return the handle from the first call. Setting the fourth argument overrides this behavior and generates a new handle. 

The final argument represents the flags for the PHP client which works in the background to connect   to   the   database.   Options   are   MYSQL_CLIENT_COMPRESS, MYSQL_CLIENT_IGNORE_SPACE and MYSQL_CLIENT_INTERACTIVE. 

To   disconnect   from   the   database   use   the  msql_close()  function   which   takes   as   a   sole argument the database resource handle returned by mysql_connect(). 

Page 96: PHP Essentials

PHP Essentials 96

We can now write a script that will connect us to our sample database (remember to modify the password to match the one you specified when creating the user account): 

<?php

$dbhandle = mysql_connect('localhost', 'phptest', '3579php');

if ($dbhandle) { echo "Connected to MySQL Database<br>"; mysql_close($dbhandle);

} else { echo "Unable to connect to MySQL Database<br>"; }

?>

Selecting Records from a MySQL Database Using PHP Now that we have connected to our MySQL database we can begin accessing the data in our 

table.   To   achieve   this   we   need   to   first   select   the   database   we   wish   to   use   by   calling   the mysql_select_db() function, passing through the database name as an argument. This will return a database handle. We then need to construct a SQL SELECT statement which we will pass to the PHP  mysql_query()  function.   This   function   takes   the   database   handle   (returned   by mysql_select_db()) and the SQL query statement as arguments. 

The  mysql_query()  function  call  places   the   results   in  an  array  which  we can  access  using   the mysql_fetch_array() function. 

Bringing this all together gives us the following: 

<?php

$dbhandle = mysql_connect('localhost', 'phptest', '3579php');

if ($dbhandle == false) { die ("Unable to connect to MySQL Database<br>"); }

$db = mysql_select_db('PHPsampleDB');

if ($db == false) { die ("Unable to Select MySQL Database<br>"); }

$dbquery = 'SELECT * FROM customer';

$dbresult = mysql_query ($dbquery, $dbhandle);

Page 97: PHP Essentials

PHP Essentials 97

if ($dbresult == false) { die ("Unable to to perform query<br>"); }

while ($dbrow = mysql_fetch_array($dbresult, MYSQL_ASSOC)) { print_r($dbrow); echo '<br>'; }

mysql_close($dbhandle);?>

When loaded into a browser the following output will be generated: 

Array ( [name] => Gregory House [email] => [email protected] [account] => 12345678 )Array ( [name] => Robert Chase [email] => [email protected] [account] => 87654321 )Array ( [name] => Lisa Cuddy [email] => [email protected] [account] => 24688642 ) 

Another way to fetch the data as an associative array see PHP Arrays) is to use the mysql_fetch_assoc(). We could, therefore, modify our while loop as follows: 

while ($dbrow = mysql_fetch_assoc($dbresult)) { print_r($dbrow); echo '<br>'; }

Adding Records to MySQL Database using PHP To add records to a database using PHP we simply need to construct a new query string using the SQL INSERT command and execute it using the mysql_query() function: 

<?php

$dbhandle = mysql_connect('localhost', 'phptest', '3579php');

if ($dbhandle == false) { die ("Unable to connect to MySQL Database<br>"); }

$db = mysql_select_db('PHPsampleDB');

if ($db == false) { die ("Unable to Select MySQL Database<br>"); } $dbquery = "INSERT INTO customer VALUES ('James Wilson', '[email protected]', '00001111')";

$dbresult = mysql_query ($dbquery, $dbhandle);

if ($dbresult == false)

Page 98: PHP Essentials

PHP Essentials 98

{ die ("Unable to add record<br>"); }

$dbquery = "SELECT * FROM customer WHERE name = 'James Wilson'";

$dbresult = mysql_query ($dbquery, $dbhandle);

if ($dbresult == false) { die ("Unable to perform query<br>"); }

while ($dbrow = mysql_fetch_Array($dbresult, MYSQL_ASSOC)) { print_r($dbrow); echo '<br>'; }?>

The above script will result in the following output:

Array ( [name] => James Wilson [email] => [email protected] [account] => 00001111 ) 

Modifying and Deleting MySQL Records using PHP Record can be similarly modified and deleted by constructing appropriate SQL DELETE 

and   UPDATE   commands   and   passing   them   through   to   the  mysql_query()  function.   After   the function has been called the mysql_affected_rows() function can be called to identify the number of rows affected by the change. mysql_affected_rows() accepts a single argument, the handle returned by the mysql_connect() function.

Using PHP to get Information about a MySQL Database PHP provides   a  number  of   useful   functions   for  obtaining   information  about   a  MySQL 

database. It is possible to obtain a list of fields in a table using the mysql_list_fields() function. This function accepts three arguments, the database name, the table name and database handle returned by mysql_connect(). 

The number of fields in a table can be obtained using the mysql_num_fields() function. This function takes the resource identifier returned by mysql_list_fields() as an argument. 

Once   you   have   obtained   the   resource   identifier   from  mysql_list_fields()  you   can   use mysql_field_name(),  mysql_field_type(), and  mysql_field_len()  functions to get information about each   field.   All   of   these   functions   take   the   handle   returned   by  mysql_list_fields()  as   the   first argument and offset into the table of the field you wish to inspect. A for  loop can be constructed using the result from mysql_num_fields() to iterate through all fields as follows: 

<?php

$dbhandle = mysql_connect('localhost', 'phptest', '3579php');

if ($dbhandle == false)

Page 99: PHP Essentials

PHP Essentials 99

{ die ("Unable to connect to MySQL Database<br>"); }

$db = mysql_select_db('PHPsampleDB');

if ($db == false) { die ("Unable to Select MySQL Database<br>"); }

$listhandle = mysql_list_fields ('PHPsampleDB', 'customer', $dbhandle);

$numfields = mysql_num_fields ($listhandle);

for ($i=0; $i<$numfields; $i++) { echo 'Name: ' . mysql_field_name($listhandle, $i) . '<br>'; echo 'Type: ' . mysql_field_type($listhandle, $i) . '<br>'; echo 'Length: ' . mysql_field_len($listhandle, $i) . '<br>'; }

?>

When loaded into a browser the above example will generate the following output: 

Name: name Type: string Length: 30Name: email Type: string Length: 30Name: account Type: string Length: 20

22. PHP and SQLite

Creating an SQLite Database with PHP

An SQLite database can be opened or created using the PHP  sqlite_open()  function. This function accepts one mandatory and two optional arguments. The first argument is the database name  (which,   by  convention,   is   given   a   .sqlite   file   extension).  The   second  argument   specifies optional UNIX file permission settings. The final argument represents an error message to display if the file cannot be opened.

The sqlite_open() function returns a database handle on success, or a boolean false value on failure. A memory resident database can be created by passing in the string :memory as the database file name argument. 

SQLite databases are closed using the sqlite_close() function. 

The following example opens a database called phptest.sqlite: 

Page 100: PHP Essentials

PHP Essentials 100

<?php $dbhandle = sqlite_open('phptest.sqlite');

if ($dbhandle == false) { die ('Unable to open database'); } else { echo 'Database created.'; } sqlite_close($dbhandle)?>

Using PHP to Add Records to an SQLite Database Records   are   added   to   a   SQLite   database   using   the   PHP  sqlite_query()  function.   The 

''sqlite_query()  function  takes   two arguments,   the first  being  the handle  returned by  the call   to sqlite_open() and the second representing the SQL command to run on the database. Records are added using the SQL insert command: 

<?php $dbhandle = sqlite_open('phptest.sqlite');

if ($dbhandle == false) { die ('Unable to open database'); } else { echo 'Database created.'; }

$dbquery = 'INSERT INTO customer (name, account) VALUES ("James Wilson", "12345678")';

$dbresult = sqlite_query($dbhandle, $dbquery);

sqlite_close($dbhandle)?>

Using PHP to Select Records from an SQLite Database As with adding records, selecting records simply consists of constructing a suitable SQL 

SELECT statement and passing it through to the sqlite_query() function: 

<?php $dbhandle = sqlite_open('phptest.sqlite');

if ($dbhandle == false) { die ('Unable to open database'); } else { echo 'Database created.'; }

Page 101: PHP Essentials

PHP Essentials 101

$dbquery = 'SELECT * FROM customer;

$dbresult = sqlite_query($dbhandle, $dbquery);

sqlite_close($dbhandle)?>

The  sqlite_query()  function returns all the selected records. These can be extracted as an array of arrays using the sqlite_fetch_all() function which takes the handle returned from the query as an argument. Whilst this approach is fine for small amounts of data it tends to be inefficient when dealing with large data sets. It is preferable, in these circumstances, to use the sqlite_fetch_single() function in conjunction with the sqlite_has_more() function as follows: 

<?php $dbhandle = sqlite_open('phptest.sqlite');

if ($dbhandle == false) { die ('Unable to open database'); } else { echo 'Database created.'; }

$dbquery = 'SELECT * FROM customer;

$dbresult = sqlite_query($dbhandle, $dbquery);

while (sqlite_has_more($dbresult)) { $dbrow = sqlite_fetch_single($dbquery); print_r ($dbrow); }

sqlite_close($dbhandle)?>

Page 102: PHP Essentials

PHP Essentials 102