Chapter 4
Chapter 4
(CoSc3031)
Internet Programming
(Server Side Scripting )Using PHP
1 Internet Programming
Web Engineering –Server Side Technology
Web Engineering aims to bring Web-based system
development under control, minimize risks and improve
quality, maintainability, and scalability of Web applications.
Web Engineering incorporate technology like client and
server sides.
Server Side Technology used to build and develop Web
Systems and Applications which helps to interact with more
than two tiers.
2 Internet Programming
Overview of Server Side Technologies
Scripts (programs) are stored on the server and are
executed on request (from a client).
Result of execution is sent to the client in the form of
HTML.
The server side script/program itself is never returned to
the client!
My be written in a wide variety of programming/scripting
languages.
php, asp, c/c++, perl, java, …
Can perform several powerful operations.
3 Internet Programming
Server-Side Scripting
5 Internet Programming
Server-Side Scripting (cont’d)
6 Internet Programming
Introduction to PHP
7 Internet Programming
PHP features
A server side scripting interpreted language
Open source(Free!)
Fairly easy but quite powerful!
Can be embedded within HTML code
Object Orientation supported
Supports (almost) all major databases
Run Faster
8 Internet Programming
PHP – Language Basics
Syntax
PHP code should enclosed within:
<?php and ?>
So that it is distinguished from HTML.
Hence, the PHP parser only parses code which is in between <?
php and ?>
PHP code can be embedded in HTML
Example:
<p>This is going to be ignored.</p>
<?php echo 'While this is going to be parsed.'; ?>
<p>This will also be ignored.</p>
9 Internet Programming
Language Basics (cont’d)
10 Internet Programming
Data types
Boolean (bool or boolean)
Simplest of all
Can be either TRUE or FALSE
Integer (int or integer)
Hold integer values (signed or unsigned)
Floating point (float or double or real)
Hold floating point values
String (string)
Hold strings of characters within either ‘ or ‘’
Escaping of special characters can be done using \
Ex. “this is a string”, ‘this is another string’, “yet \”another\”
one”
11 Internet Programming
Data types (cont’d)
Array
Collection of values of the same data type
Object
Instance of a class
Resource
Hold a reference to an external resource created by some functions
NULL
Represents that a variable has no value
A variable is considered to be NULL if
it has been assigned the constant NULL.
it has not been set to any value yet.
it has been unset()
12 Internet Programming
Variables
Variables in PHP are represented by a dollar sign followed
by the name of the variable.
The variable name is case-sensitive.
A valid variable name starts with a letter or underscore,
followed by any number of letters, numbers, or underscores.
PHP is not strongly typed
No variable declaration ( implicit )
To create a variable, just assign some value to it!
Example:
$myNum = 5; //declares and assignes 5 to the variable $myNum
13 Internet Programming
Variables (cont’d)
Example
<?php
$var = 'Bob';
$Var = 'Joe';
echo "$var, $Var"; // outputs "Bob, Joe"
$4site = 'not yet'; // invalid; starts with a number
$_4site = 'not yet'; //valid; starts with an underscore
$täyte = 'mansikka'; // valid; 'ä' is (Extended) ASCII 228.
?>
14 Internet Programming
Variables (cont’d)
Referencing
15 Internet Programming
Variables (cont’d)
Variables within double quoted strings (“”) are parsed
Example
$name = “Abebe”;
$message = “Hello $name”;
echo $message; //Hello Abebe
16 Internet Programming
Variables (cont’d)
Array variables
Can be created using the array() construct.
Syntax: array( [ key => ] value, … )
key : can be an integer or a string
value : can be any value
Example
<?php
$arr = array( "foo", "bar” );
17 Internet Programming
Variables (cont’d)
Example
<?php
$arr = array("foo" => "bar", 12 => true);
18 Internet Programming
Variables (cont’d)
The value in an array can be anything (even an array)
Example
<?php
$arr = array("somearray" => array(6 => 5, 13 => 9, "a" => 42));
19 Internet Programming
Variables (cont’d)
If you do not specify a key for a given value, then the maximum of the
integer indices is taken, and the new key will be that maximum value +
1.
If no integer indices exist yet, the key will be 0 (zero).
If you specify a key that already has a value assigned to it, that value
will be overwritten.
Example
<?php
// This array is the same as ...
array(5 => 43, 32, 56, "b" => 12);
// ...this array
array(5 => 43, 6 => 32, 7 => 56, "b" => 12);
?>
20 Internet Programming
Variables (cont’d)
Creating/modifying with square-bracket syntax
You can also modify an existing array by explicitly setting values
in it
Syntax:
$arr[key] = value;
$arr[] = value;
// key may be an integer or string
// value may be any value
If $arr doesn't exist yet, it will be created
To change a certain value, just assign a new value to an element
specified with its key.
If you want to remove a key/value pair, you need to unset() it
21 Internet Programming
Variables (cont’d)
Example
<?php
$arr = array(5 => 1, 12 => 2);
$arr["x"] = 42; // adds a new element to the array with key "x"
unset($arr[5]); // removes the element from the array
22 Internet Programming
Variables (cont’d)
To print the content of an array, use the print_r() function.
Syntax: print_r($arr);
Example
<?php
$array = array(1, 2, 3, 4, 5);
print_r($array);
?>
Output: Array ( [0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
23 Internet Programming
Variables (cont’d)
Strings
Three types of string literals
Single quoted
$str1 = ‘some string’;
Double quoted
$str2 = “some other string”;
Heredoc
$str3 = <<<EOD
Example of string
spanning multiple lines
using heredoc syntax.
EOD;
24 Internet Programming
Variables (cont’d)
Character escaping
If the string is enclosed in double-quotes ("), PHP understands
more escape sequences for special characters:
sequence meaning
\n linefeed
\r carriage return
\t horizontal tab
\\ backslash
\$ dollar sign
\" double-quote
25 Internet Programming
Variables (cont’d)
Variable parsing
variables within double quoted strings are parsed.
Example
<?php
$soft_drink = ‘coka';
echo "$soft_drink's taste is great"; // works
echo "He drank some $soft_drinks"; // won't work
echo "He drank some ${soft_drink}s"; // works
echo "He drank some {$soft_drink}s"; // works
?>
26 Internet Programming
Variables (cont’d)
String concatenation
Use the . (dot) operator
Example
<?php
$var1 = “Today is “;
$message = $var1 . date(“d-m-Y”); //Today is 28-12-2007
?>
Indexing strings
$str[index]
String index starts with 0 (similar to arrays)
For a list of string related functions, refer to the Official PHP
Reference Manual
27 Internet Programming
Output statements
Types of output: echo, print
Using the function echo
Syntax: echo $var or echo string_constant
Using short tags
Syntax: <?= $var ?>
Using heredoc
Syntax:
echo <<<LABEL
….
LABEL;
* LABEL must be placed in the first column of a new line.
* Special characters, like “, need not be escaped
28 Internet Programming
Input
Input to server side scripts comes from clients through
forms.
Two methods of sending data: GET & POST
GET
Search queries and small amounts of data
Also generated when a user clicks on a link
Non secure (displayed in address bar)
POST
Large and secure data
The default method for HTML forms is GET
29 Internet Programming
Input (cont’d)
To access form field values in PHP, use the built-in PHP
arrays: $_GET and $_POST respectively for GET and
POST request methods
The names of the form fields will be used as indices in the
respective arrays.
For example, to access the value of an input box named
‘first_name’ in a form whose method is POST, we’d
write:
$_POST[ ‘first_name’ ]
If the form method is GET,
$_GET[ ‘first_name’ ]
30 Internet Programming
Input (cont’d)
Example:
//login.html
<!DOCTYPE html>
<html>
<body>
<form method=‘POST’ action=“login.php”>
User Name: <input type="text" name="username" ><br>
Password: <input type="password" name="password"><br>
<input type="submit" value="Login">
</form>
</body>
</html>
31 Internet Programming
Input (cont’d)
//login.php
<?php
$username = $_POST[ ‘username’ ];
$password = $_POST[ ‘password’ ];
32 Internet Programming
Input (cont’d)
In effect, all form data will be available to PHP scripts
through the appropriate array: $_GET or $_POST.
33 Internet Programming
Input (cont’d)
To create a cookies, use the setcookie() function.
Cookies must be sent before any output from your script.
This function must be called before any other output in the PHP file, i.e
before <html>, any spaces, …
To retrieve a cookie value, use the $_COOKIE array with the
name of the cookie as index.
Ex.
<html><body>
<?php if( isset( $_COOKIE[ “uname” ] ) )
echo “Welcome “ . $_COOKIE[ “uname” ] . “! <br> “;
else
echo “Cookie not set <br>”;
?>
34 Internet Programming
Input Variables more
include / require
Format: include “file”; or require “file”;
includes and evaluates the specified file.
include generates a warning while require generates a fatal
error. Otherwise, both structures behave the same way.
include_once / require_once
similar in behavior to include / require with the only difference
being that if the code from a file has already been included /
required, it will not be included /required again.
35 Internet Programming
Input variables
Example
vars.php
<?php
$color = 'green';
$fruit = 'apple';
?>
test.php
<?php
include 'vars.php';
?>
36 Internet Programming
More array of variables
$ _GET[]
$ _POST[]
$ _COOKIE[]
$_REQUEST[]
$ _SESSION[]
$_SERVER[]
$_FILES[]
37 Internet Programming
Functions in PHP
Functions are at the heart of a well-organized script and will
make your code easy to read and reuse.
In PHP, functions come in two flavors – those built-in to the
language, and those that you define yourself.
User defined functions may be declared as follows:
<?php
function function_name($arg_1, $arg_2, ..., $arg_n)
{
// function body
[return $retval;]
}
?>
38 Internet Programming
Conditional functions
<?php
$defined= true;
// We can't call f1() from here since it doesn't exist yet, but we can
call f2()
f2();
if ($defined) {
function f1() {
echo "I don't exist until program execution reaches me.\n";
}
}
if ($defined) f1();
function f2() {
echo "I exist immediately upon program start.\n";
}
?>
39 Internet Programming
Functions within functions
<?php
function f1(){
function f2(){
echo "I don't exist until f1() is called.\n";
}
}
f1();
f2();
?>
40 Internet Programming
Functions (cont’d)
Recursive functions
Example
<?php
function recursion($a){
if ($a < 20) {
echo "$a \r\n";
recursion($a + 1);
}
}
?>
All functions in PHP have the global scope - they can be
called outside a function even if they were defined inside
and vice versa.
PHP does not support function overloading.
41 Internet Programming
Function arguments
PHP supports passing arguments by value (the default),
passing by reference, and default argument values.
To pass an argument to a function by reference, you can
prepend an ampersand (&) to the argument name in the
function definition.
Example
function getDate( &$arg1 ){
$arg1 = date(“d-m-Y”);
}
…
getDate( $date );
echo $date;
…
42 Internet Programming
Function arguments (cont’d)
To define an argument with a default value, the default
value can be assigned to the argument in the function
definition.
function sample( $arg1, $arg2 = “initial value” ){
…
}
when calling:
sample($var1, $var2);
sample($var1); //second argument takes default value
43 Internet Programming
Function arguments (cont’d)
PHP allows you to use arrays and special type NULL as default
values
The default value must be a constant expression, not a variable,
a class member or a function call.
Note that when using default arguments, any defaults should be
on the right side of any non-default arguments; otherwise,
things will not work as expected.
Example
<?php
function makeyogurt($type = "acidophilus", $flavour){
return "Making a bowl of $type $flavour.\n";
}
echo makeyogurt("raspberry"); // won't work, error
?>
44 Internet Programming
Returning values
Values are returned by using the optional return statement.
Any type may be returned, including lists and objects.
This causes the function to end its execution immediately
and pass control back to the line from which it was called.
To return a reference from a function, you have to use the
reference operator & in both the function declaration and
when assigning the returned value to a variable
45 Internet Programming
Returning values
Example
<?php
function &returns_reference(){
return $someref;
}
46 Internet Programming
Arrays in PHP
An array is a data structure that stores one or more similar type
of values in a single value.
The array()function is usually used when you want to
create a new array and populate it with more than one
element, all at the same time.
There are three different kind of arrays:
Numeric array − An array with a numeric index. Values are stored and
accessed in linear fashion. array(value1,value 2, …value n);
Associative array − An array with strings as index. This stores element
values in association with key values .array(“key1”’value1” ,
“key2””value2”…”keyn””valuen”);
Multidimensional array − An array containing one or more arrays and
values are accessed using multiple indices. array( array( ) );
47 Internet Programming
Array example 1
Example
…
$arr = array(“name”=>”Abebe”, “dept”=>”CS”, “year”=>3,
“cgpa”=>3.5);
foreach( $arr as $key=>$value ){
echo $key . “ = “ . $value . “<br>”;
}
//output
name = Abebe
dept = CS
year = 3
cgpa = 3.5
48 Internet Programming
Arrays Example 2 (Indexed array)
<html> <body>
<?php
/* First method to create array. */
$numbers = array( 1, 2, 3, 4, 5);
foreach( $numbers as $value ) {
echo "Value is $value <br />“; }
/* Second method to create array. */
$numbers[0] = "one"; $numbers[1] = "two"; $numbers[2] = "three";
$numbers[3] = "four"; $numbers[4] = "five";
foreach( $numbers as $value ) {
echo "Value is $value <br />"; }
?>
</body> </html>
49 Internet Programming
Arrays Example 3 (Associative array)
<html> <body>
<?php
/* First method to associate create array. */
$salaries = array("mohammad" => 2000, "qadir" => 1000, "zara" => 500);
echo "Salary of mohammad is ". $salaries['mohammad'] . "<br />";
echo "Salary of qadir is ". $salaries['qadir']. "<br />";
echo "Salary of zara is ". $salaries['zara']. "<br />";
/* Second method to create array. */
$salaries['mohammad'] = "high"; $salaries['qadir'] = "medium"; $salaries['zara'] =
"low";
echo "Salary of mohammad is ". $salaries['mohammad'] . "<br />";
echo "Salary of qadir is ". $salaries['qadir']. "<br />";
echo "Salary of zara is ". $salaries['zara']. "<br />";
?> </body> </html>
50 Internet Programming
Arrays Example 4 (Multidimensional array)
<html> <body>
<?php
$marks = array( "mohammad" => array ( "physics" => 35, "maths" => 30, "chemistry"
=> 39 ), “helen" => array ( "physics" => 30, "maths" => 32, "chemistry" => 29 ),
"zara" => array ( "physics" => 31, "maths" => 22, "chemistry" => 39 ) );
/* Accessing multi-dimensional array values */
echo "Marks for mohammad in physics : " ;
echo $marks['mohammad']['physics'] . "<br />";
echo "Marks for helen in maths : ";
echo $marks[helen ']['maths'] . "<br />";
echo "Marks for zara in chemistry : " ;
echo $marks['zara']['chemistry'] . "<br />";
?>
</body> </html>
51 Internet Programming
Arrays Example 5…
The general syntax of the foreach statement is:
foreach ( arrayname as variable ) {
//Statements to repeat }
52 Internet Programming
Arrays Example 6…
The general syntax of the foreach statement is:
foreach ( arrayname as variable ) {
//Statements to repeat }
53 Internet Programming
Array related built-in methods
To verify if a particular index exists in an associative
array, use the isset() function.
To sort array elements as ascending and descending
ordered use sort(), asort(), ksort() and rsort(),
arsort(),krsort()
• count() –to count number of array elements
• sizeof()- to know the size of arrays
• array_push()- to add elements
• array-combine()- to combine different array elements
54 Internet Programming
Server side State Maintenance -cookies
Some of the state maintenance principles in php are:
Cookies-user controlled
Cookies are text files stored on the client computer and they are kept of use
tracking purpose. PHP transparently supports HTTP cookies.
PHP provided setcookie() function to set a cookie.
setcookie(name, value, expire, path, domain, security);
<?php
setcookie("name", "John Watkin", time()+3600, "/","", 0);
setcookie("age", "36", time()+3600, "/", "", 0);
?>
Accessing Cookies :<?php echo $_COOKIE["name"]. "<br />";
You can use isset() function to check if a cookie is set or not.
if( isset($_COOKIE["name"])) echo "Welcome " . $_COOKIE["name"] . "<br />";
55 Internet Programming
Other state information managements
Sessions –server controlled
Hidden form fields- handling form elements
Query strings- handling database queries and operations
56 Internet Programming
Session
A way of preserving certain data across subsequent visits.
Enables us to build more customized applications and increase the
appeal of our web site.
A visitor accessing our web site is assigned a unique id, called
session id. This is either stored in a cookie on the user side or is
propagated in the URL.
To read/write from/to the session, it should first be initialized by
calling the function session_start()
The function will create a new session if one doesn’t exist already.
If a session already exists, all data in it will be available to the
current script.
Make use of isset() function to check if session variable is already
set or not.
57 Internet Programming
Session (cont’d)
Data in the session can be accessed through the built-in
array $_SESSION using the name of the session variable
as index.
58 Internet Programming
Starting and Checking Session
<?php
session_start();
if( isset( $_SESSION['counter'] ) )
{ $_SESSION['counter'] += 1; }
else { $_SESSION['counter'] = 1; }
$msg = "You have visited this page ". $_SESSION['counter'];
$msg .= "in this session."; ?>
<html> <head> <title>Setting up a PHP session</title> </head>
<body>
<?php echo ( $msg ); ?>
</body> </html>
59 Internet Programming
Session (cont’d)
<?php
// Use of session_register() is deprecated
$barney = "A big purple dinosaur.";
session_register("barney");
//Use of $_SESSION
$_SESSION["zim"] = "An invader from another
planet.";
60 Internet Programming
Session (cont’d) – Some functions
session_destroy Destroys all data registered to a session
session_id Get and/or set the current session id
session_is_registered Find out whether a global variable is
registered in a session
session_regenerate_id Update the current session id with a newly
generated one
session_register Register one or more global variables with the
current session
session_start Initialize session data
session_unregister Unregister a global variable from the current
session
session_unset Free all session variables, unset session variable
61 Internet Programming
PHP login and logout with session
Login :Php login script is used to provide the authentication for our web pages.
the Script executes after submitting the user login button.
<?php
ob_start();
session_start();
?>
Logout :It will erase the session data.
<?php
session_start();
unset($_SESSION["username"]); unset($_SESSION["password"]);
echo 'You have cleaned session';
header('Refresh: 2; URL = login.php'); ?>
62 Internet Programming
Database connectivity in PHP
MySQL is a free and open source database that has a lot
of users especially for web applications. It can be
downloaded from internet freely.
Whichever database you’re using, the steps to interact
with a database are similar:
Connect to the database.
Send an SQL query that contains instructions for the database
software.
If you retrieved data from the database, process the data.
Close the connection to the database.
63 Internet Programming
MySQL functions
MySQL is an open-source database management system that
well integrates with PHP.
PHP provides several functions that allow us to work with
MySQL databases.
In order to access data in a database,
Connect to the host machine on which the database server is
running
Select the database with which you want to work with
Issue queries via SQL statements
Iterate and use the result set, if any
For all of the above functions as well as many others, PHP
provides many handy functions.
64 Internet Programming
MySQL functions (cont’d)
To connect to the database host
resource mysql_connect ( [string server [, string username
[, string password [, bool new_link [, int
client_flags]]]]] )
65 Internet Programming
MySQL functions (cont’d)
To select a database
mysql_select_db( string db_name )
To query a database
mysql_query( string sql)
To iterate a result set
array mysql_fetch_array( resource result_set )
To get the number of rows in a result set
mysql_num_rows( resource result_set )
To close a connection to a database server
mysql_close()
66 Internet Programming