Chapter 5-Server-Side Scripting PHP
Chapter 5-Server-Side Scripting PHP
Scripting - PHP
1
Outline
– Introduction to PHP
– What is PHP
– Common uses of PHP
– Features of PHP
– Basics of PHP
– Data Base manipulation using PHP
What is PHP?
• PHP is a server-side scripting language designed specifically for
the Web (basically used for developing web based software
applications), it stands for Hypertext Preprocessor.
– Server-side scripting is a web server technology in which a user's request is
fulfilled by running a script directly on the web server to generate dynamic web
pages.
– It is usually used to provide interactive web sites that interface to databases or other
data stores.
• Is a programming language that allows web developers to create
dynamic content that interacts with databases.
• Within an HTML page, you can embed PHP code that will be
executed each time the page is visited.
• It is integrated with a number of popular databases, including
MySQL, PostgreSQL, Oracle, Sybase, Informix, and Microsoft
SQL Server.
Common uses of PHP
• PHP performs system functions, i.e. from files on a system it
can create, open, read, write, and close them.
• PHP can handle forms, i.e. gather data from files, save data to
a file, through email you can send data, return data to the user.
• You add, delete, modify elements within your database
through PHP.
• Access cookies variables and set cookies.
• Using PHP, you can restrict users to access some pages of your
website.
• It can encrypt data.
Features of PHP
• Open source
– PHP is an Open Source product. You have access to the
source code. You can use it, modify it, and redistribute it all
without charge.
– Simply stated, you can download and use these
applications without a credit card or a free trial period.
• Flexible for integration with HTML
– One or more PHP scripts can be embedded into static
HTML files and this makes client tier integration easy.
Features of PHP
• Suited to complex projects
– It is a fully featured object-oriented programming
language, with more than 110 libraries of programming
functions for tasks as diverse as math, sorting, creating
PDF documents, and sending email.
• Fast at running scripts
• Platform- and operating-system portable:
– PHP run on many different platforms and operating
systems. PHP can also be integrated with other web
servers.
Basics of PHP
Anatomy of a PHP Script
• A PHP script is a file (ending with a .php extension) consisting of text,
HTML, and PHP instructions interspersed throughout the file.
• The PHP instructions are contained within two HTML style tags;
<?php --- is the opening tag and
----
?> --- is the closing tag.
Steps of Writing a PHP Script
• Finding a Text Editor
• Naming the PHP File, .php Extension.
<?php
statement;
statement;
?>
e.g. <?php
echo "Hello, world.<br />";
?>
Embedding php in an html document
<html>
<head>
<title>Hello World</title>
</head>
<body>
<h1>Hello World example</h1>
<?php
echo "It's such a perfect day!<br />";
?>
</body>
</html>
Comments
18
• Arithmetic Operators
– The following arithmetic operators supported by PHP
language : +,-,*,%,++,--
• Comparison Operators
– The following comparison operators supported by PHP
language: ==,!=,>,<,<=,>=
• Logical Operators
– The following Logical operators supported by PHP
language: &&,||,!,and,or
• Assignment Operators
– The following assignment operators supported by PHP language: =,
+=,-=,*=,/=,%=
• The Conditional Operator
– The conditional operator is called a ternary operator because it requires
three operands. It is often used as a shorthand method for if/else
conditional statements
19
The Conditional Operator
• This first evaluates an expression for a true or false value
and then execute one of the two given statements
depending upon the result of the evaluation.
Format
conditional expression ? expression : expression
Examples:
$x ? $y : $z If $x evaluates to true, the value of the
expression becomes $y, else the value of the
expression becomes $z.
$big = ($x >$y)?$x :$y If x is greater than $y, $x is
assigned to variable $big, else $y is assigned to
variable $big.
20
Control structures
• Determines whether a block of statements will be executed.
• if statement
if (condition)
{ statements; }
• if - else statement
if (condition)
{ statements1; }
else
{ statements2; }
• if - else - if statement
if (condition) { statements1; }
elseif (condition) { statements2; }
elseif (condition) { statements3; }
else{ statements4; } 21
The switch Statement
switch (expression)
{
case label :
statement(s);
break;
case label :
statement(s);
break;
---
---
default :
statement;
}
22
The switch Statement
Example:
$color=“blue”;
switch ($color)
{
case "red":
print "Hot!";
break;
case "blue":
print "Cold.";
break;
default:
print "Not a good choice.";
break;
}
23
Loop statements
• Loops are used to execute a segment of code repeatedly until some condition is
met
• PHP’s basic looping:-
• while loop
while (condition)
{
statements;
increment/decrement counter;
}
• do - while loop
do
{
statements;
}
while (condition);
• for loop
for (initialize; condition; increment/decrement) 24
Loop statements(cont.)
• foreach Loop: The foreach statement is used to loop through arrays.
• The foreach loop is designed to work with arrays and works only
with array.
• For each pass the value of the current array element is assigned to
$value and the array pointer is moved by one and in the next pass
next element will be processed.
$array_name=array( item1, item2, item3, ...);
foreach ($array_name as $value)
{
do-something with the element's value;
}
Example:
$fruit =array(“orange”, “banana”, “strawberry”,);
foreach ( $fruit as $fruit_list)
{
25
echo $Fruit_list. "<br />";
The break statement
• The PHP break keyword is used to terminate the execution of a loop prematurely.
• The break statement is located inside the statement block. It gives you full control
and whenever you want to exit from the loop you can come out. After coming out
of a loop immediate statement to the loop will be executed.
• Example: In the following example condition test becomes true when the counter
value reaches 3 and loop terminates.
<html><body>
<?php
$i = 0; Output
Value is 1
while( $i < 10) Value is 2
{
$i++;
if( $i == 3 )break;
echo (“Value is $i”);
}
?>
26
</body></html>
The continue statement
• The PHP continue keyword is used to stop the current iteration of a loop
but it does not terminate the loop.
• Just like the break statement the continue statement is located inside the
statement block containing the code that the loop executes, preceded by a
conditional test. For the pass encountering continue statement, rest of the
loop code is skipped and next pass starts.
• Example: In the following example loop prints the value of array but for
which condition becomes true it just skip the code and next value is printed.
Output
<html><body> Value is 1
<?php Value is 2
$array = array( 1, 2, 3, 4, 5); Value is 4
Value is 5
foreach( $array as $value ) {
if( $value == 3 )continue;
echo "Value is $value <br />";
}
?> 27
Arrays in PHP
Two types of array:
• Numeric Array:- an array indexed by a number.
• Associative Array:- an array indexed by a string.
Syntax:
$array_name = array(value1, value2, value3 ...);
$array_name = array(key=>value, key=>value, ...);
Example:
$colors = array('red', 'green', 'blue');
$colors = array(1 => 'red', 2 => 'green', 3 => 'blue');
28
Let’s look at the following Example, which shows a numeric
array, an array indexed by number.
<html>
<head><title>Array of Products</title></head>
<body bgcolor="lightgreen">
<?php
$products=array('Pen','Pencil', 'Book', 'Exersice book');
echo "<b>Product list</b><br/>";
echo "\$products[0] is $products[0].<br/>";
echo "\$products[1] is $products[1].<br/>";
echo "\$products[2] is $products[2].<br />";
echo "\$products[3] is $products[3].<br />";
?>
</body> 29
Now let’s look at the following Example, which
shows an associative array, an array indexed by a
string.
<?php
$show=array( 'Title'=>'Aga-Boom','Author'=>
'Dmitri Bogatirev','Genre'=> 'Physical comedy',);
echo "\$show is $show.<br />\n";
?>
$show['Title'] is <?=$show['Title']?>.<br />
$show['Author'] is <?=$show['Author']?>.<br />
$show['Genre'] is <?=$show['Genre']?>.<br />
30
PHP - Functions
• A function is a piece of code which takes one more input in the form of
parameter and does some processing and returns a value.
– Creating a PHP Function and Calling a PHP Function
• function name should start with keyword function and all the PHP
code should be put inside { and } braces.
<html><head>
<title>Writing PHP Function</title>
</head>
<body>
<?php
/* Defining a PHP Function */
function writeMessage() {
echo "You are really a nice person, Have a nice time!";
}
/* Calling a PHP Function */
writeMessage();
?> 31
PHP Functions with Parameters
41
PHP Per-defined function : PHP String functions
3. The
strrev() function
The PHP strrev() function reverses a string:
Example:
<?php
echo strrev("Hello world!"); // outputs !dlrow olleH
?>
4. The strpos() function: searches for a specific text within a string.
• If a match is found, the function returns the character position of the first match. If no
match is found, it will return FALSE.
• The example below searches for the text "world" in the string "Hello world!":
Example:
<?php
echo strpos("Hello world!", "world"); // outputs 6
?>
5. The str_replace()
• The PHP str_replace() function replaces some characters with some other characters in
a string.
Example:
<?php
echo str_replace("world", "Dolly", "Hello world!"); // outputs Hello Dolly! 42
PHP 5 Array Functions
44
Retrieve data from html forms
• Setting up the HTML form
– To set up a form for server processing and data retrieval, two
important form attributes that controls how the form data is
processed whenever it is submitted must be specified. These two
form attributes are:
– Method Attributes
– Action Attributes
<form action="" method=""> ... </form>
• Action Attributes: specifies the PHP script file location for
processing when it is submitted.
• Method Attributes: specifies what type of method the form will
use to send the data. We have two methods, the GET and POST.
– Note: By default, if no method is specified, the GET method is used.
• Setting access keys for the form data by using the element's name
45
attribute
Retrieve data from html forms
• Name attribute
– The element's name attribute ( name="unique-name-
here" ) value is used by PHP as key to enable access to the
data value of the specified form field element when you
submit the form.
– Without the name attribute specified for each element
contained in the form, PHP can't access that element form
data value after the form has been submitted to the server
because its key is undefined.
<input type="text" name="unique-name-here" />
46
Retrieve data from html forms
• How form data is sent
– Client browsers can send information to a web server in
two different ways:
• GET Method
• POST Method
• GET Method: This method instructs the browser to send the information
(the name/value pairs) through the URL parameter by appending it to the
page request.
Example: How the form GET method data is submitted
48
Retrieve data from html forms
Retrieve form data sent via GET
<form action=“Get-method.php" method="get">
Firstname:<input type="text" name="firstname">
Lastname:<input type="text" name="lastname">
<input type="submit" value="submit" name="submit">
</form>
Get-method.php look like this
<?php
if( isset( $_GET['submit'] ) )
{
$FN=$_GET['firstname'];
$LN=$_GET['lastname'];
echo 'Your name is ' . $FN . ' ' . $LN;
}
?> N:B The PHP isset() function is used to determine if a variable is
set and is not null. 49
Using the POST
51
Using the POST
<form action="post-method.php" method="post">
<input type="text" name="firstname"/>
<input type="text" name="lastname" />
<input type="submit" name="submit" />
</form>
post-method.php look like this
<?php
$FN = $_POST['firstname'];
$LN = $_POST['lastname'];
echo 'Your name is ' . $FN . ' ' . $LN;
?>
52
The $_REQUEST variable
• The $_REQUEST variable is another PHP superglobal variable
that you can use to dynamically retrieve form data sent from
both Form GET and POST methods.
<form action="request-variable.php" method="post">
<input type="text" name="firstname" />
<input type="text" name="lastname" />
<input type="submit" name="submit" />
</form>
request-variable.php look like this
<?php
$firstname = $_REQUEST['firstname'];
$lastname = $_REQUEST['lastname'];
echo 'Your name is ' . $lastname .' ' . $firstname;
?> 53
Example
<html>
<head>
<title>Simple HTML Form</title>
</head>
<body bgcolor="lightblue"><font size="+1">
<form action=“form_example.php“/><p>
please enter your name: <br />
<input type="text" size=30 name="your_name" /><br />
please enter your phone number: <br />
<input type="text" size=30 name="your_phone" /><br />
<input type=submit value="submit" />
</form>
</body> 54
(The PHP Script)
form_example.php
<?php
extract($_REQUEST);
print "Your name is $your_name. <br />";
print "Your phone number is $your_phone.";
?>
55
Example 2
<html>
<body>
<form method="post" action="account.php">
Username<input type="text" name="uname"><br/>
Password<input type="password" name="pass"><br/>
<input type="submit" value="login">
</form>
</body>
</html>
#account.php
<?php
$u=$_POST['uname'];
$p=$_POST['pass'];
echo $u," ",$p;
?>
56
Data Base manipulation using PHP
Connecting PHP to MySQL Database
b. The database
c. Tables
e. Primary key
f. Schema
The Anatomy of a Relational Database
• Mysql_fetch_array( ) function
– Fetch a result row as an associative array, a numeric array,
or both
Syntax:
• array mysql_fetch_array( resource result )
Example:
• $record=mysql_fetch_array($record_set)
• mysql_num_rows()
– returns the number of rows in the result-set
– $number_of_rows = mysql_num_rows( $result_set )
• mysql_num_fields()
– returns the number of fields in a table
– $number_of_fields = mysql_num_fields( $result_set )
• mysql_field_name()
– returns the name of a specific field
– $field_name = mysql_field_name( $result_set, $index )
Retrieving the Query Results (SELECT)
• The mysql_num_rows() Function
– The mysql_num_rows() function returns the number of rows in the
result-set.
Format
int mysql_num_rows( resource result )
Example:
$number_of_rows = mysql_num_rows( $result_set )
• The mysql_num_fields() Function
– The mysql_num_fields() function returns the number of fields in a
table and the mysql_field_name() function returns the name of a field.
Format
int mysql_num_fields( resource result )
Example:
$number_of_fields = mysql_num_fields( $result_set )
Retrieving the Query Results (SELECT)
• Cipher
– A way of changing a message to keep it secret
– An algorithm used to encrypt or decrypt
• Role of cryptography
– Secure communications from tired parties
– Confidentiality of communication
PHP Built-in Encryption Functions
• PHP ships with three built-in encryption functions:
– md5(),
– crypt(), and
– sha1().
1. The md5() function :The function calculates the MD5 hash of a
supplied string using the MD5 Message-Digest algorithm.
Format :
string md5(string $str [, bool $raw_output ])
• The $str argument represents the string to be encrypted.
• If you pass FALSE in the $raw_output argument (the default), the
function returns the hash as a 32-character hexadecimal number.
• If you pass TRUE then the function returns a 16-byte raw binary
value
PHP Built-in Encryption Functions
2. The PHP crypt() function :It returns an encrypted string
using the standard Unix DES-based encryption algorithm (or
alternative algorithms that may be available on the system).
83