PHP All in One
PHP All in One
Chapter One
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.
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.
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
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:
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
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?
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.
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:
<?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:
%>
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>
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 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!
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";
?>
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";
?>
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.
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.
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.
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;
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:
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);
?>
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.
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.
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
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. ";
?>
Function parameters are declared after the function name and inside parentheses. They are
declared much like a typical variable would be:
<?
// 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";
?>
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();
?>
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++;
print $count;
print " ";
}
keep_track();
keep_track();
keep_track();
?>
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.
There is no need to write a dollar sign ($) before a constant, where as in Variable one has
to write a dollar sign.
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.
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 */ }
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>”; }
Calculating Exponents
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.
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:-
String concatenation operation: - To concatenate two string variables together, use the dot (.)
operator like echo $string1 . " " . $string2;
Substr()-uses to copy strings.
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.
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
End_of_Sketch;
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
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";
Here's how we can insert at the beginning of the string without deleting from original character:
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);
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);
strrev() function:- takes a string and returns a reversed copy of it. Has syntax:-
$string = strrev(string);
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.
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 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.
Example: the following code used to show from where the word “world” started.
<?php
echo strpos("Hello world!","world");
?>
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");
}
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.
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
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 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 above code’s action attribute value can be represented as the filename itself like:-
<form action=”info.php” method=”Get”>
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 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.
<?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
Presence Validation
String Length Validation
Type Validation
Inclusion in set Validation
Uniqueness Validation
Format Validation
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
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.
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)) {
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.
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!";
?>
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!";
?>
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
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 ?";
}
?>
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 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)
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 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>
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);
?>
</body></html>
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
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
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.
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:
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
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:
$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.
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).
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:-
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
<?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);
?>
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).
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
Output:
12 value(s) found:
orange, owl, one, tea, ten, tag, twenty, three, vingt, trois, baron, blood
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.
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.
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.
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:
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.
mysql_connect(server,username,passwd,new_link,client_flag);
There are also functions in PHP which have different purposes. For instance,
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”;
$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);
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
<?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
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
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:
We are now going to design a MySQL query to summon our table from database test.
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:
<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) ;
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
?>
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.
Example:
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”);
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.
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.
}
?>
Output:
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:
} else }
die("Database not selected:".mysql_error()); mysqli_close($connection);//closing connection
}else{
die("Connection Failed:".mysql_error()); ?>
}
?>
Output:
Records Deleted!
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:
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.
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.
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.
Chapter Four
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!
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");
?>
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.
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.
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
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"].
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.
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:
<?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.
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.
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.
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.
Chapter Five
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:-
while (!feof($handle)) {
echo fgets($handle, 1024);
echo '<br />';
} 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.
The following example assigns the content of a text file to a variable then displays those contents
on the web page.
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.
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 )
{
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
<html><body>
<h1>Coast sharing payment system</h1>
<?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;
Example 3:
<?php
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.
Copying Files
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
Example 1:- This is used to demonstrate how gare directory contents of files are displayed.
<?php
$Dir = "C:\\gare";
$DirOpen = opendir($Dir);
closedir($DirOpen);
?>
Example 2:- The following example shows how the content of the current directory opened
$handle = opendir('./');
closedir($handle);
There are also different functions which have different purposes. Some of them are listed below:-
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>";
?>
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
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
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.
$_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";
$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