0% found this document useful (0 votes)
37 views76 pages

PHP All in One

The document provides an overview of server-side scripting, explaining the differences between static and dynamic web pages, and the role of scripting languages like PHP. It details the advantages of server-side scripting, including security and customization, and introduces PHP as a widely used server-side language. Additionally, it covers PHP syntax, output statements, comments, and variable handling, along with basic data types in PHP.

Uploaded by

kidusm760
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
37 views76 pages

PHP All in One

The document provides an overview of server-side scripting, explaining the differences between static and dynamic web pages, and the role of scripting languages like PHP. It details the advantages of server-side scripting, including security and customization, and introduces PHP as a widely used server-side language. Additionally, it covers PHP syntax, output statements, comments, and variable handling, along with basic data types in PHP.

Uploaded by

kidusm760
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 76

Server-Side Web System Design and Programming BahirDar, 2012E.

Chapter One

Server-Side Scripting Basics

Overview of Web Scripting

Web page is a document, typically written in HTML that is almost always accessible via HTTP.
Or pages on which, information is displayed on the web. It can be static or dynamic.

Static web page means that what is displayed does not change until the underlying HTML or
XML is changed.

When the content that is displayed changes in response to actions taken by the user, then the web
page is said to be dynamic. This kind of web page is developed using scripting languages.

A scripting language is a programming language in a simple text format. Generally, code


written in a scripting language does not have to be compiled – unlike, for example, code written
in C++ or Visual Basic. Instead, it is interpreted at the time of execution. Web browsers can
interpret certain scripting languages.

Scripts can be written to run either server-side or client-side. A script must be interpreted at the
time it is requested from the web server. Each scripting language has its own script interpreter –
called a script engine.

A client-side script is executed on the client, by the browser. Client-scripting is often used to
validate data entered on a form by the user, before the form is submitted to the server e.g. check
that an email address has a @ sign in it. Some of client side scripts are java script, VB script etc.
In client side script, users may be able to see the source code by viewing a file that contains the
script.

A server-side script is executed on the server, and generally produces HTML which is then
output HTML to the client.

Introduction to server-side scripting

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. The primary advantage of
server-side scripting is the ability to highly customize the response based on the user's

Page 1 of 19 Departments of Software Engineering By Alehegn E.


Server-Side Web System Design and Programming BahirDar, 2012E.C

requirements, access rights, or queries into data stores. From security point of view, server-side
scripts are never visible to the browser as these scripts are executed on the server and emit
HTML corresponding to user's input to the page.

In contrast, server-side scripts, written in languages such as PHP, ASP.NET, Java, ColdFusion,
Perl, Ruby, Go, Python, and server-side JavaScript, are executed by the web server when the
user requests a document. They produce output in a format understandable by web browsers
(usually HTML), which is then sent to the user's computer. The user cannot see the script's
source code (unless the author publishes the code separately), and may not even be aware that a
script was executed. Documents produced by server-side scripts may, in turn, contain client-side
scripts.

Server-side Web scripting is mostly about connecting Web sites to back end servers, such as
databases. This enables two-way communication:

i. Client to server: Customer-enter information as request.


ii. Server to client: Web pages can be assembled from back end-server to give output.

A server side script can:-

 Dynamically edit, change or add any content to a Web page to make it more useful for
individual users
 Respond to user queries or data submitted from HTML forms
 Access any data or databases and return the result to a browser
 Provide security since server side codes cannot be viewed from a browser

In server side script, since the scripts are executed on the server, the browser that displays the file
does not need to support scripting at all. The following are server-side scripting languages:

 PHP (*.php)
 Active Server Pages (ASP)
 ANSI C scripts
 Java via JavaServer Pages (*.jsp)
 JavaScript using Server-side JavaScript (*.ssjs)
 Lasso (*.lasso) etc

The main focus here is PHP.

Page 2 of 19 Departments of Software Engineering By Alehegn E.


Server-Side Web System Design and Programming BahirDar, 2012E.C

What is PHP?

PHP stands for Hypertext Preprocessor and is a server-side language. This means that the script
is run on your web server, not on the user's browser, so you do not need to worry about
compatibility issues. PHP supports many databases (MySQL, Informix, Oracle, Sybase, Solid,
PostgreSQL, Generic ODBC, Microsoft SQL Server etc.). PHP files can contain text, HTML
tags and scripts. Like other files written in server side language, PHP files are returned to the
browser as plain HTML and it has a file extension of ".php", ".php3", or ".phtml".

Why PHP?

 Allows easy storage and retrieval of information from supported database.


 Accessibility: You can reach the internet from any browser, any device, anytime,
anywhere.
 Manageability: It does not require distribution of application code and it is easy to change
code.
 Security: The source code is not exposed. Once user is authenticated, can only allow
certain actions. It also allows encryption.
 Scalability: Web-based 3-tier architecture can scale out

What you need to get started

Hopefully you have established a basic idea of what server-side scripting is, and when you
should use it. Next you need some basic requisites to be able to write and execute scripts.
Basically you need:

1) First of all you need a computer with a web server installed. PHP uses web servers such
as Apache, IIS etc. But for this course we will install WAMP server. WAMP server
refers to a software stack for the Microsoft Windows operating system, created by
Romain Bourdon and consisting of the Apache web server, OpenSSL for SSL (Secure
Sockets Layer) support, MySQL database and PHP programming language. WAMP sever
has a root directory called WWW. So all the files of a website must be stored under this
directory (C:\wamp\www\) to be executed by the server.
2) You need some sort of text editor such as Notepad, Notepad++, etc. to write the scripts.
3) You also need a web browser to display the web content. The web browser can be
Internet Explorer, Mozilla Firefox, Opera, and Google Chrome etc.

Page 3 of 19 Departments of Software Engineering By Alehegn E.


Server-Side Web System Design and Programming BahirDar, 2012E.C

PHP Basic Syntax

The PHP parsing engine needs a way to differentiate PHP code from other elements in the page.
The mechanism for doing so is known as ‘escaping to PHP.’ There are four ways to do this:

i. Canonical PHP tags


The most universally effective PHP tag style is:

<?php
Your PHP code here

?>

If you use this style, you can be positive that your tags will always be correctly interpreted.

ii. Short-open (SGML-style) tags: Short or short-open tags look like this:

<?
Your PHP code here

?>

Short tags are, as one might expect, the shortest option. We must do one of two things to enable
PHP to recognize the tags:

 Choose the --enable-short-tags configuration option when building PHP.


 Set the short_open_tag setting in php.ini file to on. This option must be disabled to parse
XML with PHP because the same syntax is used for XML tags.
iii. ASP-style tags: ASP-style tags mimic the tags used by Active Server Pages to delineate
code blocks. ASP-style tags look like this:
<%
Your PHP code here

%>

To use ASP-style tags, we should set the configuration option in your php.ini file.

iv. HTML script tags: HTML script tags look like this:
PHP output Statement <script language="PHP">
Your PHP code here

</script>

Page 4 of 19 Departments of Software Engineering By Alehegn E.


Server-Side Web System Design and Programming BahirDar, 2012E.C

PHP Output Statement

As shown above PHP has different syntaxes but for maximum compatibility, it is recommended
to use <?php…?> .

Each code line in PHP must end with a semicolon. The semicolon is a separator and is used to
distinguish one set of instructions from another.

There are two basic statements to output text with PHP: echo and print.

 echo has no return value whereas print has a return value. The returned value represents
whether the print statement is succeeded or not. If the print statement succeeds, the
statement returns 1 otherwise 0. It is rare that a syntactically correct print statement will
fail, but in theory this return value provides a means to test, for example, if the user’s
browser has closed the connection and sometimes the returned value can be used in
expressions.
 echo can take multiple parameters (although such usage is rare) but print can only take
one argument.
 echo is marginally faster than print.
 The echo or print statement can be used with or without parentheses: echo or echo().

The general format of the echo statement is as follows:


echo outputitem1,outputitem2,outputitem3, . . .;
echo (output statement);

The parameterized version of echo does not accept multiple arguments.

The general format of the print statement is as follows:


print outputstatement;
print(outputstatement);

Example: different ways of echo and print

echo 123; //output: 123

echo “Hello World!”; //output: Hello world!

echo (“Hello World!”); //output: Hello world!

echo “Hello”,”World!”; //output: Hello World!

echo Hello World!; //output: error, string should be enclosed in quotes

Page 5 of 19 Departments of Software Engineering By Alehegn E.


Server-Side Web System Design and Programming BahirDar, 2012E.C

print (“Hello world!”); //output: Hello world!

The command print is very similar to echo, with two important differences:
 Unlike echo, print can accept only one argument.
 Unlike echo, print returns a value, which represents whether the print statement
succeeded.
It is possible to embed HTML tags in echo or print statements. The browser will parse and
interpret them like any tag included in HTML page and display the page accordingly.
Table1.1 Using echo/print statements
echo/print statement PHP output web page display
echo “Hello World”; HelloWorld! HelloWorld!

echo “Hello”; HelloWorld! HelloWorld!


echo “World!”;
echo “Hello\nWorld!”; Hello Hello World!
World!
echo “Hello<br>World!”; Hello<br>World Hello
World!
echo “<u> <i> Hello world!</i></u>”; <u>Hello world!</u> Hello world!

The first echo statement includes a space so the space is output. The second row has two echo
statements, but neither includes a space, so no space appears in the Web page. Each echo
statement output does not go to new line unless we insert \n. The third row shows a space on the
Web page, even though no space is included in the echo statement. The space is added by the
browser when it reads the PHP output as HTML. In HTML, a new line is not displayed as a new
line; it is just interpreted as a single space.

Multi-lines printing: use the key word END next to <<< symbol and before the statement
terminating symbol (;) or enclose the statements to be displayed using double quotes. Here are
the examples to print multiple lines in a single print statement:
<?php
# First Example
print <<<END
This uses the "here document" syntax to output multiple lines with $variable
interpolation. Note that the here document terminator must appear on a line with
just a semicolon no extra whitespace!
END;
# Second Example
print "This spans multiple lines. The newlines will be
output as well";
?>

Page 6 of 19 Departments of Software Engineering By Alehegn E.


Server-Side Web System Design and Programming BahirDar, 2012E.C

Note: The file must have a .php extension. If the file has a .html extension, the PHP code will
not be executed.

PHP Comments

A comment is the portion of a program that exists only for the human reader and stripped out
before displaying the programs result. There are two commenting formats in PHP:

 Single-line comments: They are generally used for short explanations or notes relevant
to the local code. Here are the examples of single line comments.

<?php
# This is a comment
// This is a comment too
print “An example with single line comment”;
?>

 Multi-lines comments: They are generally used to provide pseudo code algorithms and
more detailed explanations when necessary. The multiline style of commenting is the
same as in C. Here is the example of multi lines comments.

<?php
/* This is a comment with multiline
Author : Abebe Kebede
Purpose: Multiline Comments Demo
Subject: PHP
*/
echo "An example with multi line comments";
?>

Working with Variables

A variable is a special container that can be defined to hold a value such as number, string,
object, array, or a Boolean. The main way to store information in the middle of a PHP program is
by using a variable. Here are the most important things to know about variables in PHP.

 All variables in PHP are denoted with a leading dollar sign ($).
 The value of a variable is the value of its most recent assignment.
 Variables are assigned with the = operator, with the variable on the left-hand side and the
expression to be evaluated on the right.
 Variables can, but do not need, to be declared before assignment.

Page 7 of 19 Departments of Software Engineering By Alehegn E.


Server-Side Web System Design and Programming BahirDar, 2012E.C

 Variables in PHP do not have intrinsic types - a variable does not know in advance
whether it will be used to store a number or a string of characters.
 Variables used before they are assigned have default values.
 PHP does a good job of automatically converting types from one to another when
necessary.

Variable Naming Rules

When creating PHP variables, you must follow these four rules:

 Variable names must start with a letter of the alphabet or the _ (underscore) character.
 Variable names can contain only the characters: a-z, A-Z, 0-9, and _ (underscore).
 Variable names may not contain spaces. If a variable must comprise more than one word
it should be separated with the _ (underscore) character. (e.g., $user_name).
 Variable names are case-sensitive. The variable $High_Score is not the same as the variable
$high_score.

The correct way of declaring a variable in PHP is:


$Variable_Name=value;

PHP has a total of eight data types which we use to construct our variables: integers, doubles,
Booleans, null, strings, arrays, objects and resources. The first five are simple types, and the
next two (arrays and objects) are compound - the compound types can package up other arbitrary
values of arbitrary type, whereas the simple types cannot.

Integers:

Integers are whole numbers, without a decimal point, like 3214. They are the simplest type .they
correspond to simple whole numbers, both positive and negative. Integers can be assigned to
variables, or they can be used in expressions, like so:
$int_var = 12345;
$another_int = -12345 + 12345;

Doubles:

They are floating point numbers. By default, doubles print with the minimum number of decimal
places needed. For example, the code:
$pi= 3.14;
$version=1.12;

Page 8 of 19 Departments of Software Engineering By Alehegn E.


Server-Side Web System Design and Programming BahirDar, 2012E.C

Boolean:

They have only two possible values either true or false. PHP provides a couple of constants
especially for use as Booleans: TRUE and FALSE, which can be used like so:

if (TRUE)
print("This will always print<br>");
else
print("This will never print<br>");

NULL:
NULL is a special type that only has one value: NULL. To give a variable the NULL value, simply assign it like
this:

$my_var = NULL;

The special constant NULL is capitalized by convention, but actually it is case insensitive; you
could just as well have typed:
$my_var = null;

A variable that has been assigned NULL has the following properties:

 It evaluates to FALSE in a Boolean context.


 It returns FALSE when tested with IsSet() function.

Strings:

They are sequences of characters, like "PHP supports string operations". Following are valid
examples of string
$string_1 = "This is a string in double quotes";
$string_2 = "This is a somewhat longer, singly quoted string";
$string_39 = "This string has thirty-nine characters";
$string_0 = ""; // a string with zero characters

Singly quoted strings are treated almost literally, whereas doubly quoted strings replace variables
with their values as well as specially interpreting certain character sequences.
<? php
$variable = "name";
$literally = 'My $variable will not print!\\n';
print($literally);
$literally = "My $variable will print!\\n";
print($literally);
?>

This will produce the following result:


My $variable will not print!\n
My name will print

Page 9 of 19 Departments of Software Engineering By Alehegn E.


Server-Side Web System Design and Programming BahirDar, 2012E.C

There are no artificial limits on string length - within the bounds of available memory, you ought
to be able to make arbitrarily long strings.

Strings that are delimited by double quotes (as in "this") are preprocessed in both the following
two ways by PHP:

 Certain character sequences beginning with backslash (\) are replaced with special
characters
 Variable names (starting with $) are replaced with string representations of their values.

The escape-sequence replacements are:

 \n is replaced by the newline character


 \r is replaced by the carriage-return character
 \t is replaced by the tab character
 \$ is replaced by the dollar sign itself ($)
 \" is replaced by a single double-quote (")
 \\ is replaced by a single backslash (\)

PHP provides a large number of predefined variables to all scripts. The variables represent
everything from external variables to built-in environment variables, last error messages to last
retrieved headers.
 Superglobals — Superglobals are built-in variables that are always available in all scopes
 $GLOBALS — References all variables available in global scope
 $_SERVER — Server and execution environment information
 $_GET — HTTP GET variables
 $_POST — HTTP POST variables
 $_FILES — HTTP File Upload variables
 $_REQUEST — HTTP Request variables, and can replace $_POST, $_GET and
$_COOKIE variables
 $_SESSION — Session variables
 $_COOKIE — HTTP Cookies
 $php_errormsg — The previous error message
 $HTTP_RAW_POST_DATA — Raw POST data
 $http_response_header — HTTP response headers
 $argc — The number of arguments passed to script
 $argv — Array of arguments passed to script
Many of these variables, however, cannot be fully documented as they are dependent upon which
server are running, the version and setup of the server, and other factors.

Page 10 of 19 Departments of Software Engineering By Alehegn E.


Server-Side Web System Design and Programming BahirDar, 2012E.C

Removing Variables
 We can uncreated the variable by using this statement: unset(VariableName);
 After this statement, the variable $age no longer exists. If we try to echo it, you get an
“undefined variable” notice. It is possible to unset more than one variable at once, as
follows: unset($age, $name, $address);

Variable Scope:

Scope can be defined as the range of availability a variable has to the program in which it is
declared. PHP variables can be one of four scope types:

 Local variables
 Function parameters
 Global variables
 Static variables

PHP Local Variables

A variable declared in a function is considered local; that is, it can be referenced solely in that
function. Any assignment outside of that function will be considered to be an entirely different
variable from the one contained in the function:
<?
$x = 4;
function assignx () {
$x = 0;
print "\$x inside function is $x. ";
}
assignx();
print "\$x outside of function is $x. ";
?>

This will produce the following result.


$x inside function is 0.
$x outside of function is 4.

PHP Function Parameters


PHP Functions are covered in detail in PHP Function Chapter. In short, a function is a small unit
of program which can take some input in the form of parameters and does some processing and
may return some value.

Function parameters are declared after the function name and inside parentheses. They are
declared much like a typical variable would be:

Page 11 of 19 Departments of Software Engineering By Alehegn E.


Server-Side Web System Design and Programming BahirDar, 2012E.C

<?
// multiply a value by 10 and return it to the caller
function multiply ($value) {
$value = $value * 10;
return $value;
}
$retval = multiply (10);
Print "Return value is $retval\n";
?>

This will produce the following result.


Return value is 100

PHP Global Variables

In contrast to local variables, a global variable can be accessed in any part of the program.
However, in order to be modified, a global variable must be explicitly declared to be global in
the function in which it is to be modified. This is accomplished, conveniently enough, by placing
the keyword GLOBAL in front of the variable that should be recognized as global. Placing this
keyword in front of an already existing variable tells PHP to use the variable having that name.
Consider an example:
<?
$somevar = 15;
function addit() {
GLOBAL $somevar;
$somevar++;
print "Somevar is $somevar";
}
addit();
?>

This will produce the following result.


Somevar is 16

PHP Static Variables

In contrast to the variables declared as function parameters, which are destroyed on the
function's exit, a static variable will not lose its value when the function exits and will still hold
that value should the function be called again.

You can declare a variable to be static simply by placing the keyword STATIC in front of the
variable name.
<?
function keep_track() {
STATIC $count = 0;
$count++;

Page 12 of 19 Departments of Software Engineering By Alehegn E.


Server-Side Web System Design and Programming BahirDar, 2012E.C

print $count;
print " ";
}
keep_track();
keep_track();
keep_track();
?>

This will produce the following result.


1
2
3

Work with constants

A constant is a name or an identifier for a simple value. A constant value cannot change during
the execution of the script. By default a constant is case-sensitive. By convention, constant
identifiers are always uppercase. A constant name starts with a letter or underscore, followed by
any number of letters, numbers, or underscores. If you have defined a constant, it can never be
changed or undefined.

To define a constant you have to use define() function and to retrieve the value of a constant, you
have to simply specifying its name. Unlike with variables, you do not need to have a constant
with a $. You can also use the function constant() to read a constant's value if you wish to obtain
the constant's name dynamically.

constant() function

As indicated by the name, this function will return the value of the constant.

This is useful when you want to retrieve value of a constant, but you do not know its name, i.e. It
is stored in a variable or returned by a function.

Example
<?php
define("MINSIZE", 50);
echo MINSIZE;
echo constant("MINSIZE"); // same thing as the previous line
?>

Only scalar data (boolean, integer, float and string) can be contained in constants.

Differences between constants and variables are

 There is no need to write a dollar sign ($) before a constant, where as in Variable one has
to write a dollar sign.

Page 13 of 19 Departments of Software Engineering By Alehegn E.


Server-Side Web System Design and Programming BahirDar, 2012E.C

 Constants cannot be defined by simple assignment, they may only be defined using the
define() function.
 Constants may be defined and accessed anywhere without regard to variable scoping
rules.
 Once the Constants have been set, may not be redefined or undefined.

Manipulate Numbers

In everyday life, numbers are easy to identify. They're 3:00 P.M., as in the current time, or 1.29
Birr, as in the cost of an item. Maybe they're like, the ratio of the circumference to the diameter
of a circle. In PHP, numbers can be all these things.

However, PHP doesn't treat all these numbers as "numbers." Instead, it breaks them down into
two groups: integers and floating-point numbers. Integers are whole numbers, such as -4, 0, 5,
and 1,975. Floating-point numbers are decimal numbers, such as -1.23, 0.0, 3.14159, and
9.9999999999.

Conveniently, most of the time PHP doesn't make you worry about the differences between the
two because it automatically converts integers to floating-point numbers and floating-point
numbers to integers. This conveniently allows you to ignore the underlying details. It also means
3/2 is 1.5, not 1, as it would be in some programming languages. PHP also automatically
converts from strings to numbers and back. For instance, 1+"1" is 2.

Checking Whether a String Contains a Valid Number:

You want to ensure that a string contains a number. For example, you want to validate an age
that the user has typed into a form input field. Use is_numeric( ):
if (is_numeric('five')) { /* false */ }
if (is_numeric(5)) { /* true */ }
if (is_numeric('5')) { /* true */ }
if (is_numeric(-5)) { /* true */ }
if (is_numeric('-5')) { /* true */ }

Rounding Floating-Point Numbers:

To round a number to the closest integer, use round( ) :


$number = round(2.4); // $number = 2
To round up, use ceil( ):
$number = ceil(2.4); // $number = 3
To round down, use floor( ):
$number = floor(2.4); // $number = 2

Page 14 of 19 Departments of Software Engineering By Alehegn E.


Server-Side Web System Design and Programming BahirDar, 2012E.C

Operating on a Series of Integers

Use the range( ) function, which returns an array populated with integers:
foreach(range($start,$end) as $i) {
echo “$i<br>”; }

Instead of using range(), it can be more efficient to use a for loop. Also, you can increment
using values other than 1. For example:
for ($i = $start; $i <= $end; $i += $increment) {
echo “$i<br>”; }

Generating Random Numbers within a Range

To generate a random number within a range of numbers: Use mt_rand( ):


// random number between $upper and $lower, inclusive
$random_number = mt_rand($lower, $upper);

Calculating Exponents

To raise e to a power, use exp( ):


$exp = exp(2); // 7.3890560989307

To raise it to any power, use pow( ):


$exp = pow( 2, M_E); // 6.5808859910179
$pow = pow( 2, 10); // 1024

Formatting Numbers

You have a number and you want to print it with thousands and decimals separators. For
instance, you want to display prices for items in a shopping cart.

Use the number_format( ) function to format as an integer:


$number = 1234.56;
print number_format($number); // 1,235 because number is rounded up

Specify a number of decimal places to format as a decimal:


print number_format($number, 2); // 1,234.56

Manipulate Strings

Strings in PHP are a sequence of characters, such as "We hold these truths to be self evident," or
"Once upon a time," or even "111211211". When you read data from a file or output it to a web
browser, your data is represented as strings. The following are string manipulation operations:-

Page 15 of 19 Departments of Software Engineering By Alehegn E.


Server-Side Web System Design and Programming BahirDar, 2012E.C

 String concatenation operation: - To concatenate two string variables together, use the dot (.)
operator like echo $string1 . " " . $string2;
 Substr()-uses to copy strings.

Syntax :- variable = substr(string, start [, length ]);

The start argument is the position in string at which to begin copying, with 0 meaning the
start of the string. The length argument is the number of characters to copy (the default is to
copy until the end of the string).

For example:
$name = "Fred Flintstone";

$fluff = substr($name, 6, 4);// $fluff is "lint" i.e copy strings from 6th about 4 chars consecutively

$sound = substr($name, 11);// $sound is "tone" i.e copy from 11th character on wards and assign
to the variable $sound

 substr_count():- uses to count how many times a smaller string occurs in a larger one.

written as $number = substr_count(big_string, small_string);

The output is always integer.

For example:
$sketch = <<< End_of_Sketch

Well, there's egg and bacon; egg sausage and bacon; egg and spam;

egg bacon and spam; egg bacon sausage and spam; spam bacon sausage

and spam; spam egg spam spam bacon and spam; spam sausage spam spam

bacon spam tomato and spam;

End_of_Sketch;

$count = substr_count($sketch, "spam");

print("The word spam occurs $count times.");

The word spam occurs 14 times.

 substr_replace(): permits many kinds of string modifications:

Has syntax of $string = substr_replace(original string, new string, start [, length ]);
where start shows starting from where we need replace by new string/ start is the index of the

Page 16 of 19 Departments of Software Engineering By Alehegn E.


Server-Side Web System Design and Programming BahirDar, 2012E.C

first character that we need to replace. The length parameter uses to indicate how many
characters we need to replace from original characters.

The function replaces the part of original indicated by the start (0 means the start of the
string) and length values with the string new. If no fourth argument is given, substr_replace(
) removes the text from start to the end of the string.

For instance:
$greeting = "good morning citizen";

$farewell = substr_replace($greeting, "bye", 5, 7);

// $farewell is "good bye citizen"

Use a length value of 0 to insert without deleting the original strings:


$farewell = substr_replace($farewell, "kind ", 9, 0);

// $farewell is "good bye kind citizen"

Use a replacement of "" to delete without inserting:


$farewell = substr_replace($farewell, "", 8);

// $farewell is "good bye"

Here's how we can insert at the beginning of the string without deleting from original character:

Let $farewell= "good bye"


$well = substr_replace($farewell, "now it's time to say ", 0, 0);

//$well is "now it's time to say good bye"'

A negative value for start indicates the number of characters from the end of the string from
which to start the replacement:
$farewell = substr_replace($farewell, "riddance", -3);

// $farewell is "now it's time to say good riddance"

A negative length indicates the number of characters from the end of the string at which to stop
deleting:
$farewell = substr_replace($farewell, "", -8, -5);

// $farewell is "now it's time to say good dance"

 strrev() function:- takes a string and returns a reversed copy of it. Has syntax:-
$string = strrev(string);

Page 17 of 19 Departments of Software Engineering By Alehegn E.


Server-Side Web System Design and Programming BahirDar, 2012E.C

For example:
echo strrev("There is no cabal");

labac on si erehT

 str_repeat() function:- takes a string and a count and returns a new string consisting of the
argument string repeated count times.

Written as $repeated = str_repeat(string, count);

For example, to build a crude horizontal rule:

echo str_repeat('-', 40); this will displays 40 dashes.

 str_pad( ) function:- pads one string with another i.e left blank space. Optionally, we can say
what string to pad with, and whether to pad on the left, right, or both:
$padded = str_pad(to_pad, length [, with [, pad_type ]]);

The default is to pad on the right with spaces:


$string = str_pad('Fred Flintstone', 30);
echo "$string:35:Wilma";
Fred Flintstone :35:Wilma

The optional third argument is the string to pad with:


$string = str_pad('Fred Flintstone', 30, '. ');
echo "{$string}35";
Fred Flintstone. . . . . . . .35

The optional fourth argument can be either STR_PAD_RIGHT (the default), STR_PAD_LEFT, or
STR_PAD_BOTH (to center). For example:
echo '[' . str_pad('Fred Flintstone', 30, ' ', STR_PAD_LEFT) . "]\n";
echo '[' . str_pad('Fred Flintstone', 30, ' ', STR_PAD_BOTH) . "]\n";
[ Fred Flintstone]
[ Fred Flintstone ]

 strpos() function:- used to search for a string or character within a string. If a match is found in
the string, this function will return the position of the first match. If no match is found, it will
return FALSE.

Written as strops(orginal string, new string)

Example: the following code used to show from where the word “world” started.
<?php
echo strpos("Hello world!","world");

Page 18 of 19 Departments of Software Engineering By Alehegn E.


Server-Side Web System Design and Programming BahirDar, 2012E.C

?>

The output will be 6. As seen the position of the string "world" in our string is position 6. The
reason that it is 6, and not 7, is that the first position in the string is 0, and not 1.

Example:-
$long = "Today is the day we go on holiday to Florida";
$to_find = "day";
$pos = strpos(strrev ($long), strrev($to_find));
if ($pos === false) {
echo("Not found");
} else {
// $pos is offset into reversed strings
// Convert to offset into regular strings
$pos = strlen($long) - $pos - strlen($to_find);;
echo("Last occurrence starts at position $pos");
}

Last occurrence starts at position 30

 String-Searching Functions

Several functions find a string or character within a larger string. They come in three families:
strpos() and strrpos(), which return a position; strstr() and strchr(), which return the
string they find; and strspn() and strcspn(), which return how much of the start of the string
matches a mask.

The strstr() function finds the first occurrence of a small string in a larger string and returns
from that small string on. For instance:
$record = "Fred,Flintstone,35,Wilma";
$rest = strstr($record, ","); // $rest is ",Flintstone,35,Wilma"

As with strrpos(), strrchr() searches backward in the string, but only for a character, not for
an entire string.

 Using the strlen() function

The strlen() function is used to find the length of a string. For example:- To find the length of
"Hello world!", we can write as follows
<?php
echo strlen("Hello world!");
?>

Reading Assignment

 PHP Date and Time


 PHP Operators

Page 19 of 19 Departments of Software Engineering By Alehegn E.


Server-Side Web System Design and Programming BahirDar, 2012E.C

Unit Two
2. PHP Forms and Statements
2.1. PHP Forms

One of the most powerful features of PHP is the way it handles HTML forms. The basic concept
that is important to understand is that any form element will automatically be available to your
PHP scripts.

 The syntax could be written as -


<form action=“url to submit the form filled” method=“get” or “post”>
<!–- form contents -->
</form>
 Where action=“…” is the page that the form should submit its data to, and
method=“…” is the method by which the form data is submitted. If the method is get the
data is passed in the url string, if the method is post it is passed as a separate file.

The form variables are available to PHP in the page to which they have been submitted. The
variables are available in three superglobal arrays created by PHP called $_POST, $_GET and
$_REQUEST.

The GET Method:-

 Has restriction to send to server/ database parts up to 1024 characters only.


 Never use GET method for systems which have password or other sensitive information
to be sent to the server.
 GET can't be used to send binary data, like images or word documents, to the server
because GET method sends the encoded user information.
 The data sent by GET method can be accessed using QUERY_STRING environment
variable.

Example: - Save it as info.php


<?php
if( $_GET["name"] || $_GET["age"] )
{ echo "Welcome ". $_GET['name']. "<br />";
echo "You are ". $_GET['age']. " years old.";
exit();
}
?>
<html><body>
<form action="<?php $_PHP_SELF ?>" method="GET">

Page 1 of 21 Departments of Software Engineering By Alehegn E.


Server-Side Web System Design and Programming BahirDar, 2012E.C

Name: <input type="text" name="name" />


Age: <input type="text" name="age" />
<input type="submit" />
</form>
</body></html>

The above code’s action attribute value can be represented as the filename itself like:-
<form action=”info.php” method=”Get”>

The POST Method:


The POST method transfers information via HTTPs headers. The information is encoded as
described in case of GET method and put into a header called QUERY_STRING.

 The POST method does not have any restriction on data size to be sent.
 Relatively secured and can be used in large data requesting and responding
 The POST method can be used to send ASCII as well as binary data.
 The data sent by POST method goes through HTTP header so it is secured enough on
HTTP protocol. The PHP provides $_POST associative array to access all the
information sent using POST method.

Example: - Take the above example and change the value of method attribute in the form from
GET to POST and the variable from $_GET to $_POST.

The $_REQUEST variable

 The PHP $_REQUEST variable contains the contents of $_GET, $_POST, and
$_COOKIE variables
 This variable can be used to get the result from form data sent with both the GET and
POST methods.

Example1: - Create the following two.


<?php
echo "Welcome to the homepage";
?>
Save the above file with a filename welcome.php.
<html><body>
<form action="" method="post">
Username:<input type="text" name="username"><br>
Password:<input type="password" name="password"><br>
<input type="submit" value="Login">
</form>
</body>
</html>

Page 2 of 21 Departments of Software Engineering By Alehegn E.


Server-Side Web System Design and Programming BahirDar, 2012E.C

<?php
$una="abc";
$pwd="abc1234";
$username=$_REQUEST['username'];
$password=$_REQUEST['password'];
if($username==$una&&$password==$pwd)
header("location:welcome.php");
else
echo "Please enter valid username/password";
?>
Save the above file with a filename login.php, run it and see the output.
The PHP header () function supplies raw HTTP headers to the browser and can be used to
redirect it to another location. The redirection script should be at the very top of the page to
prevent any other part of the page from loading.

The target is specified by the Location: header as the argument to the header () function. After
calling this function the exit () function can be used to halt parsing of rest of the code.

Form Validation

User input should be validated on the browser whenever possible (by client scripts). Browser
validation is faster and reduces the server load.

You should consider server validation if the user input will be inserted into a database. A good
way to validate a form on the server is to post the form to itself, instead of jumping to a different
page. The user will then get the error messages on the same page as the form. This makes it
easier to discover the error.

Common Validations

We can categorize validation in to the following groups:

 Presence Validation
 String Length Validation
 Type Validation
 Inclusion in set Validation
 Uniqueness Validation
 Format Validation

Presence Validation: is used to check if there is something in a field or if a variable is not


empty.
$value=“”;
if(!isset($value)||empty($value))

Page 3 of 21 Departments of Software Engineering By Alehegn E.


Server-Side Web System Design and Programming BahirDar, 2012E.C

die("Validation failed");
String Length Validation: is used to check if a value is within a certain range.
$password=”itec1234”;
$min=6;
$max=10;
if(strlen($password)<$min&&strlen($password)>$max)
die("Password doesnot fulfill the requirement");
Type Validation: is checking whether the given value is number, string or of another type.
$value=5;
if(!is_numeric($value))
die("Validation failed not integer");
Inclusion in set Validation: Is used to validate whether the value is in the set
$value=$_POST['value'];
$set=array("M","F");
if(!in_array($value,$set))
die("Not in the list");
Uniqueness Validation: Is used to validate whether the value which is going to be submitted to a
database is unique or not
$username=$_POST['value'];
$usernamefromdb=array();
if(in_array($username,$usernamefromdb))
die("Not unique");
Format Validation: Is used to validate whether the value has the right format e.g. email with @
symbol, currency with $ symbol, DateTime with AM or PM

 uses regular expression on the string Syntax: preg_match($regexp,$subject)


if(!preg_match("/PHP/","PHP is SSS"))
die("match not found");
else
echo "Match Found!";
 Digits 0-9 only: This uses to check whether an input is digit/ number or not. The
following is a syntax to check if $age is a number or not. If not number, it display
“Please enter numbers only for Age”
if (!preg_match("/^[.0-9]*$/",$value))
die("Please enter numbers only for Age");
or
$age= htmlspecialchars($_POST['age']);
if (!preg_match("/\D/",$age))
die("Please enter numbers only for Age");
 Letters a-z and A-Z only

Page 4 of 21 Departments of Software Engineering By Alehegn E.


Server-Side Web System Design and Programming BahirDar, 2012E.C

if (!preg_match("/^[a-zA-Z ]*$/",$value)) {
die("Only letters and white space allowed");
 Validate e-mail address: Used to check an email is valid, i.e to have valid forms.
There is a simple way to check if data entered into input field named "email" is an
e-mail address without any unnecessary complications and fancy regular
expressions.
if (!filter_var($value, FILTER_VALIDATE_EMAIL))
die("Invalid email format");
Or
if(!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$value))
die("Invalid email format");
 URL Address: If there is an input field named "website" we can check for a valid
URL address like this
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-
9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$value)) {
die("Invalid URL");
Example: Using form validation. The validation rules here are:

 Display “Welcome! Please fill the following fields if you wanna sign up!” message
while the page is opened for the first time.
 Display “Please fill all the required fields!” message if all of the fields are empty upon
submission.
 Display “First Name can contain only characters!” message if the user enters characters
other than a-z or A-Z in FirstName field.
 Display “Last Name can contain only characters!” message if the user enters characters
other than a-z or A-Z in LastName field.
 Display “Age can only be number!” message if the user enters characters other than 0-9
in FirstName field.
 Display “Invalid Email!” message if the user enters an email which does not include @
and . symbols in it.
 Display “Username already exist!” message if the user enter either of abc,12, xyz
usernames
 Display “Password must be above 6 characters!” message if the user enters a password
which consists 6 or less characters.
 Display “Invalid URL!” message if the user enters a website which does not contain
http/s,ftp,www,.domainname.

Page 5 of 21 Departments of Software Engineering By Alehegn E.


Server-Side Web System Design and Programming BahirDar, 2012E.C

 Otherwise display all the values submitted from the form.

Formvalidation.php
<html>
<head><link rel="stylesheet" type="text/css" href="formstyle.css"></head>
<body>
<div id="xx"><div id="xxx"><h1>User SignUp Form</h1></div>
<hr> <div id="xxx">
<form action="" method="post">
FirstName:<input type="text" name="fname"><font>*</font><br>
LastName:<input type="text" name="lname"><font>*</font><br>
Sex:<select name="sex"><option value="" selected>Choose Gender</option><option
value="M">Male</option><option value="F">Female</option></select><font>*</font></br>
Age:<input type="text" name="age"><font>*</font><br>
Email:<input type="text" name="email"><font>*</font><br>
Username:<input type="text" name="username"><font>*</font><br>
Password:<input type="Password" name="password"><font>*</font><br>
Website(if any):<input type="text" name="website"><br>
<input type="submit" name="signup" value="SignUp"><input type="reset" value="Reset">
</form></div></div>
<?php
echo "<div id=xr><div id=xxx>";
if(isset($_POST['signup']))
{
if(!empty($_POST['fname'])&&!empty($_POST['lname'])&&!empty($_POST['sex'])&&!e
mpty($_POST['age'])&&!empty($_POST['email'])&&!empty($_POST['username'])&&!empty($_PO
ST['password']))
{
$fname=$_POST['fname'];
$lname=$_POST['lname'];
$sex=$_POST['sex'];
$age=$_POST['age'];
$email=$_POST['email'];
$usernames=array("abc","123","xyz");
$gender=array("M","F");
$username=$_POST['username'];
$password=$_POST['password'];
$website=$_POST['website'];
$c=0; $minchar=6;
if(!preg_match("/^[a-zA-Z ]*$/",$fname)) {
echo ("First Name can contain only characters<br>");
$c++;
}
if(!preg_match("/^[a-zA-Z ]*$/",$lname)) {
echo ("Last Name can contain only characters<br>");
$c++;
}
if(!in_array($sex,$gender)){
echo ("Please select your gender!<br>");
$c++;
}
if(!preg_match("/^[0-9]*$/",$age)) {

Page 6 of 21 Departments of Software Engineering By Alehegn E.


Server-Side Web System Design and Programming BahirDar, 2012E.C

echo ("Age can only be numbers<br>");


$c++;
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)){
echo ("Invalid email format<br>");
$c++;
}
if(in_array($username,$usernames))
{
echo ("$username already exist!<br>");
$c++;
}
if(strlen($password)<$minchar) {
echo ("Password must be above 6 characters!<br>");
$c++;
}
if($c==0) {
echo "<center><i>You have successfully signed up!</i></center>";
echo "<hr><b><center>Your Details</center></b><hr>";
echo "Full Name:$fname $lname<br>";
echo "Sex:$sex Age:$age<br>";
echo "Email:$email<br>Username:$username<br>";
}
}else{
echo "Please fill all the required fields!<br>";
}
if(!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-
9+&@#\/%=~_|]/i",$website)&&$c==0)
echo "";
else if($c>0)
echo "Invalid url";
else
echo "Website:$website<br><hr><br>";
}else{
echo "Welcome! Please fill the following fields if you wanna sign up!</div></div>";
}
?></body></html>

Page 7 of 21 Departments of Software Engineering By Alehegn E.


Server-Side Web System Design and Programming BahirDar, 2012E.C

2.2. Decision Statements

The if, else if ...else and switch statements are used to take decision based on the different
condition.

You can use conditional statements in your code to make your decisions. PHP supports
following decision making statements:

The if Statement

Use the if statement to execute some code only if a specified condition is true.

Syntax
if (condition)
code to be executed if condition is true;
The following example will output "Have a nice weekend!" if the current day is Friday:
<?php
$d=date("D");
if ($d=="Fri") echo "Have a nice weekend!";
?>

Notice that there is no ..else.. in this syntax. The code is executed only if the specified condition
is true.

The If...Else Statement

Use this statement, if you want to execute some code if a condition is true and another code if a
condition is false.

Syntax
if (condition)
code to be executed if condition is true;
else
code to be executed if condition is false;
Note: If more than one line should be executed if a condition is true/false, the lines should be
enclosed within curly braces.
Example:
The following example will output "Have a nice weekend!" if the current day is Friday,
otherwise it will output "Have a nice day!”
<?php
$d=date("D");
if ($d=="Fri")
echo "Have a nice weekend!";
else
echo "Have a nice day!";

Page 8 of 21 Departments of Software Engineering By Alehegn E.


Server-Side Web System Design and Programming BahirDar, 2012E.C

?>

The ElseIf Statement

If you want to execute some code if one of the several conditions is true, then use the elseif
statement.
Syntax
if (condition)
code to be executed if condition is true;
else if(condition)
code to be executed if condition is true;
else
code to be executed if condition is false;
Example:
The following example will output "Have a nice weekend!" if the current day is Friday, and
"Have a nice Sunday!" if the current day is Sunday. Otherwise it will output "Have a nice day!"
<?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!";
?>

The Switch Statement

If you want to select one of many blocks of code to be executed, use the Switch statement.

The switch statement is used to avoid long blocks of if..else if..else code.

Syntax:
switch (expression)
{
case label1:
code to be executed if expression = label1;
break;
case label2:
code to be executed if expression = label2;
break;
default:
code to be executed if expression is different from both label1 and label2; }
Example
The switch statement works in an unusual way. First it evaluates given expression then seeks a
label to match the resulting value. If a matching value is found, then the code associated with the

Page 9 of 21 Departments of Software Engineering By Alehegn E.


Server-Side Web System Design and Programming BahirDar, 2012E.C

matching label will be executed. If none of the labels match, then the statement will execute any
specified default code.
<?php
$d=date("D");
switch ($d)
{
case "Mon":
echo "Today is Monday"; break;
case "Tue":
echo "Today is Tuesday"; break;
case "Wed":
echo "Today is Wednesday"; break;
case "Thu":
echo "Today is Thursday"; break;
case "Fri":
echo "Today is Friday"; break;
case "Sat":
echo "Today is Saturday"; break;
case "Sun":
echo "Today is Sunday"; break;
default:
echo "Wonder which day is this ?";
}
?>

2.3. PHP Loops

Loops in PHP are used to execute the same block of code a specified number of times. PHP
supports following four loop types.

The for Loop Statement

The for loop is used when you know in advance how many times the script should run.
Syntax
for (initialization; condition; increment)
{
code to be executed;
}
Parameters:

 initialization: Mostly used to set a counter (but can be any code to be executed once at
the beginning of the loop)
 condition: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues.
If it evaluates to FALSE, the loop ends.
 increment: Mostly used to increment a counter (but can be any code to be executed at the
end of the loop)

Page 10 of 21 Departments of Software Engineering By Alehegn E.


Server-Side Web System Design and Programming BahirDar, 2012E.C

Note: Each of the parameters above can be empty, or have multiple expressions (separated by
commas).

Example
1. The example below defines a loop that starts with i=1. The loop will continue to run as long as i is less than, or equal to
5. i will increase by 1 each time the loop runs:

<?php
for ($i=1; $i<=5; $i++)
{
echo "The number is " . $i . "<br />";
}
?>
2. The following example displays a product table
<html><body>
<?php
echo "<h1>Multiplication table</h1>";
echo "<table border=2 width=50%";
for ($i = 1; $i <= 5; $i++ ) { //this is the outer loop
echo "<tr>";
echo "<td>".$i."</td>";
for ( $j = 2; $j <= 5; $j++ ) { // inner loop
echo "<td>".$i * $j."</td>";
}
echo "</tr>";
}
echo "</table>";
?>
</body>
</html>

The while loop Statement

The while statement will execute a block of code if and as long as a test expression is true. If the
test expression is true then the code block will be executed. After the code has executed the test
expression will again be evaluated and the loop will continue until the test expression is found to
be false.

Syntax
while (condition)
{
code to be executed;
}
Example: The following example shows how to insert years from 1970-2015 in a form list box
and display the selected year upon submit.
<html><body>

Page 11 of 21 Departments of Software Engineering By Alehegn E.


Server-Side Web System Design and Programming BahirDar, 2012E.C

<form action="" method="post">


Year:<select name="year">
<?php
$year=1970;
while($year<=2015)
{ echo "<option value=$year>$year</option>";
$year++;
}
echo "</select>";
?>
<br><input type="submit" value="Display"></form>
<?php
$year=$_POST['year'];
if($year!=null)
echo "Year:$year";
?>
</body></html>

The do...while loop Statement

The do...while statement will always execute the block of code once, it will then check the
condition, and repeat the loop while the condition is true.

Syntax
do
{
code to be executed;
}
while (condition);

Example

The example below defines a loop that starts with i=1. It will then increment i with 1, and write
some output. Then the condition is checked, and the loop will continue to run as long as i is less
than, or equal to 5:

<html><body>
<?php
$i=1;
echo “The number is:”;
do
{
$i++;
echo "$i ";
}
while ($i<=5);

Page 12 of 21 Departments of Software Engineering By Alehegn E.


Server-Side Web System Design and Programming BahirDar, 2012E.C

?>
</body></html>

This will produce the following result:


The number is= 2 3 4 5 6

The foreach loop Statement

The foreach statement is used to loop through arrays. 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.

Syntax
foreach (array as value)
{
code to be executed;
}
Example

Try out the following example to list out the values of an array.
<?php
$array = array( 1, 2, 3, 4, 5);
echo "Values of the array:”;
foreach( $array as $value )
{
echo “$value ";
}
?>
This will produce the following result:
Values of the array:1 2 3 4 5

The break statement


The PHP break keyword is used to terminate the execution of a loop prematurely. The break
statement is situated 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:
<?php
$i = 0;
while( $i < 10)
{
$i++;
if( $i == 3 ) break;
}
Page 13 of 21 Departments of Software Engineering By Alehegn E.
Server-Side Web System Design and Programming BahirDar, 2012E.C

echo ("Loop stopped at i = $i" );


?>

This will produce the following result:


Loop stopped at i = 3

The continue statement

The PHP continue keyword is used to halt the current iteration of a loop but it does not terminate
the loop. Just like the break statement the continue statement is situated 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.
<?php
$array = array( 1, 2, 3, 4, 5);
echo “Values of the array:”;
foreach( $array as $value )
{
if( $value == 3 )continue;
echo "$value ";
}
?>
This will produce the following result:
Values of the array: 1 2 4 5

2.4. Arrays

A variable is a storage area holding a number or text. The problem is, a variable will hold only
one value.

An array is a special variable that stores one or more similar type of values in a single variable.
For example if you want to store 100 numbers then instead of defining 100 variables it’s easy to
define an array of 100 length.

An array can hold all your variable values under a single name. And you can access the values
by referring to the array name. Each element in the array has its own index so that it can be
easily accessed.

In PHP, there are three kinds of arrays:

Page 14 of 21 Departments of Software Engineering By Alehegn E.


Server-Side Web System Design and Programming BahirDar, 2012E.C

 Numeric array - An array with a numeric index. Values are stored and accessed in linear
fashion
 Associative array - An array where each ID key is associated with a value
 Multidimensional array - An array containing one or more arrays and values are
accessed using multiple indices

Numeric Array
These arrays can store numbers, strings and any object but their index will be represented by
numbers. By default, the array index starts from zero.

Example
The following example demonstrates how to create and access numeric arrays. Here we have
used array() function to create array.
<?php
/* First method to create array. */
$numbers = array( 1, 2, 3, 4, 5);
echo "Value of the array:”;
foreach( $numbers as $value )
{
echo "$value ";
}
/* Second method to create array. */
$numbers[0] = "one";
$numbers[1] = "two";
$numbers[2] = "three";
$numbers[3] = "four";
$numbers[4] = "five";
echo "Value of the array:”;
foreach( $numbers as $value )
{
echo "$value ";
}
?>
This will produce the following result:

Values of the array: 1 3 2 4 5


Values of the array: one two three four five

Associative Arrays
The associative arrays are very similar to numeric arrays in terms of functionality but they are
different in terms of their index. When storing data about specific named values, a numerical
array is not always the best way to do it. Associative array will have their index as string so that
you can establish a strong association between key and values.
Page 15 of 21 Departments of Software Engineering By Alehegn E.
Server-Side Web System Design and Programming BahirDar, 2012E.C

Example 1

In this example we use an array to assign credit_hours to the different courses:


$credit_hour = array("AIP"=>3, "AP"=>3, "DCN"=>4, "CMT"=>4, "EDP"=>4);
This is equivalent with:
$credit_hour[‘AIP’] = "3";
$credit_hour[‘AP’] = "3";
$credit_hour[‘DCN’] = "4";
$credit_hour[‘CMT’] = "4";
$credit_hour[‘EDP’] = "4";
<?php
$credit_hour = array("AIP"=>3, "AP"=>3, "DCN"=>4, "CMT"=>4, "EDP"=>4);
$grade = array("AIP"=>'A', "AP"=>'B', "DCN"=>'C', "CMT"=>'A', "EDP"=>'C');
$grade_point= array("AIP"=>12, "AP"=>9, "DCN"=>8, "CMT"=>16, "EDP"=>8);
foreach($credit_hour as $value)
$total_credit_hour+=$value;
foreach($grade_point as $value)
$total_grade_point+=$value;
$semester_gpa=number_format(($total_grade_point/$total_credit_hour),2);
echo "GPA:".$semester_gpa;
?>
This will produce the following result:

GPA: 2.94
NOTE: Don't keep associative array inside double quote while printing, otherwise it would not
return any value.

Multidimensional Arrays

A multi-dimensional array each element in the main array can also be an array. And each
element in the sub-array can be an array, and so on. Values in the multi-dimensional array are
accessed using multiple indexes.

Example:
<?php
$grade = array("Abebe"=>array("AIP"=>'A',"AP"=>'B'),"Ermias"=>array("AIP"=>'B',
"AP"=>'C'));
foreach($grade['Abebe'] as $key=>$value)
echo "<br>Abebe scored:".$value." in ".$key;
foreach($grade['Ermias'] as $key=>$value)
echo "<br>Ermias scored:".$value." in ".$key;
?>
This will produce the following result:

Abebe scored:A in AIP


Abebe scored:B in AP

Page 16 of 21 Departments of Software Engineering By Alehegn E.


Server-Side Web System Design and Programming BahirDar, 2012E.C

Ermias scored:B in AIP


Ermias scored:C in AP

The above code is equivalent with:


<?php
$grade['Abebe']['AIP']="A";

$grade['Abebe']['AP']="B";

$grade[‘Ermias’]['AIP']="B";

$grade[‘Ermias’]['AP']="C";

foreach($grade['Abebe'] as $key=>$value)
echo "<br>Abebe scored:".$value." in ".$key;
foreach($grade['Ermias'] as $key=>$value)
echo "<br>Ermias scored:".$value." in ".$key;”\
?>
This will produce the same output as the above example.

Adding and Removing Array Elements

PHP comes with four functions that allow us to add or remove elements from the beginning or
end of an array: the array_unshift() function adds an element to the beginning of an array; the
array_shift() function removes the first element of an array; the array_push() function adds an
element to the end of an array; and the array_pop() function removes the last element of an
array. The following listing illustrates them all in action:
<?php
// define array
$movies = array('The Lion King', 'Cars', 'A Bug\'s Life');
// remove element from beginning of array
array_shift($movies);
// remove element from end of array
array_pop($movies);
// add element to end of array
array_push($movies, 'Ratatouille');
// add element to beginning of array
array_unshift($movies, 'The Incredibles');
// print array
// output: ('The Incredibles', 'Cars', 'Ratatouille')
print_r($movies);
?>
Notethat:- The array_unshift(), array_shift(), array_push(), and
array_pop() functions should be used only with numerically indexed arrays and not with
associative arrays. Each of these functions automatically re-indexes the array to account for the
value(s).

Page 17 of 21 Departments of Software Engineering By Alehegn E.


Server-Side Web System Design and Programming BahirDar, 2012E.C

Sorting Arrays

PHP comes with a number of built-in functions designed for sorting array elements in
different ways. The first of these is the sort() function, which lets to sort numerically
indexed arrays alphabetically or numerically, from lowest to highest value.

Some Sorting Functions of PHP which has different sorting orders are:-

 sort() : sorts the elements in the numeric and alphabetical order.


 rsort() : sorts the elements in the reverse order.
 asort() : sorts the elements in the array without changing the indices.
 ksort() : sorts the arrays by key.
For example:
<?php
// define array
$data = array(15,81,14,74,2);
asort($data);
print_r($data);// Array ( [4] => 2 [2] => 14 [0] => 15 [3] => 74 [1] => 81 )
echo "<br/>";
ksort($data);
print_r($data);// Array ( [0] => 15 [1] => 81 [2] => 14 [3] => 74 [4] => 2 )
echo "<br/>";
sort($data);
print_r($data);// Array ( [0] => 2 [1] => 14 [2] => 15 [3] => 74 [4] => 81 )
?>

2.5. PHP Functions

PHP functions are similar to other programming languages. A function is a piece of code which
takes one or more input in the form of parameter and does some processing and returns a value.

 Functions MUST be defined before they called. Functions can only be executed if they
are called. Function headers are of the format:- function functionName($arg_1, $arg_2,
…, $arg_n)
 Unlike variables, function names are not case sensitive (foo(…) == Foo(…) == FoO(…))
 Function statements do the actual work of the function and must be contained within
the function braces

i. Creating PHP Function:


We can create a function with its name should start with keyword function and all the PHP code
should be put inside { and } braces as shown in the following example below:

Page 18 of 21 Departments of Software Engineering By Alehegn E.


Server-Side Web System Design and Programming BahirDar, 2012E.C

<?php
function writeMessage()
{
echo "You are really a nice person, Have a nice time!";
}
writeMessage();
?>
ii. PHP Functions with Parameters:
PHP gives us option to pass our parameters inside a function. We can pass as many as
parameters we like. These parameters work like variables inside function. Following example
takes two integer parameters and add them together and then print them.
<?php
function addFunction($num1, $num2){
$sum = $num1 + $num2;
echo "Sum of the two numbers is : $sum";
}
addFunction(10, 20);
?>

iii. Passing Arguments by Reference:


It is possible to pass arguments to functions by reference. This means that a reference to the
variable is manipulated by the function rather than a copy of the variable's value.

Any changes made to an argument in these cases will change the value of the original variable.
You can pass an argument by reference by adding an ampersand to the variable name in either
the function call or the function definition. The following example shows both the cases.
<html><body> <?php
function addFive(&$num){
$num += 5;}
function addSix(&$num){
$num += 6;}
$orignum = 10;
addFive($orignum );
echo "Original Value is $orignum<br />";
addSix($orignum );
echo "Original Value is $orignum<br />";
?></body></html>
iv. PHP Functions returning value:
A function can return a value using the return statement in conjunction with a value or object.
Return stops the execution of the function and sends the value back to the calling code. It is
possible to return more than one value from a function using return array(1,2,3,4).

Page 19 of 21 Departments of Software Engineering By Alehegn E.


Server-Side Web System Design and Programming BahirDar, 2012E.C

The following example takes two integer parameters and adds them together and then returns
their sum to the calling program. Note that return keyword is used to return a value from a
function.
<html><body>
<?php
function addFunction($num1, $num2){
$sum = $num1 + $num2;
return $sum;}
$return_value = addFunction(10, 20);
echo "Returned value from the function : $return_value”;
?>
</body></html>
We can return multiple values from a function, by placing them all in an array and returning the
array. The next example illustrates, by accepting a sentence and returning the individual words,
reversed, to the caller as an array:
<?php
function add_sub($num1,$num2){
$add=$num1+$num2;
$sub=$num1-$num2;
return array($add,$sub);
}
$result_array=add_sub(15,20);
echo "Add:".$result_array[0]."<br>";
echo "Sub:".$result_array[1]."<br>";
//you can use list function to assign the returned value to variables
list($add_result,$sub_result)=add_sub(30,20);
echo "Add:".$add_result."<br>";
echo "Sub:".$sub_result;
?>
v. Setting Default Values for Function Parameters:
We can set a parameter to have a default value if the function's caller doesn't pass it.
<?php
function studinfo($department="IT",$year="3rd"){
return "You are $year year $department student<br>";
}
echo studinfo();
echo studinfo("Software Engineering","1st");
echo studinfo("Electrical",Null);
echo studinfo("2nd");
?>
Output
You are 3rd year IT student
You are 1st year Software Engineering student
You are year Electrical student
You are 3rd year 2nd student

Page 20 of 21 Departments of Software Engineering By Alehegn E.


Server-Side Web System Design and Programming BahirDar, 2012E.C

vi. Dynamic Function Calls:


It is possible to assign function names as strings to variables and then treat these variables
exactly as the function name itself. Following example depicts this behavior. From the following
code, Hello will be displayed.
<html><body>
<?php
function sayHello(){
echo "Hello<br />";}
$function_holder = "sayHello";
$function_holder();
?>
</body></html>
vii. Using Recursive Function
Another, slightly more complex idea involving functions is recursion. A recursive function is a
function that calls itself repeatedly until a condition is satisfied. Such a function is typically used
to solve complex, iterative calculations, or to process deeply nested structures.
<?php
function printValues($arr) {
global $count;
global $out;
if (!is_array($arr)) {
die('ERROR: Input is not an array');
}
foreach ($arr as $a) {
if (is_array($a)) {
printValues($a);
} else {
$out[] = $a;
$count++;
}
}
return array('total' => $count, 'values' => $out);
}
$data = array('o' => array('orange','owl','one'),'t' => array('tea','ten','tag','twentythree' =>
array(array('twenty', 'three'),array('vingt', 'trois', array('red' => 'baron','blue' => 'blood')))));
// count and print values in nested array
$ret = printValues($data);
echo $ret['total'] . ' value(s) found: ';
echo "<br/>";
echo implode(', ', $ret['values']);
?>

Output:
12 value(s) found:
orange, owl, one, tea, ten, tag, twenty, three, vingt, trois, baron, blood

Page 21 of 21 Departments of Software Engineering By Alehegn E.


Server-Side Web System Design and Programming BahirDar, 2012E.C

Unit Three

3. Connecting to Databases

3.1. Introduction

One of the reasons for PHP’s popularity as a Web scripting language is its support for a wide
range of relational database systems. This support makes it easy for Web developers to create
data-driven Web sites and to prototype new Web applications quickly and efficiently.

PHP supports more than fifteen different database engines, including Microsoft SQL Server,
IBM DB2, PostgreSQL, MySQL, and Oracle. Using database in applications helps us to:
Read/write data, Store more data, have better organized data, faster access to data, easier to
manipulate and relate data to other data.

Database: is a set of tables. We should have 1 database for 1 application.

Tables: is a set of rows and columns. It represents a single concept such as products, customers,
orders etc. We can create relationships among tables.

Columns: a set of data of single data type. Ex. FirstName, LastName, Email, Password etc.
columns have types such as strings, integers, float, date etc.

Rows: single record of data. Ex. “Abebe”, “Kebede”, “[email protected]”, “password”

Field: is the intersection of a row and a column. Ex. FirstName: ”Abebe”

Index: data structure on a table to increase look up speed.

Foreign key: table columns whose values references rows in another table. It is the foundation
of relational table.

PHP allows developers to interact with databases in two ways: by using a customized database
specific extension, or by using the database-neutral PHP Data Objects (PDO) extension. While
the PDO extension is more portable, many developers still find it preferable to use the native
database extension, especially when the native extension offers better performance or more
features than the PDO version.

Of the various database engines supported by PHP, the most popular one by far is MySQL. Both
PHP and MySQL are open-source.

Page 1 of 15 Departments of Software Engineering By Alehegn E.


Server-Side Web System Design and Programming BahirDar, 2012E.C

Connect to an MySQL server/existing Database

PHP provides us different APIs to deal with MySQL server databases: mysql( Original MySQL),
mysqli( MySQL improved) and PDO( PHP Data Objects). The differences between these APIs
are shown on the table given below:

PHP database interactions in five steps:

 Create a database connection


 Perform Database query
 Use returned data if any
 Release returned data
 Close database connection

Creating a database connection:

Before we enable do anything with MySQL in PHP, we should first connect to the MySQL
server using specific connection variables. Connection variables consist of the following
common parameters, of which the first one is required while others are optional:-

 Host name: This is the name of the server. We can change to whatever host is acting as
MySQL server.
 User name: The root user of the system.
 User’s password:- This is encrypted written with the form for security.

The common function in PHP that uses for server connection is mysql_connect( ) or
mysqli_connect() function. This function has the following syntax:- mysql_connect
("hostname", "user", "pass") to connect with MySQL server. PHP provides mysql_connect
function to open a database connection. This function can take up to five parameters and returns
a MySQL link identifier on success, or FALSE on failure.

The five parameters are the three above and the two below options.

Page 2 of 15 Departments of Software Engineering By Alehegn E.


Server-Side Web System Design and Programming BahirDar, 2012E.C

Optional - If a second call is made to mysql_connect() with the same


new_link arguments, no new connection will be established; instead, the identifier of the
already opened connection will be returned.

Optional - A combination of the following constants:

MYSQL_CLIENT_SSL - Use SSL encryption

MYSQL_CLIENT_COMPRESS - Use compression protocol


client_flags
MYSQL_CLIENT_IGNORE_SPACE - Allow space after function names

MYSQL_CLIENT_INTERACTIVE - Allow interactive timeout seconds of


inactivity before closing the connection

Therefore, mysql_connect() function written as follows with respective parameters:-

mysql_connect(server,username,passwd,new_link,client_flag);

There are also functions in PHP which have different purposes. For instance,

 mysql_select_db("database name") or mysqli_select_db(“connection”,"database


name") : Equivalent to the MySQL command USE; makes the selected database the
active one.
 mysql_query("query"): Used to send any type of MySQL command to the server.
 mysql_fetch_rows("results variable from query"): Used to return a row of the entire
results of a database query.
 mysqli_affected_rows():Print out affected rows from different queries:
 mysql_fetch_array("results variable from query"): Used to return several rows of the
entire results of a database query.
 mysql_free_result(“result variable from query”): Used to release the returned results.
 mysql_error(): Shows the error message that has been returned directly from the
MySQL server.

We issue this connection command with the PHP function called mysql_connect() or
mysqli_connect(). As with all of our PHP/MySQL statements, you can either put the information
into variables, or leave them as text in MySQL query as shown below:-:
$host = “localhost”;

Page 3 of 15 Departments of Software Engineering By Alehegn E.


Server-Side Web System Design and Programming BahirDar, 2012E.C

$user = “root”;
$pass = “”;
$connect = mysql_connect($host, $user, $pass); Or simply $connect = mysql_connect(“localhost”, “root”, “”);
Or you can also use
$connect=mysqli_connect($host, $user, $pass);

Choosing and Creating the working Database

After establishing a MySQL connection with the code above, you then need to choose which
database you will be using with this connection. This is done with the
mysql_select_db(“database-name”) or mysqli_select_db(“connection”,”databasename”)
function. If the database you are looking to work on is not available, you can create it using
mysql_query() or mysqli_query() function together with CREATE command followed by
database name. mysql_query function can take two parameters and returns TRUE on success or
FALSE on failure. The parameters are:- sql and connection. The syntax of the function is:-
mysql_query(sql, connection variable); or mysqli_query(connection variable,sql);
To create a database uses the following sql syntax:
CREATE DATABASE database_name

Example Using : mysql Example Using : mysqli

Page 4 of 15 Departments of Software Engineering By Alehegn E.


Server-Side Web System Design and Programming BahirDar, 2012E.C

<?php <?php
$connection=$mysql_connect("localhost", "root", "") ; $connection=$mysqli_connect("localhost", "root", "");
If($connection) If($connection)
echo "Connected to MySQL<br />"; echo "Connected to MySQL<br />";
$sql=mysql_select_db("test"); }else{
If($sql){ $result=mysqli_query($connection,“create database
echo "Connected to Database";//display this message if test”);//create a database called test if not available
database is selected If($result)
}else{ mysqli_select_db($connection,"test")
$result=mysql_query(“create database else
test”,$connection);//create a database called test if not die(“Database not
available selected:”.mysql_error($connection));//select test
If($result) database
mysql_select_db("test");//select test database }
else mysqli_close($connection);//closing connection
die(“Database not selected:”.mysql_error()); ?>
}
?>
mysql_close();//closing connection

Output:
Connected to MySQL
Connected to Database

 mysql_query ("create database test”,$connection): told MySQL to create a database


called test.
 die(mysql_error()); will print out an error if there is a problem in the database creation
process.

Closing Query

 When you are finished working with query results retrieved with the mysql_query() function,
use the mysql_free_result() function to close the resultset
 To close the resultset, pass to the mysql_free_result() function the
variable containing the result pointer from the mysql_query() function

Create Table MySQL

Before you enter data (rows) into a table, you must first define what kinds of data will be stored
(columns).This can be done using Create sql statement.
Page 5 of 15 Departments of Software Engineering By Alehegn E.
Server-Side Web System Design and Programming BahirDar, 2012E.C

Syntax:

CREATE TABLE table_name (column_name1 data_type,column_name2 data_type,....)

We are now going to design a MySQL query to summon our table from database test.

Example Using : mysql Example Using : mysqli


<?php <?php
// Make a MySQL Connection // Make a MySQL Connection
$server=”localhost”; $server=”localhost”;
$dbuser=”root”; $dbuser=”root”;
$dbpassword=””; $dbpassword=””;
$dbname=”test”; $dbname=”test”;
$connection=$mysql_connect($server,$dbuser,$dbpass $connection=$mysqli_connect($server,$dbuser,$dbpass
word); word,$dbname);
if($connection) if($connection)
{ { // Create a MySQL table in the selected database
$sql=mysql_select_db($dbname); $sql2="CREATE TABLE example(
If($sql) id INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(id),
{ // Create a MySQL table in the selected database name VARCHAR(30), age INT)";
$sql2="CREATE TABLE example( $result=mysqli_query($connection,$sql2);
id INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(id), If($result)
name VARCHAR(30), age INT)"; echo "Table Created!";
$result=mysql_query($sql2,$connection); else
If($result) die(“Table Creation
echo "Table Created!"; failed:”.mysqli_error($connection));
else }else{
die(“Table Creation failed:”.mysql_error()); die(“Mysql server Connection
}else{ Failed:”.mysqli_error($connection));
die(“Database selection failed:”.mysql_error()); }
} mysqli_close($connection);//closing connection
}else{
die(“Mysql server Connection Failed:”.mysql_error()); ?>
}
mysql_close();//closing connection
?>

Page 6 of 15 Departments of Software Engineering By Alehegn E.


Server-Side Web System Design and Programming BahirDar, 2012E.C

Send/Insert Data to a Database

When data is put into a MySQL table it is referred to as inserting data. When inserting data it is
important to remember the exact names and types of the table's columns. If you try to place a 500
word essay into a column that only accepts integers of size three, you will end up with errors.
Inserting data into a table can be performed using Insert into sql statement.

Syntax:

INSERT INTO table_name VALUES (value1, value2, value3,...) Or

INSERT INTO table_name (column1, column2,...) VALUES (value1, value2,...)

<html><style>
#style{ display:block;
width:220px;
height:120px;
border:1px solid black;
line-height:30px;
}
#style p{
margin-left:20px;
margin-right:20px;
}</style><body>
<?php
if(isset($_POST['submit']))
{
//getting name and age from the user
$name=$_POST['name'];
$age=$_POST['age'];
// Make a MySQL Connection
$connection=mysql_connect("localhost", "root", "");
If($connection){
$sql=mysql_select_db("test”);
If($sql){
// Insert a row of information into the table "example"
$sql2="INSERT INTO example(name, age) VALUES('$name', '$age') ";
$result=mysql_query($sql2,$connection) ;

Page 7 of 15 Departments of Software Engineering By Alehegn E.


Server-Side Web System Design and Programming BahirDar, 2012E.C

If($result)
echo "Data Inserted!";
else
die(“Data not inserted:”.mysql_error());
} else
die(“Database not selected:”.mysql_error());

}else{
die(“Connection Failed:”.mysql_error());
}
mysql_close();//closing connection
?>
<div id="style"><p><form action="" method="post">
Name:<input type="text" name="name" required="" placeholder="name"><br>
Age:<input type="text" name="age" required="" placeholder="age"><br>
<input type="submit" value="Submit" name="submit"><input type="reset" value="Reset">
</form></p></div></body></html>

If you want to use mysqli, replace mysql connection and data insertion by the following code:
// Make a MySQL Connection
$connection=mysqli_connect("localhost", "root", "","test”);
If($connection){
// Insert a row of information into the table "example"
$sql2="INSERT INTO example(name, age) VALUES('$name', '$age') ";
$result=mysqli_query($connection,$sql2) ;
If($result)
echo "Data Inserted!";
else
die(“Data not inserted:”.mysqli_error($connection));
} else
die(“Database not selected:”.mysqli_error($connection));
}else{
die(“Connection Failed:”.mysqli_error($connection));
}
mysqli_close($connection);//closing connection
?>

Page 8 of 15 Departments of Software Engineering By Alehegn E.


Server-Side Web System Design and Programming BahirDar, 2012E.C

Retrieve Data from a Database

Usually most of the work done with MySQL involves pulling down data from a MySQL
database. In MySQL, data is retrieved with the "SELECT" keyword. Think of SELECT as
working the same way as it does on your computer. If you want to copy some information in a
document, you would first select the desired information, then copy and paste.

Before attempting to retrieve data, be sure that you have created a table that contains some data.
In this example, we will output the first entry of our MySQL "examples" table to the web
browser.

The SELECT statement is used to select data from a database.

Syntax: SELECT column_name(s) FROM table_name

Example:

Example Using : mysql Example Using : mysqli


<?php <?php
// Make a MySQL Connection // Make a MySQL Connection
$connection=mysql_connect("localhost", "root", ""); $connection=mysqli_connect("localhost", "root", "","test”);
If($connection){ If($connection){
$sql=mysql_select_db("test"); / Retrieving all records from "example" table
If($sql){ $sql=”select * from example ";
// Retrieving all records from "example" table $result=mysqli_query($connection,$sql) ;
$sql2="select * from example"; If($result){
$result=mysql_query($sql2,$connection) ; //Displaying the values using a table
If($result){//Displaying the values using a table echo “<table border=1><tr><th>Id</th>”;
echo "<table border=1><tr><th>Id</th>"; echo “<th>Name</th><th>Age</th></tr>”;
echo "<th>Name</th><th>Age</th></tr>"; While($row=mysqli_fetch_assoc($result))
While($row=mysql_fetch_array($result)) {
{ echo "<tr><td>".$row['id']."</td>"; echo “<tr><td>”.$row[‘id’].”</td>”;
echo "<td>".$row['name']."</td>"; echo “<td>”.$row[‘name’].”</td>”;
echo "<td>".$row['age']."</td></tr>"; echo “<td>”.$row[‘age’].”</td></tr>”;
} }
echo "</table>"; echo “</table>”;
}else }else
die("Record Not Selected:".mysql_error()); die(“Record Not Selected:”.mysqli_error($connection));
} else }else{
die("Database not die(“Connection Failed:”.mysqli_error($connection));

Page 9 of 15 Departments of Software Engineering By Alehegn E.


Server-Side Web System Design and Programming BahirDar, 2012E.C

selected:".mysql_error()); }
}else{ mysqli_close($connection);//closing connection
die("Connection Failed:".mysql_error());
} ?>

?>

Output:

When you select items from a database using mysql_query, the data is returned as a MySQL
result. Since we want to use this data in our table we need to store it in a variable. $result now
holds the result from our mysql_query.

The mysql_fetch_array function gets the next-in-line associative/numeric array from a MySQL
result. The mysql_fetch_row function gets the next-in-line numeric array from a MySQL result.
The mysqli_fetch_assoc function gets the next-in-line associative array from a MySQL result.
By putting it in a while loop it will continue to fetch the next array until there is no next array to
fetch. This function can be called as many times as you want, but it will return FALSE when the
last associative array has already been returned.

By placing this function within the conditional statement of the while loop,

 We can retrieve the next associative array from our MySQL Resource, $result, so that we
can print out the id, name and age of that person.
 We can tell the while loop to stop printing out information when the MySQL Resource
has returned the last array, as False is returned when it reaches the end and this will cause
the while loop to halt.

In our MySQL table "example" there are only three fields: id, name and age. These fields are the
keys to extracting the data from our associative array. To get the id, name and age we use
$row[‘id’], $row['name'] and $row['age'] respectively. The html table tag is used to let the output
look better. The above select statement retrieves everything from the example table. If you want
to retrieve specific record, you can use where clause in the select statement. For example:
mysql_query(“select * from example where id=1”);

Page 10 of 15 Departments of Software Engineering By Alehegn E.


Server-Side Web System Design and Programming BahirDar, 2012E.C

Modify/Updating Existing Data

Imagine that you have a MySQL table that holds the information of all the employees in your
company. One of the columns in this table is called "Seniority" and it holds an integer value of
how many months an employee has worked at your company. Unfortunately for you, your job is
to update these numbers every month.

You may be thinking that you'll have to open up your MySQL administration tool and edit each
entry by hand. That would take hours. On the other hand, you could master MySQL and have an
automated script that you run each month to get the job done for you.

The UPDATE statement is used to update existing records in a table.

Syntax
UPDATE table_name SET column1=value, column2=value2,... WHERE some_column=some_value

Example: In the example table we have 4 records. The person whose has an id number of 4 is
turned to 17. So change the persons age accordingly.

Example Using : mysql Example Using : mysqli


<?php <?php
// Make a MySQL Connection // Make a MySQL Connection
$connection=mysql_connect("localhost", "root", ""); $connection=mysqli_connect("localhost", "root", "","test”);
If($connection){ If($connection){
$sql=mysql_select_db("test"); // Updating record
If($sql){ $sql=”update example set age=17 where id=4 ";
// Updating record $result=mysqli_query($connection,$sql) ;
$sql2=" update example set age=17 where id=4 "; If($result){
$result=mysql_query($sql2,$connection) ; echo “Age successfully updated!”;
If($result){ }else
echo “Age successfully updated!”; die(“Record Not Updated:”.mysqli_error($connection));
}else }else{
die("Record Not updated:".mysql_error()); die(“Connection Failed:”.mysqli_error($connection));
} else }
die("Database not selected:".mysql_error()); mysqli_close($connection);//closing connection
}else{
die("Connection Failed:".mysql_error()); ?>

}
?>

Page 11 of 15 Departments of Software Engineering By Alehegn E.


Server-Side Web System Design and Programming BahirDar, 2012E.C

Output:

Age successfully updated!

In the above example:

 UPDATE - Performs an update MySQL query


 SET - The new values to be placed into the table follow SET
 WHERE - Limits which rows are affected

Remove Existing Data

Maintenance is a very common task that is necessary for keeping MySQL tables current. From
time to time, you may even need to delete items from your database. Some potential reasons for
deleting a record from MySQL include when: someone deletes a post from a forum.

The DELETE query is very similar to the UPDATE Query. We need to choose a table, tell
MySQL to perform the deletion, and provide the requirements that a record must have for it to be
deleted.

Syntax:

DELETE from table_name where column_name comparison_operator value

For example: delete all records in which age is below 18.

Example Using : mysql Example Using : mysqli


<?php <?php
// Make a MySQL Connection // Make a MySQL Connection
$connection=mysql_connect("localhost", "root", ""); $connection=mysqli_connect("localhost", "root", "","test”);
If($connection){ If($connection){
$sql=mysql_select_db("test"); // Updating records
If($sql){ $sql=” delete from example where age<18";
// deleting records $result=mysqli_query($connection,$sql) ;
$sql2="delete from example where age<18 "; If($result){
$result=mysql_query($sql2,$connection) ; echo “Records Deleted!”;
If($result){ }else
echo “Records Deleted!”; die(“Record Not Deleted:”.mysqli_error($connection));
}else }else{
die("Record Not deleted:".mysql_error()); die(“Connection Failed:”.mysqli_error($connection));

Page 12 of 15 Departments of Software Engineering By Alehegn E.


Server-Side Web System Design and Programming BahirDar, 2012E.C

} else }
die("Database not selected:".mysql_error()); mysqli_close($connection);//closing connection
}else{
die("Connection Failed:".mysql_error()); ?>

}
?>

Output:

Records Deleted!

Data base security using server side scripting

Nowadays, databases are cardinal components of any web based application by enabling
websites to provide varying dynamic content. Since very sensitive or secret information can be
stored in a database, you should strongly consider protecting your databases.

To retrieve or to store any information you need to connect to the database, send a legitimate
query, fetch the result, and close the connection.

Encryption in PHP

Once an attacker gains access to your database directly (bypassing the web server), stored
sensitive data may be exposed or misused, unless the information is protected by the database
itself. Encrypting the data is a good way to mitigate this threat, but very few databases offer this
type of data encryption.

The easiest way to work around this problem is to first create your own encryption package, and
then use it from within your PHP scripts. PHP provides us with different types of encryptions
such as: md5, sha1, hash, crypt, hashed_password etc.

Example:
<?php
$pass="12345678";
echo "md5 encryption $pass=".md5($pass)."<br>";
echo "sha1 encryption $pass=".sha1($pass)."<br>";
echo "hash encryption $pass=".hash('sha1',$pass)."<br>";
echo "crypt encryption $pass=".crypt($pass,$salt);
?>

Output:

Page 13 of 15 Departments of Software Engineering By Alehegn E.


Server-Side Web System Design and Programming BahirDar, 2012E.C

md5 encryption 12345678=25d55ad283aa400af464c76d713c07ad


sha1 encryption 12345678=7c222fb2927d828af22f592134e8932480637c0d
hash encryption 12345678=7c222fb2927d828af22f592134e8932480637c0d
crypt encryption 12345678=$1$.90.tj5.$CG0sUopGFc1ADWxBqDjPu.

In the above example, the salt parameter is optional. However, crypt () creates a weak password
without the salt. Make sure to specify a strong enough salt for better security.

SQL Injection

SQL injection attacks are extremely simple to defend against, but many applications are still
vulnerable. Consider the following SQL statement:
<?php
$sql = "INSERT INTO users (reg_username,reg_password,reg_email) VALUES ('{$_POST['reg_username']}',
'$reg_password', '{$_POST['reg_email']}')";
?>

This query is constructed with $_POST, which should immediately look suspicious.

Assume that this query is creating a new account. The user provides a desired username and an
email address. The registration application generates a temporary password and emails it to the
user to verify the email address. Imagine that the user enters the following as a username:
bad_guy', 'mypass', ''), ('good_guy

This certainly doesn't look like a valid username, but with no data filtering in place, the
application can't tell. If a valid email address is given ([email protected], for example),
and 1234 is what the application generates for the password, the SQL statement becomes the
following:
<?php
$sql = "INSERT INTO users (reg_username,reg_password,reg_email) VALUES ('bad_guy', 'mypass', ''),
('good_guy','1234',
'[email protected]')";
?>

Rather than the intended action of creating a single account (good_guy) with a valid email
address, the application has been tricked into creating two accounts, and the user supplied every
detail of the bad_guy account.

Page 14 of 15 Departments of Software Engineering By Alehegn E.


Server-Side Web System Design and Programming BahirDar, 2012E.C

While this particular example might not seem so harmful, it should be clear that worse things
could happen once an attacker can make modifications to your SQL statements.

For example, depending on the database you are using, it might be possible to send multiple
queries to the database server in a single call. Thus, a user can potentially terminate the existing
query with a semicolon and follow this with a query of the user's choosing.

MySQL, until recently, does not allow multiple queries, so this particular risk is mitigated.
Newer versions of MySQL allow multiple queries, but the corresponding PHP extension
(ext/mysqli) requires that you use a separate function if you want to send multiple queries
(mysqli_multi_query() instead of mysqli_query()). Only allowing a single query is safer,
because it limits what an attacker can potentially do.

Protecting against SQL injection is easy:

 Filter your data: This cannot be overstressed. With good data filtering in place, most
security concerns are mitigated, and some are practically eliminated.
 Quote your data: If your database allows it (MySQL does), put single quotes around all
values in your SQL statements, regardless of the data type.
 Escape your data: Sometimes valid data can unintentionally interfere with the format of
the SQL statement itself. Use mysql_escape_string() or mysqli_real_escape_string() an
escaping function native to your particular database. If there isn't a specific
one, addslashes() is a good last resort.

Page 15 of 15 Departments of Software Engineering By Alehegn E.


Server-Side Web System Design and Programming BahirDar, 2012E.C

Chapter Four

4. PHP File Inclusion, Cookies and Sessions

4.1. File inclusions

You can include the content of a PHP file into another PHP file before the server executes it.
There are two PHP functions which can be used to include one PHP file into another PHP file.

 include() Function
 require() Function

This is a strong point of PHP which helps in creating functions, headers, footers, or elements that
can be reused on multiple pages. This will help developers to make it easy to change the layout
of complete website with minimal effort. If there is any change required then instead of changing
thousands of files just change included file.

include () Function

The include() function takes all the text in a specified file and copies it into the file that uses the
include function. If there is any problem in loading a file then the include () function generates a
warning but the script will continue execution.

Assume you want to create a common menu for your website. Then create a file menu.php with
the following content.
|<a href="index.php">Home</a>||
<a href="feedback.php">Feedback</a>||
<a href="login.php">Login</a>|
Now create as many pages as you like and include this file to create header. For example now
your test.php file can have following content.
<html>
<body>
<?php include("menu.php"); ?>
<p>This is an example to show how to include PHP file!</p>
</body>
</html>
This will produce the following result:
|Home||Feedback||Login|
This is an example to show how to include PHP file.
You can include menu.php file in as many as files you like!

Page 1 of 8 Departments of Software Engineering By Alehegn E.


Server-Side Web System Design and Programming BahirDar, 2012E.C

require() Function

The require() function takes all the text in a specified file and copies it into the file that uses the
require function. If there is any problem in loading a file then the require() function generates a
fatal error and halt the execution of the script.

So there is no difference in require() and include() except they handle error conditions. It is
recommended to use the require() function instead of include(), because scripts should not
continue executing if files are missing or misnamed.

You can try using above example with require() function and it will generate same result. But if
you will try following two examples where file does not exist then you will get different results.
<html> <body>
<?php include("xxmenu.php"); ?>
<p>This is an example to show how to include wrong PHP file!</p>
</body> </html>
This will produce the following result:
This is an example to show how to include wrong PHP file!
Now lets try same example with require() function.
<html> <body>
<?php require("xxmenu.php"); ?>
<p>This is an example to show how to include wrong PHP file!</p>
</body> </html>
This time file execution halts and nothing is displayed.

NOTE: You may get plain warning messages or fatal error messages or nothing at all. This
depends on your PHP Server configuration.

PHP require_once()

require_once() statement can be used to include a php file in another one, when you may need to
include the called file more than once. If it is found that the file has already been included,
calling script is going to ignore further inclusions.

If a.php is a php script calling b.php with require_once() statement, and does not find b.php,
a.php stops execution causing a fatal error.

Syntax
require_once('name of the calling file with path');
Example :
<?php
echo "today is:".date("Y-m-d");
?>

Page 2 of 8 Departments of Software Engineering By Alehegn E.


Server-Side Web System Design and Programming BahirDar, 2012E.C

The above file is x.php

The above file x.php, is included twice with require_once() statement in the following file y.php.
But from the output you will get that the second instance of inclusion is ignored, since
require_once() statement ignores all the similar inclusions after the first one.
<?php
require_once('x.php');
require_once('x.php');
?>
Output: today is:2016-05-27
If a calling script does not find a called script with require_once statement, it halts the execution
of the calling script.

PHP include_once()

The include_once() statement can be used to include a php file in another one, when you may
need to include the called file more than once. If it is found that the file has already been
included, calling script is going to ignore further inclusions.

If a.php is a php script calling b.php with include_once() statement, and does not find b.php,
a.php executes with a warning, excluding the part of the code written within b.php.

Syntax
include_once('name of the called file with path');
Example :
<?php
echo "today is:".date("Y-m-d");
?>
The above file is x.php

The above file x.php, is included twice with include_once() statement in the following file y.php.
But from the output you will get that the second instance of inclusion is ignored, since
include_once() statement ignores all the the similar inclusions after the first one.
<?php
include_once('x.php');
include_once('x.php');
?>
Output: today is:2016-05-27

If a calling script does not find a called script with include_once statement, it halts the execution
of the calling script.
Page 3 of 8 Departments of Software Engineering By Alehegn E.
Server-Side Web System Design and Programming BahirDar, 2012E.C

4.2. Cookies

A client can visit and load a website several times. If so, there should be certain mechanism to
remember the previous instances of it being requested by a client. This leads to persistency of
files or data.
As discussed in IP-I, http is a stateless protocol. It remembers nothing about previous transfers.

A cookie is a packet of informationsent from the server to client, and then sent back to the server
each time. Or cookies are text files stored on the client computer and they are kept of use
tracking purpose. PHP transparently supports HTTP cookies.

There are three steps involved in identifying returning users:

 Server script sends a set of cookies to the browser. For example name, age, or
identification number etc.
 Browser stores this information on local machine for future use.
 When next time browser sends any request to web server then it sends those cookies
information to the server and server uses that information to identify the user.

The Anatomy of a Cookie

Cookies are usually set in an HTTP header (although JavaScript can also set a cookie directly on
a browser). A PHP script that sets a cookie might send headers that look something like this:
HTTP/1.1 200 OK
Date: Fri, 04 Feb 2000 21:03:38 GMT
Server: Apache/1.3.9 (UNIX) PHP/4.0b3
Set-Cookie: name=xyz; expires=Friday, 04-Feb-07 22:03:38 GMT;
path=/; domain=tutorialspoint.com
Connection: close
Content-Type: text/html

Page 4 of 8 Departments of Software Engineering By Alehegn E.


Server-Side Web System Design and Programming BahirDar, 2012E.C

As you can see, the Set-Cookie header contains a name value pair, a GMT date, a path and a
domain. The name and value will be URL encoded. The expires field is an instruction to the
browser to "forget" the cookie after the given time and date.

If the browser is configured to store cookies, it will then keep this information until the expiry
date. If the user points the browser at any page that matches the path and domain of the cookie, it
will resend the cookie to the server. The browser's headers might look something like this:
GET / HTTP/1.0
Connection: Keep-Alive
User-Agent: Mozilla/4.6 (X11; I; Linux 2.2.6-15apmac ppc)
Host: zink.demon.co.uk:1126
Accept: image/gif, */*
Accept-Encoding: gzip
Accept-Language: en
Accept-Charset: iso-8859-1,*,utf-8
Cookie: name=xyz
A PHP script will then have access to the cookie in the environmental variables $_COOKIE or
$HTTP_COOKIE_VARS[] which holds all cookie names and values. Above cookie can be
accessed using $HTTP_COOKIE_VARS["name"].

Setting Cookies with PHP

PHP provided setcookie() function to set a cookie. This function requires up to six arguments
and should be called before <html> tag. For each cookie this function has to be called separately.
setcookie(name, value, expire, path, domain, security);
Here is the detail of all the arguments:

 Name - This sets the name of the cookie and is stored in an environment variable called
HTTP_COOKIE_VARS. This variable is used while accessing cookies.
 Value -This sets the value of the named variable and is the content that you actually want
to store.
 Expiry - This specify a future time in seconds since 00:00:00 GMT on 1st Jan 1970.
After this time cookie will become inaccessible. If this parameter is not set then cookie
will automatically expire when the Web Browser is closed.
 Path -This specifies the directories for which the cookie is valid. A single forward slash
character permits the cookie to be valid for all directories.
 Domain - This can be used to specify the domain name in very large domains and must
contain at least two periods to be valid. All cookies are only valid for the host and domain
which created them.
Page 5 of 8 Departments of Software Engineering By Alehegn E.
Server-Side Web System Design and Programming BahirDar, 2012E.C

 Security - This can be set to 1 to specify that the cookie should only be sent by secure
transmission using HTTPS otherwise set to 0 which mean cookie can be sent by regular
HTTP.

The following example will create two cookies name and age. These cookies will expire after an
hour.
<?php
setcookie("name", "Abebawabibual", time()+3600, "/","", 0);
setcookie("age", "36", time()+3600, "/", "", 0);
?>
<html><head><title>Setting Cookies with PHP</title></head>
<body>
<?php echo "Set Cookies"?>
</body></html>
Accessing Cookies with PHP

PHP provides many ways to access cookies. The simplest way is to use either $_COOKIE or
$HTTP_COOKIE_VARS variables. Following example will access all the cookies set in above
example.

<html><head><title>Accessing Cookies with PHP</title></head>


<body>
<?php
echo $_COOKIE["name"]. "<br />";
/* is equivalent to */
echo $HTTP_COOKIE_VARS["name"]. "<br />";
echo $_COOKIE["age"] . "<br />";
/* is equivalent to */
echo $HTTP_COOKIE_VARS["age"] . "<br />";
?>
</body></html>
You can use isset() function to check if a cookie is set or not.
<html><head><title>Accessing Cookies with PHP</title></head><body>
<?php
if(isset($_COOKIE["name"]))
echo "Welcome " . $_COOKIE["name"] . "<br />";
else
echo "Sorry... Not recognized" . "<br />";
?>
</body></html>
Deleting Cookie with PHP

Officially, to delete a cookie you should call setcookie() with the name argument only but this
does not always work well, however, and should not be relied on. It is safest to set the cookie
with a date that has already expired:

Page 6 of 8 Departments of Software Engineering By Alehegn E.


Server-Side Web System Design and Programming BahirDar, 2012E.C

<?php
setcookie( "name", "", time()- 60, "/","", 0);
setcookie( "age", "", time()- 60, "/","", 0);
?>
<html><head><title>Deleting Cookies with PHP</title></head>
<body>
<?php echo "Deleted Cookies" ?>
</body></html>

4.3. Sessions

An alternative way to make data accessible across the various pages of an entire website is to use
a PHP Session.

A session creates a file in a temporary directory on the server where registered session variables
and their values are stored. This data will be available to all pages on the site during that visit.

The location of the temporary file is determined by a setting in the php.ini file called
session.save_path. Before using any session variable make sure you have setup this path.

When a session is started, the following actions take place:

 PHP first creates a unique identifier for that particular session which is a random string of
32 hexadecimal numbers such as 3c7foj34c3jj973hjkop2fc937e3443.
 A cookie called PHPSESSID is automatically sent to the user's computer to store unique
session identification string.
 A file is automatically created on the server in the designated temporary directory and
bears the name of the unique identifier prefixed by sess_ ie
sess_3c7foj34c3jj973hjkop2fc937e3443.

When a PHP script wants to retrieve the value from a session variable, PHP automatically gets
the unique session identifier string from the PHPSESSID cookie and then looks in its temporary
directory for the file bearing that name and a validation can be done by comparing both values.

A session ends when the user loses the browser or after leaving the site, the server will terminate
the session after a predetermined period of time, commonly 30 minutes duration.

Starting a PHP Session

A PHP session is easily started by making a call to the session_start() function. This function
first checks if a session is already started and if none is started then it starts one. It is
recommended to put the call to session_start() at the beginning of the page.

Page 7 of 8 Departments of Software Engineering By Alehegn E.


Server-Side Web System Design and Programming BahirDar, 2012E.C

Session variables are stored in associative array called $_SESSION[]. These variables can be
accessed during lifetime of a session.

The following example starts a session and then registers a variable called counter that is
incremented each time the page is visited during the session.

 Make use of isset() function to check if session variable is already set or not.
 Put this code in a test.php file and load this file many times to see the result:
<?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>
Destroying a PHP Session

A PHP session can be destroyed by session_destroy() function. This function does not need any
argument and a single call can destroy all the session variables. If you want to destroy a single
session variable then you can use unset () function to unset a session variable.

Here is the example to unset a single variable:


<?php
unset($_SESSION['counter']);
?>
Here is the call which will destroy all the session variables:
<?php
session_destroy();
?>

Page 8 of 8 Departments of Software Engineering By Alehegn E.


Server-Side Web System Design and Programming BahirDar, 2012E.C

Chapter Five

5. Files and Directories

5.1. Reading files/ Directories


Files and directories have three levels of access: User, Group and Other. The three typical
permissions for files and directories are:

 Read (r)
 Write (w)
 Execute (x)

A stream is a channel used for accessing a resource that you can read from and write to. The
input stream reads data from a resource (such as a file) while the output stream writes data to a
resource. In file operation, we do have the following steps or procedures:-

1. Open the file stream with the fopen() function


Syntax:- variable= fopen(“text file”, “mode”); where mode mean r, r+, w, w+ etc as
shown in the next page.
2. Write data to or read data from the file stream
 We use fread(($filepointer,”filesize”) function to read files or data.. We can also use
fgets() function to read files or data. It is written with two parameters like
fgets($filepointer,”filesize”)
o Reads up to $bytes of data, stops at newline or end of file (EOF)
 PHP supports two basic functions for writing data to text files:
o file_put_contents() function writes or appends a text string to a file. Its syntax for
the file_put_contents() function is: file_put_contents (filename, string[, options]
o fwrite() function incrementally writes data to a text file. Its syntax for the fwrite()
function is: fwrite($handle, data[, length]);
3. Close the file stream with the fclose() function:- used when finished working with a file
stream to save space in memory.
Syntax:- fclose(file name that contains the opened files);

Example:- $handle = fopen('people.txt', 'r');

while (!feof($handle)) {
echo fgets($handle, 1024);
echo '<br />';

Page 1 of 13 Departments of Software Engineering By Alehegn E.


Server-Side Web System Design and Programming BahirDar, 2012E.C

} fclose($handle);

Files modes can be specified as one of the six options in this table.

Mode Purpose

r Opens the file for reading only. Places the file pointer at the beginning of the file.

r+ Opens the file for reading and writing. Places the file pointer at the beginning of the file.

Opens the file for writing only. Places the file pointer at the beginning of the file and
w
truncates the file to zero length. If files does not exist then it attempts to create a file.

Opens the file for reading and writing only. Places the file pointer at the beginning of the
w+ file and truncates the file to zero length. If file does not exist then it attempts to create a
file.

Opens the file for writing only. Places the file pointer at the end of the file. If files does
a
not exist then it attempts to create a file.

Opens the file for reading and writing only. Places the file pointer at the end of the file. If
a+
files does not exist then it attempts to create a file.

Once a file is opened using fopen() function it can be read with a function called fread(). This
function requires two arguments. These must be the file pointer and the length of the file
expressed in bytes.

The files's length can be found using the filesize() function which takes the file name as its
argument and returns the size of the file expressed in bytes. So here are the steps required to read
a file with PHP.

 Open a file using fopen() function.


 Get the file's length using filesize() function.
 Read the file's content using fread() function.
 Close the file with fclose() function.

The following example assigns the content of a text file to a variable then displays those contents
on the web page.

<html><head><title>Reading a file using PHP</title></head><body>


<?php
$filename = "/home/user/guest/tmp.txt";

Page 2 of 13 Departments of Software Engineering By Alehegn E.


Server-Side Web System Design and Programming BahirDar, 2012E.C

$file = fopen( $filename, "r" );


if( $file == false )
{
echo ( "Error in opening file" );
exit();
}
$filesize = filesize( $filename );
$filetext = fread( $file, $filesize );
fclose( $file );
echo ( "File size : $filesize bytes" );
echo ( "<pre>$filetext</pre>" );
?>
</body></html>

Note That:- There are two „shortcut‟ functions that don‟t require a file to be opened:

 $lines = file($filename) :Reads entire file into an array with each line a separate entry in
the array.
 $str = file_get_contents($filename) :Reads entire file into a single string.

4.1. Writing a File


A new file can be written or text can be appended to an existing file using the PHP function as
discus in the previous discussions. These functions require two arguments specifying a file
pointer and the string of data that is to be written. Optionally a third integer argument can be
included to specify the length of the data to write. If the third argument is included, writing
would will stop after the specified length has been reached. The following is the syntax to write
files:-

fwrite(file we write on it, string what we write[,length of string])

The following example creates a new text file then writes a short text heading inside it. After
closing this file its existence is confirmed using file_exists() function which takes file name as an
argument. See the following example how open file, write in file and close files

<?php
$filename = "/home/user/guest/newfile.txt";
$file = fopen( $filename, "w" );
if( $file == false )

Page 3 of 13 Departments of Software Engineering By Alehegn E.


Server-Side Web System Design and Programming BahirDar, 2012E.C

{
echo ( "Error in opening new file" );
exit();
}
fwrite( $file, "This is a simple test\n" );
fclose( $file );
?>
<html><head><title>Writing a file using PHP</title></head><body>
<?php
if( file_exists( $filename ) )
{
$filesize = filesize( $filename );
$msg = "File created with name $filename ";
$msg .= "containing $filesize bytes";
echo ($msg );
}
else
echo ("File $filename does not exit" );
?>
</body></html>

If an attempt to open a file fails then fopen returns a value of false otherwise it returns a file
pointer which is used for further reading or writing to that file.

After making a changes to the opened file it is important to close it with the fclose() function.
The fclose() function requires a file pointer as its argument and then returns true when the
closure succeeds or false if it fails.

Note that:-

 The file_put_contents() function can also writes or appends a text string to a file, doesn‟t
need to use fopen or fclose. If no data was written to the file, the function returns a value
of 0 which can determine if data was successfully written to the file. The FILE_APPEND
constant appends data to any existing contents in the specified filename instead of
overwriting it

Example:- This example shows costsharing payment system

<html><body>
<h1>Coast sharing payment system</h1>

Page 4 of 13 Departments of Software Engineering By Alehegn E.


Server-Side Web System Design and Programming BahirDar, 2012E.C

<?php
if (isset($_GET['first_name']) && isset($_GET['last_name'])) {
$First = $_GET['first_name'];
$Last = $_GET['last_name'];
$New= $Last . ", " . "$First" . "\n";
$x = "bowlers.txt";
if (file_put_contents($x, $New, FILE_APPEND) > 0)
echo "<p>{$_GET['first_name']} {$_GET['last_name']} has been registered for the payment!</p>";
else
echo "<p>Registration error!</p>";
}
else{
echo "<p>To sign up for the cost sharing system, enter your first
and last name and click the Register button.</p>";
if(!empty($_GET['first_name']))
echo $_GET['first_name'];
if(!$_GET['last_name'])
echo $_GET['last_name'];}
?>
<form action="<?php $_PHP_SELF ?>" method="get" enctype="application/x-www-form-urlencoded">
<p>First Name: <input type="text" name="first_name" size="30" /></p>
<p>Last Name: <input type="text" name="last_name" size="30" /></p>
<p><input type="submit" value="Register" /></p>
</form></body></html >

In general;

 To write files incrementally, use the fwrite() function


 fclose() closes a file.
 fgetc() reads a single character
 feof() determines if the end is true.
 fgets() reads a line of data
 file() reads entire file into an array

See the following examples

Page 5 of 13 Departments of Software Engineering By Alehegn E.


Server-Side Web System Design and Programming BahirDar, 2012E.C

Example 3:

<?php

Example 1:- $lines = file('welcome.txt');


foreach ($lines as $l_num => $line)
<?php
{
$myFile = "welcome.txt";
echo "Line #{$l_num}:“ .$line.”<br/>”;
if (!($fh=fopen($myFile,'r')))
}
exit("Unable to open file.");
?>
while (!feof($fh))
{ Example 4:-
$x=fgetc($fh); <?php
echo $x; $myFile = "testFile.txt";
} $fh = fopen($myFile, 'a') or die("can't open
fclose($fh); file");
?> $stringData = "New Stuff 1\n";

Example 2 fwrite($fh, $stringData);


$stringData = "New Stuff 2\n";
<?php
fwrite($fh, $stringData);
$myFile = "welcome.txt";
fclose($fh); ?>
$fh = fopen($myFile, 'r');
$theData = fgets($fh);
fclose($fh);
echo $theData;?>

Locking Files

 To prevent multiple users from modifying a file simultaneously use the flock() function
 The syntax for the flock() function is:flock($handle, operation) where operations could
be LOCK_EX, LOCK_NB, etc. The followings are possible file lock functions and their
descriptions.

Page 6 of 13 Departments of Software Engineering By Alehegn E.


Server-Side Web System Design and Programming BahirDar, 2012E.C

Reading an Entire File

Copying Files

 Use the copy() function to copy a file with PHP


 The function returns a value of true if it is successful or false if it is not
 The syntax for the copy() function is: copy(source, destination)
 For the source and destination arguments:
o Include just the name of a file to make a copy in the current directory, or
o Specify the entire path for each argument

Example:-
if (file_exists(“a.txt”)) {
if(is_dir(“history”)) {
if (copy(“a.txt”,“history\\b.txt”))
echo “<p>File copied successfully.</p>”;
else
echo “<p>Unable to copy the file!</p>”; }
else

Page 7 of 13 Departments of Software Engineering By Alehegn E.


Server-Side Web System Design and Programming BahirDar, 2012E.C

echo (“<p>The directory does not exist!</p>”);}


else
echo (“<p>The file does not exist!</p>”);

5.2. Create Directories


Basic functions/methods that are used to open directories, read directories and close directories
are;-
o To iterate through the entries in a directory, open a handle to the directory with the
opendir() function
o Use the readdir() function to return the file and directory names from the open directory
o Use the closedir() function to close a directory handle

Example 1:- This is used to demonstrate how gare directory contents of files are displayed.
<?php

$Dir = "C:\\gare";

$DirOpen = opendir($Dir);

while ($CurFile = readdir($DirOpen)) {

echo $CurFile . "<br />";

closedir($DirOpen);

?>

Example 2:- The following example shows how the content of the current directory opened

$handle = opendir('./');

while(false !== ($file=readdir($handle)))

{ echo "$file<br />";

closedir($handle);

There are also different functions which have different purposes. Some of them are listed below:-

Page 8 of 13 Departments of Software Engineering By Alehegn E.


Server-Side Web System Design and Programming BahirDar, 2012E.C

To create directories:-

Use the mkdir() function to create a new directory. To create a new directory pass just the name
of the directory we want to create to the mkdir() function.

Example
mkdir(“bowlers”);
mkdir(“..\\tournament”);
mkdir(“C:\\PHP\\utilities”);
Warning will appear if directory already exists
Example:-
<?php
$Dir = "C:\\Wamp";
if(is_dir($Dir)) {
echo "<table border='1‘ width='100%'>";
echo "<tr><th>Filename</th><th>File Size</th>
<th>File Type</th></tr>";
$DirEntries = scandir($Dir);
foreach ($DirEntries as $Entry) {
echo "<tr><td>$Entry</td><td>" . filesize($Dir . "\\"
. $Entry) . "</td><td>" . filetype($Dir . "\\"
. $Entry) . "</td></tr>";
}
echo "</table>";
Page 9 of 13 Departments of Software Engineering By Alehegn E.
Server-Side Web System Design and Programming BahirDar, 2012E.C

}
else echo "<p>The directory does not exist.</p>";
?>

5.3. Rename and Delete Files and Directories

 Use the rename() function to rename a file or directory with PHP. This function returns a
value of true if it is successful or false if it is not

o The syntax is: rename(old_name, new_name)


 Use the unlink() function to delete files and the rmdir() function to delete directories
 Pass the name of a file to the unlink() function and the name of a directory to the rmdir()
function. Both functions return a value of true if successful or false if not
o Use the file_exists() function to determine whether a file or directory name exists
before we attempt to delete it

5.4. Upload Files


Web applications allow visitors to upload files to and from their local computer. The files that
are uploaded and downloaded may be simple text files or more complex file types, such as
images, documents, or spreadsheets.

Files are uploaded through an HTML form using the “post” method and enctype attribute with
value of “multipart/form-data,” which instructs the browser to post multiple sections – one for
regular form data and one for the file contents. The file input field creates a browser button for
the user to navigate to the appropriate file to upload

<form method=”post” action=” ” enctype= multipart/form-data >


<input type="file" name="picture_file" />
</form>

The MAX_FILE_SIZE (uppercase) attribute of a hidden form field specifies the maximum
number of bytes allowed in the uploaded file and it must appear before the file input field.

When the form is posted, information for the uploaded file is stored in the $_FILES auto global
array.

The $_FILES[] array contains five elements:

a. // Contains the error code associated with the file


$_FILES['picture_file']['error']
b. // Contains the temporary location of the file
Page 10 of 13 Departments of Software Engineering By Alehegn E.
Server-Side Web System Design and Programming BahirDar, 2012E.C

$_FILES['picture_file']['tmp_name'] contents
c. // Contains the name of the original file
$_FILES['picture_file']['name']
d. // Contains the size of the uploaded file in bytes
$_FILES['picture_file']['size']
e. // Contains the type of the file
$_FILES['picture_file']['type']
Example:-The following HTM code below creates an upload form. This form is having
method attribute set to post and enctype attribute is set to multipart/form-data

<html><body><h3>File Upload:</h3>
Select a file to upload: <br />
<form action="<?php $_PHP_SELF ?>" method="post" enctype="multipart/form-data">
<input type="file" name="photo" required=””/><br />
<input type="submit" value="Upload File" />
</form></body></html>
<?php
$filename=$_FILES['photo']['name'];
$filetmpname=$_FILES['photo']['tmp_name'];
$target="uploadedfiles/".$_FILES['photo']['name'];
if(!file_exists("uploadedfiles"))
mkdir("uploadedfiles");
if( copy($_FILES['photo']['tmp_name'], $target) or die( "Could not copy file!"))
echo "file uploded successfully";
else
die("unable to upload!");
?>
<h2>Uploaded File Info:</h2>
<ul><li>Sent file: <?php echo $_FILES['photo']['name']; ?>
<li>File size: <?php echo $_FILES['photo']['size']; ?> bytes
<li>File type: <?php echo $_FILES['photo']['type']; ?>
</ul><a href=<?php echo $target; ?>>Click here to open</a></body></html>

Example2: Inserting the above file to a database: First create a table with two columns such as
id(int auto increment) and file_path (varchar(50)).

<?php
$server="localhost";

Page 11 of 13 Departments of Software Engineering By Alehegn E.


Server-Side Web System Design and Programming BahirDar, 2012E.C

$dbuser="root";
$dbpass="";
$dbname="sims";
$connection = mysql_connect($server, $dbuser, $dbpass) or die("Couldn't make connection.");
$db = mysql_select_db($dbname, $connection) or die("Couldn't select database");
?><html><body><h3>File Upload:</h3>
Select a file to upload: <br />
<form action="<?php $_PHP_SELF ?>" method="post" enctype="multipart/form-data">
<input type="file" name="photo" required=""/><br />
<input type="submit" value="Upload File" name="upload" />
</form></body></html>
<?php
if(isset($_POST['upload']))
{
$filename=$_FILES['photo']['name'];
$filetmpname=$_FILES['photo']['tmp_name'];
$target="uploadedfiles/".$_FILES['photo']['name'];
if(!file_exists("uploadedfiles"))
mkdir("uploadedfiles");
//uploading a file into uploadedfiles folder
if(copy($_FILES['photo']['tmp_name'], $target) or die( "Could not copy file!"))
{
//inserting a file to a file table in sims database
$result = mysql_query("INSERT INTO file(file_path) VALUE ('$target')");
if(!$result)
{
echo "File uploaded successfully";
}
//retrieving records from file table
$result = mysql_query("select * from file");
echo "<table border=1><tr><th>Id</th><th>File</th></tr>";
while($row=mysql_fetch_array($result))
{
echo "<tr><th>".$row['id']."</th><th><a href='".$row['file_path']."'>".$row['file_path']."</a></th></tr>";
}
echo "</table>";

}else
Page 12 of 13 Departments of Software Engineering By Alehegn E.
Server-Side Web System Design and Programming BahirDar, 2012E.C

echo "Unable to uploaded files";


}
?>
</body></html>

Page 13 of 13 Departments of Software Engineering By Alehegn E.

You might also like