Lesson 07 PHP
Lesson 07 PHP
Learning outcomes:
After completing lesson 7, you will be able to explain basics such as syntax, data types
and operators of the PHP programming language. In addition to that you will be able to
use files, sessions and cookies. Further you will be able to use PHP programming to
solve small day to day programming problems. In addition to that you will be able to
describe Object Oriented Programming in PHP.
7.1 Introduction
PHP is one of the most popular web development languages written by and for Web
developers. PHP stands for PHP: Hypertext Preprocessor. It is open source and
currently in its fifth major rewrite, called PHP5 or just plain PHP.
PHP can be used on all major operating systems, including Linux, Unix, Microsoft
Windows and Mac OS X. PHP also has support for most of the web servers such as
Apache, Microsoft Internet Information Server (IIS), Personal Web Server, Netscape
and iPlanet servers. Further, it can work with a wide range of databases such as
Oracle, Microsoft SQL Server, MySQL, SQLite and IBM DB2.
This lesson will focus on using PHP with the Apache Web server on Windows, but you
can just as easily use PHP with any other supporting web server and platform. Detailed
instructions on how to set up this development environment were given in Lesson 05.
<?php
PHP Code In Here
php?>
<script language="php">
PHP Code In Here
</script>
<html>
<head>
<title>PHP Hello World</title>
</head>
<body>
<?php echo '<p>Hello World</p>'; ?>
</body>
</html>
Example 7.1
Create a file named helloworld.php and put it in your web server's root directory
(DOCUMENT_ROOT) with the above listing. Use your browser to access the file with
your web server's URL, ending with the /helloworld.php file reference. If you are
browsing from the same computer that you used to installed the server the URL will be
of the form http://localhost/helloworld.php. If your server computer is connected to a
network, you can open the browser on a different computer and direct it to the URL
http://hostname/helloworld.php , where hostname is the name of your server computer.
When you requested the above script your Web server intercepted your request and
handed it off to PHP. PHP then parsed the script, executing the code between the
<?php...?> marks and then replacing it with the output of the executed code. The result
was then handed back to the server and transmitted to the client. Since the output
contained valid HTML, the browser was able to render it for display to the user.
Example 7.2
The phpinfo() function gives information about the current state of PHP. This includes
information about PHP compilation options and extensions, the PHP version, server
information and environment, the PHP environment, OS version information, paths,
master and local values of configuration options, HTTP headers, and the PHP License.
This function is useful for checking the configuration settings and the predefined
variables on a given system as well as a debugging tool since it contains all EGPCS
(Environment, GET, POST, Cookie, Server) data. Construct the code to make a call to
the phpinfo() function.
Answer
<html>
<head>
<title>PHP Info</title>
</head>
<body>
<?php phpinfo(); ?>
</body>
</html>
7.2.3 Separating statements within a PHP block
Every PHP statement ends with a semicolon. However, you do not need to have a
semicolon terminating the last line of a PHP block since the closing tag of a block of
PHP code implies a semicolon.
<?php
echo 'This is a test';
?>
/*
This is a multiple line comment.
None of this will
be parsed by the
PHP engine
*/
7.2.5 Variables
A variable can be defined as a programming construct used to store both numeric and
non-numeric data where the contents of a variable can be altered during program
execution.
Variables in PHP are case sensitive and are represented by a dollar sign followed by
the name of the variable. The name of the variable should start with either a letter or an
underscore and can optionally be followed by more letters, numbers and underscores.
For example $emp_name and $_mobile1 are valid PHP variable names while $123 and
$1st_name are not.
7.2.6 Types
PHP supports 8 primitive data types, which consists of four scalar types, two compound
types and two special types.
7.2.7 Constants
If you want to work with a value that you do not want to alter throughout your script's
execution, you can define a constant. A valid constant name starts with a letter or
underscore, followed by any number of letters, numbers, or underscores. You must use
PHP's built-in function define() to create a constant as given below.
<?php
define ("USER", "Piumi");
print "Welcome ".USER;
?>
7.2.8 Operators
Operators are symbols that enable you to use one or more values to produce a new
value. A value that is operated on by an operator is referred to as an operand. PHP
supports various types of operators as listed below.
Syntax
if(expression){
//Code to execute if the expression evaluates to true
}
Example 7.3
The following listing will printout Have a nice weekend! if the current day is Friday.
<html>
<body>
<?php
$d=date("D");
if ($d=="Fri")
echo "Have a nice weekend!";
?>
</body>
</html>
7.3.1.2 The if.... else Statement
Syntax
if(expression){
//Code to execute if the expression evaluates to true
}else{
//Code to execute in all other cases
}
Example 7.4
The following listing will printout Have a nice weekend! if the current day is Friday and
Have a nice day! if it is any other day
<html>
<body>
<?php
$d=date("D");
if ($d=="Fri")
echo "Have a nice weekend!";
else
echo "Have a nice day!";
?>
</body>
</html>
Syntax
if(expression 1){
//Code to execute if the expression 1 evaluates to true
}else if(expression 2){
//Code to execute if the expression 1 failed
//And expression 2 evaluated to true
}else{
//Code to execute in all other cases
}
Example 7.5
The following listing will printout Have a nice weekend! if the current day is Friday,
Have a nice Sunday! if the current day is a Sunday and Have a nice day! if it is any
other day.
<html>
<body>
<?php
$d=date("D");
if ($d=="Fri")
echo "Have a nice weekend!";
elseif ($d=="Sun")
echo "Have a nice Sunday!";
else
echo "Have a nice day!";
?>
</body>
</html>
Syntax
while(expression){
//Code to executed
}
Example 7.6
The following listing will printout the list of first 10 odd numbers using a while loop.
<html>
<body>
<?php
$val=0;
while ($val < 10){
print ($val*2) . "<br />";
$val++;
}
?>
</body>
</html>
Syntax
do{
//Code to executed
} while(expression);
Note that the expression always ends with a semicolon
Example 7.7
The following listing will printout the integers less than 10 starting from $val. However
since in the given listing $val is initially assigned to 10, it will print out the message
Starting value is larger than or equal to 10" and exit.
<html>
<body>
<?php
$val=10;
do{
if($val >=10)
print "Starting value is larger than or equal to 10";
else
{
print ($val) . "<br />";
$val++;
}
}while ($val < 10);
?>
</body>
</html>
7.3.2.3 The for Statement
Syntax
The initialization expression is evaluated once at the start of the execution of the for
loop. The test expression is evaluated in the beginning of each iteration is evaluated. If
it evaluates to TRUE, the loop continues and the code within the loop is executed. If it
evaluates to FALSE, the execution of the loop ends. The modification expression is
evaluated, at the end of each iteration.
Example 7.8
The following listing will printout the list of first 10 odd numbers using a for loop.
<html>
<body>
<?php
for($val=0;$val<10;$val++){
print ($val*2) . "<br />";
}
?>
</body>
</html>
Syntax
switch (expression) {
case result1:
// execute this if expression results in result1
break;
case result2:
// execute this if expression results in result2
break;
default:
// execute this if no break statement
// has been encountered hitherto
}
The switch statement's expression is often simply a variable. Within the switch
statement's block of code, you find a number of case statements. Each of these tests a
value against the result of the switch statement's expression. If these are equivalent, the
code after the case statement is executed. The break statement ends execution of the
switch statement altogether. If this is omitted, the next case statement's expression is
evaluated. If the optional default statement is reached, its code is executed.
Example 7.9
The following listing will print out the day if it is a Saturday or a Sunday or will print out
Today is a working day. if the day is a week day.
<html>
<body>
<?php
$d=date("D");
switch ($d)
{
case "Sat":
echo "Today is Saturday";
break;
case "Sun":
echo "Today is Sunday";
break;
default:
echo "Today is a working day.";
}
The $_GET variable is used to collect values from a form with method="get" while the
$_POST variable is used to collect values from a form with method="post".
Example 7.10
This example contains two scripts, one containing an HTML form (input.html) and the
other containing the form processing logic (message.php). When the user fills in his
information in the form and clicks on the Submit button, the page message.php is
called.
input.html
<html>
<head></head>`
<body>
<form action="message.php" method="post">
<p>Enter your name : <input type="text" name="name" size="30"></p>
<p>Enter message: <input type="text" name="msg" size="30"></p>
<p><input type="submit" value="Send"></p>
</form>
</body>
</html>
Note that the "action" attribute of the <form> tag specifies the name of the server-side
script (message.php in this case) that will process the information entered into the form.
The "method" attribute specifies how the information will be passed.
Whenever a form is submitted to a PHP script, with the post method, all variable-value
pairs within that form automatically become available for use within the script, through
the PHP container variable: $_POST. You can then access the value of the form
variable by using its "name" inside the $_POST container
message.php
<html>
<head></head>
<body>
<?php
// retrieve form data
$name = $_POST['name'];
$input = $_POST['msg'];
// use it
echo "Hello $name</br>";
The outputecho
will be similar
"You saidto:the following
<i>$input</i></br>";
?>
</body>
Hello Nimal
</html>
You said: I love PHP
Sessions and cookies thus provide an elegant way to bypass the stateless nature of the
HTTP protocol, and are used on many of today's largest sites to track and maintain
information for personal and commercial transactions. Typically, sessions are used to
store values that are required over the course of a single visit, and cookies to store
more persistent data that is used over multiple visits.
PHP has included support for cookies and has built-in session management which is
enabled by default, so you don't have to do anything special to activate them.
7.5.1 Sessions
Every session has a unique session ID, which PHP uses to keep track of different
clients. This session ID is a long alphanumeric string, which is automatically passed by
PHP from page to page so that the continuity of the session is maintained. The session
will end when the user shuts down the client browser or when the session is explicitly
destroyed as discussed below in section 7.5.1.4.
After a session has been started, you instantly have access to the user's session ID via
the session_id() function. session_id() allows you to either set or get a session ID.
Example 7.11
The following listing will register the users session with the server and print out the
session ID.
<?php
session_start(); //Start the session
?>
<html>
<body>
<?php
echo "Welcome, your session ID is ". session_id();//print session ID
?>
</body>
</html>
When this?> script is run for the first time from a browser, a session ID is generated by the
session_start().
</body> If the page is later reloaded or revisited, the same session ID is
allocated</html>
to the user. This presupposes, of course, that the user has cookies enabled
on his browser.
You can set any number of variables as elements of the superglobal $_SESSION array.
After these are set, they are available to future requests in the session.
Example 7.12
The following example has two pages. In the first page two products are registered.
These products are accessed in the second page by the use of session variables
<?php
session_start(); //Start the session
?>
<html>
<body>
<?php
$_SESSION['product1'] = "Sugar";
$_SESSION['product2'] = "Milk";
print "The products have been registered";
?>
</body>
</html>
<?php
session_start(); //Start the session
?>
<html>
<body>
<?php
print "You have chosen the products are:\n\n";
?>
<ul>
<li><?php print $_SESSION['product1'] ?></li>
<li><?php print $_SESSION['product2'] ?></li>
</body>
</html>
<?php
unset($_SESSION['product1']);
\ ?>
7.5.1.4 Deleting Session Variables
The session_destroy() function can used to completely destroy a session.
<?php
session_destroy();
?>
7.5.2 Cookies
A session works by using an in-memory cookie, which explains why it's only active while
the browser instance that created it is active; once the browser instance is terminated,
the memory allocated to that instance is flushed and returned to the system, destroying
the session cookie in the process. If you want longer-lasting cookies, you can use
PHP's built-in cookie functions to write data to the user's disk as a cookie file, and read
this data back as and when needed.
Cookies are used to record information about your activities on a particular domain,
therefore they can only be read by the domain that created them. Further a single
domain cannot set more than twenty cookies, and the maximum size of a cookie is 4
KB.
A cookie usually possesses six attributes as given below of which only the name
attribute is mandatory.
name: the name of the cookie
value: the value of the cookie
expires: the date and time at which the cookie expires
path: the top-level directory on the domain from which cookie data can be
accessed
domain: the domain for which the cookie is valid
secure: a Boolean flag indicating whether the cookie should be transmitted only
over a secure HTTP connection
Example 7.13
The following listing will create a cookie named "user", assign the value "Nimal Perera"
to it and specify that it will expire in one hour.
<?php
setcookie("user", "Nimal Perera", time()+3600);
?>
7.5.2.2 Accessing the value of a cookie
A values of a cookie can be accessed with the PHP $_COOKIE variable.
Example 7.14
The following listing displays how to first check if the cookie named user has been set
and then to retrieve the value of the cookie.
<html>
<body>
<?php
if (isset($_COOKIE["user"]))
echo "Welcome " . $_COOKIE["user"] . "!<br />";
else
echo "Welcome guest!<br />";
?>
</body>
</html>
Example 7.15
The following listing displays how to delete a cookie by setting its expiration value to an
hour ago.
<?php
// set the expiration date to one hour ago
setcookie("user", "", time()-3600);
?>
There are three basic modes for use with the fopen() function as given below;
'r' - opens a file in read mode
'w' - opens a file in write mode, destroying existing file contents
'a' - opens a file in append mode, preserving existing file contents
Example 7.16
The following listing displays how open the file hello.txt
<html>
<body>
<?php
$file=fopen("welcome.txt","r");
?>
</body>
</html>
Example 7.17
The following listing displays how open and then close the file hello.txt
<html>
<body>
<?php
$file = fopen("hello.txt","r");
//some code to be executed
fclose($file);
?>
</body>
</html>
The feof() function which checks if the end of file has been reached comes in handy
when reading files.
Example 7.18
The following listing displays how to read a file to line by line until the end of file has
been reached.
<?php
$file = fopen("welcome.txt", "r") or exit("Unable to open file!");
//Output a line of the file until the end is reached
while(!feof($file))
{
echo fgets($file). "<br />";
}
fclose($file);
?>
Example 7.19
The following listing displays how to read a file to character by charactor until the end of
file has been reached.
<?php
$file=fopen("welcome.txt","r") or exit("Unable to open file!");
while (!feof($file))
{
echo fgetc($file);
}
fclose($file);
?>
One of the greatest advantages of object-oriented code is its reusability. Because the
classes used to create objects are self-enclosed, they can be easily pulled from one
project and used in another. Additionally, it is possible to create child classes that inherit
and override the characteristics of their parents. This technique can allow you to create
progressively more complex and specialized objects that can draw on base functionality
while adding more of their own.
The specific instances of a class are referred to as objects. Every object has certain
characteristics, or properties, and certain pre-defined functions, or methods.
By defining a class, you lay down a set of characteristics. By creating objects of that
type, you create entities that share these characteristics but might initialize them as
different values.
Example 7.20
The following code listing creates a class named Account. This file will be saved as
MyAccount.php.
<?php
class MyAccount {
var $name;
var $account;
var $balance;
//The constructor
function MyAccount ($name, $account, $balance) {
$this->name = $name;
$this->account = $account;
$this->balance = $balance;
}
function getName() {
return $this->name;
}
function getBalance() {
return $this->balance;
}
function getAccount() {
return $this->account;
}
The class MyAccount has 3 variables, $name, $account and $balance and several
functions that can be used to change the state of the class.
There is also a special function the constructor, which has the same name as the class,
and is used to initialize the variables when your class is instantiated.
Example 7.21
The following code listing will create objects from the class that was defined above and
call its functions and adjust the properties of each class. This file will be saved as
AccountTest.php.
<?php
include_once("MyAccount.php");
$account1->withdrawCash (100);
echo ("Withdrew Rs 100. ");
echo ("Balance = Rs " . $account1->getBalance() . "<br>");
$account1->depositCash (500);
echo ("Deposited Rs 500. ");
echo ("Balance = Rs" . $account1->getBalance() . "<br><br><br>");
$account2->withdrawCash (250);
echo ("Withdrew Rs 250. ");
echo ("Balance = Rs " . $account2->getBalance() . "<br>");
$account2->depositCash (1000);
echo ("Deposited Rs 1000. ");
echo ("Balance = Rs" . $account2->getBalance() . "<br>");
?>
Now, save the script and execute it from your web browser. You should see the
following output.
7.8 Summary
In this lesson you learnt about the server side scripting language PHP. You learnt the
basic language constructs, file and form handling, session management and object
oriented programming in PHP.