WT Unit-I
WT Unit-I
Introduction to PHP: Declaring variables, data types, arrays, strings, operators, expressions,
control structures, functions, Reading data from web form controls like text boxes, radio buttons,
lists etc,. Handling File Uploads, Connecting to databases (MySQL as reference), executing
simple queries, handling results, Handling sessions and cookies.
File Handling in PHP: File operations like opening, closing, reading, writing, appending,
deleting etc. on text and binary files, listing directories.
Introduction to PHP :
PHP is an acronym for "PHP: Hypertext Preprocessor"
PHP is a widely-used, open source scripting language
PHP scripts are executed on the server
PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web
pages.
PHP is a widely-used, free, and efficient alternative to competitors such as Microsoft's ASP.
PHP files can contain text, HTML, CSS, JavaScript, and PHP code
PHP code are executed on the server, and the result is returned to the browser as plain
HTML
PHP files have extension ".php"
PHP can generate dynamic page content
PHP can create, open, read, write, delete, and close files on the server
PHP can collect form data
PHP can send and receive cookies
PHP can add, delete, modify data in your database
PHP can be used to control user-access
PHP can encrypt data
PHP runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)
PHP is compatible with almost all servers used today (Apache, IIS, etc.)
PHP supports a wide range of databases
A PHP script is executed on the server, and the plain HTML result is sent back to the browser.
Example
<!DOCTYPE html>
<html>
<body>
<?php
echo "My first PHP script!";
?>
</body>
</html>
OUTPUT:
My first PHP script!
1
Basic PHP Syntax
A PHP script can be placed anywhere in the document.
A PHP script starts with <?php and ends with ?>:
<?php
// PHP code goes here
?>
The default file extension for PHP files is ".php".
A PHP file normally contains HTML tags, and some PHP scripting code.
Below, we have an example of a simple PHP file, with a PHP script that uses a built-in PHP
function "echo" to output the text "Hello World!" on a web page:
Example
<!DOCTYPE html>
<html>
<body>
<h1>My first PHP page</h1>
<?php
echo "Hello World!";
?>
</body>
</html>
Note: PHP statements end with a semicolon (;).
Comments in PHP
Example
<!DOCTYPE html>
<html>
<body>
<?php
// This is a single-line comment
# This is also a single-line comment
/*
This is a multiple-lines comment block
that spans over multiple
lines
*/
// You can also use comments to leave out parts of a code line
$x = 5 /* + 15 */ + 5;
echo $x;
?>
</body>
</html>
In PHP, all keywords (e.g. if, else, while, echo, etc.), classes, functions, and user-defined functions are
NOT case-sensitive.
<!DOCTYPE html>
<html>
<body>
2
<?php
$color = "red";
echo "My car is " . $color . "<br>";
echo "My house is " . $COLOR . "<br>";
echo "My boat is " . $coLOR . "<br>";
?>
</body>
</html>
OUTPUT:
My car is red
My house is
My boat is
Declaring variables:
Example:
<!DOCTYPE html>
<html>
<body>
<?php
$txt = "Hello world!";
$x = 5;
$y = 10.5;
echo $txt;
echo "<br>";
echo $x;
echo "<br>";
echo $y;
?>
</body>
</html>
OUTPUT:
3
Hello world!
5
10.5
Output Variables
The PHP echo statement is often used to output data to the screen.
The following examples will show how to output text and a variable:
Example1:
<!DOCTYPE html>
<html>
<body>
<?php
$txt = "W3Schools.com";
echo "I love $txt!";
?>
</body>
</html>
OUTPUT:
I love W3Schools.com!
Example2:
<!DOCTYPE html>
<html>
<body>
<?php
$txt = "W3Schools.com";
echo "I love " . $txt . "!";
?>
</body>
</html>
OUTPUT:
I love W3Schools.com!
Example3:
<!DOCTYPE html>
<html>
<body>
<?php
$x = 5;
$y = 4;
echo $x + $y;
?>
</body>
</html>
OUTPUT:
9
4
PHP is a Loosely Typed Language
In the example above, notice that we did not have to tell PHP which data type the variable is.
PHP automatically converts the variable to the correct data type, depending on its value.
In other languages such as C, C++, and Java, the programmer must declare the name and type of
the variable before using it.
<!DOCTYPE html>
<html>
<body>
<?php
$x = 5; // global scope
function myTest() {
// using x inside this function will generate an error
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
echo "<p>Variable x outside function is: $x</p>";
?>
</body>
</html>
OUTPUT:
Variable x inside function is:
Variable x outside function is: 5
A variable declared within a function has a LOCAL SCOPE and can only be accessed within that
function:
<!DOCTYPE html>
<html>
<body>
5
<?php
function myTest() {
$x = 5; // local scope
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
// using x outside the function will generate an error
echo "<p>Variable x outside function is: $x</p>";
?>
</body>
</html>
You can have local variables with the same name in different functions, because local variables are only
recognized by the function in which they are declared.
The global keyword is used to access a global variable from within a function.
To do this, use the global keyword before the variables (inside the function):
<!DOCTYPE html>
<html>
<body>
<?php
$x = 5;
$y = 10;
function myTest() {
global $x, $y;
$y = $x + $y;
}
myTest(); // run function
echo $y; // output the new value for variable $y
?>
</body>
</html>
OUTPUT:
15
PHP also stores all global variables in an array called $GLOBALS[index]. The index holds the
name of the variable. This array is also accessible from within functions and can be used to
update global variables directly.
6
<!DOCTYPE html>
<html>
<body>
<?php
$x = 5;
$y = 10;
function myTest() {
$GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y'];
}
myTest();
echo $y;
?>
</body>
</html>
OUTPUT:
15
Normally, when a function is completed/executed, all of its variables are deleted. However,
sometimes we want a local variable NOT to be deleted. We need it for a further job.
To do this, use the static keyword when you first declare the variable:
<!DOCTYPE html>
<html>
<body>
<?php
function myTest() {
static $x = 0;
echo $x;
$x++;
}
myTest();
echo "<br>";
myTest();
echo "<br>";
myTest();
?>
</body>
</html>
OUTPUT:
0
1
2
7
Data Types:
Variables can store data of different types, and different data types can do different things.
String
Integer
Float (floating point numbers - also called double)
Boolean
Array
Object
NULL
Resource
PHP String
A string can be any text inside quotes. You can use single or double quotes:
<!DOCTYPE html>
<html>
<body>
<?php
$x = "Hello world!";
$y = 'Hello world!';
echo $x;
echo "<br>";
echo $y;
?>
</body>
</html>
OUTPUT:
Hello world!
Hello world!
8
PHP Integer
In the following example $x is an integer. The PHP var_dump() function returns the data type
and value:
<!DOCTYPE html>
<html>
<body>
<?php
$x = 5985;
var_dump($x);
?>
</body>
</html>
OUTPUT:
int(5985)
PHP Float
A float (floating point number) is a number with a decimal point or a number in exponential
form.
In the following example $x is a float. The PHP var_dump() function returns the data type and
value:
<!DOCTYPE html>
<html>
<body>
<?php
$x = 10.365;
var_dump($x);
?>
</body>
</html>
OUTPUT:
9
float(10.365)
PHP Boolean
$x = true;
$y = false;
Booleans are often used in conditional testing. You will learn more about conditional testing in a
later chapter of this tutorial.
PHP Array
In the following example $cars is an array. The PHP var_dump() function returns the data type
and value:
<!DOCTYPE html>
<html>
<body>
<?php
$cars = array("Volvo","BMW","Toyota");
var_dump($cars);
?>
</body>
</html>
OUTPUT:
array(3) { [0]=> string(5) "Volvo" [1]=> string(3) "BMW" [2]=> string(6) "Toyota" }
PHP Object
An object is a data type which stores data and information on how to process that data.
First we must declare a class of object. For this, we use the class keyword. A class is a structure
that can contain properties and methods:
<!DOCTYPE html>
<html>
<body>
10
<?php
class Car {
function Car() {
$this->model = "VW";
}
}
// create an object
$herbie = new Car();
</body>
</html>
OUTPUT:
VW
Null is a special data type which can have only one value: NULL.
A variable of data type NULL is a variable that has no value assigned to it.
<!DOCTYPE html>
<html>
<body>
<?php
$x = "Hello world!";
$x = null;
var_dump($x);
?>
</body>
</html>
OUTPUT:
NULL
PHP Resource
The special resource type is not an actual data type. It is the storing of a reference to functions
and resources external to PHP.A common example of using the resource data type is a database
call.We will not talk about the resource type here, since it is an advanced topic.
11
PHP Arrays
An array stores multiple values in one single variable:
<!DOCTYPE html>
<html>
<body>
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
</body>
</html>
OUTPUT:
I like Volvo, BMW and Toyota.
What is an Array?
An array is a special variable, which can hold more than one value at a time.
If you have a list of items (a list of car names, for example), storing the cars in single variables
could look like this:
$cars1 = "Volvo";
$cars2 = "BMW";
$cars3 = "Toyota";
However, what if you want to loop through the cars and find a specific one? And what if you had
not 3 cars, but 300?
The solution is to create an array!
An array can hold many values under a single name, and you can access the values by referring
to an index number.
Create an Array in PHP
In PHP, the array() function is used to create an array:
array();
In PHP, there are three types of arrays:
Indexed arrays - Arrays with a numeric index
Associative arrays - Arrays with named keys
Multidimensional arrays - Arrays containing one or more arrays
Get The Length of an Array - The count() Function:The count() function is used to
return the length (the number of elements) of an array:
<!DOCTYPE html>
<html>
<body>
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo count($cars);
?>
</body>
</html>
OUTPUT: 3
Loop Through an Indexed Array: To loop through and print all the values of an indexed
array, you could use a for loop, like this:
<!DOCTYPE html>
<html>
<body>
<?php
$cars = array("Volvo", "BMW", "Toyota");
$arrlength = count($cars);
for($x = 0; $x < $arrlength; $x++) {
echo $cars[$x];
echo "<br>";
}
?>
</body>
</html>
OUTPUT:
Volvo
BMW
Toyota
13
PHP Associative Arrays: Associative arrays are arrays that use named keys that you assign
to them.
or:
$age['Peter'] = "35";
$age['Ben'] = "37";
$age['Joe'] = "43";
<!DOCTYPE html>
<html>
<body>
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";
?>
</body>
</html>
OUTPUT:
Peter is 35 years old.
To loop through and print all the values of an associative array, you could use a foreach loop,
like this:
<!DOCTYPE html>
<html>
<body>
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
foreach($age as $x => $x_value) {
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>
14
</body>
</html>
OUTPUT:
Key=Peter, Value=35
Key=Ben, Value=37
Key=Joe, Value=43
The dimension of an array indicates the number of indices you need to select an element.
Volvo 22 18
BMW 15 13
Saab 5 2
Land Rover 17 15
We can store the data from the table above in a two-dimensional array, like this:
$cars = array
(
array("Volvo",22,18),
array("BMW",15,13),
15
array("Saab",5,2),
array("Land Rover",17,15)
);
Now the two-dimensional $cars array contains four arrays, and it has two indices: row and
column.
To get access to the elements of the $cars array we must point to the two indices (row and
column):
<!DOCTYPE html>
<html>
<body>
<?php
$cars = array
(
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);
</body>
</html>
OUTPUT:
Volvo: In stock: 22, sold: 18.
BMW: In stock: 15, sold: 13.
Saab: In stock: 5, sold: 2.
Land Rover: In stock: 17, sold: 15.
We can also put a For loop inside another For loop to get the elements of the $cars array (we still have to
point to the two indices):
OUTPUT:
Row number 0
Volvo
22
18
Row number 1
BMW
15
13
16
Row number 2
Saab
5
2
Row number 3
Land Rover
17
15
PHP Strings
In this chapter we will look at some commonly used functions to manipulate strings.
The example below returns the length of the string "Hello world!":
<!DOCTYPE html>
<html>
<body>
<?php
echo strlen("Hello world!");
?>
</body>
</html>
OUTPUT: 12
<!DOCTYPE html>
<html>
17
<body>
<?php
echo str_word_count("Hello world!");
?>
</body>
</html>
OUTPUT:2
Reverse a String
<!DOCTYPE html>
<html>
<body>
<?php
echo strrev("Hello world!");
?>
</body>
</html>
The PHP strpos() function searches for a specific text within a string.
If a match is found, the function returns the character position of the first match. If no match is
found, it will return FALSE.
The example below searches for the text "world" in the string "Hello world!":
<!DOCTYPE html>
<html>
<body>
<?php
echo strpos("Hello world!", "world");
?>
18
</body>
</html>
OUTPUT: 6
The PHP str_replace() function replaces some characters with some other characters in a string.
<!DOCTYPE html>
<html>
<body>
<?php
echo str_replace("world", "Dolly", "Hello world!");
?>
</body>
</html>
Operators :
perators are used to perform operations on variables and values.
Arithmetic operators
Assignment operators
Comparison operators
Increment/Decrement operators
Logical operators
String operators
Array operators
The PHP arithmetic operators are used with numeric values to perform common arithmetical
operations, such as addition, subtraction, multiplication etc.
19
Operator Name Example Result
The PHP assignment operators are used with numeric values to write a value to a variable.
The basic assignment operator in PHP is "=". It means that the left operand gets set to the value
of the assignment expression on the right.
x += y x=x+y Addition
x -= y x=x-y Subtraction
x *= y x=x*y Multiplication
x /= y x=x/y Division
x %= y x=x%y Modulus
20
PHP Comparison Operators
The PHP comparison operators are used to compare two values (number or string):
21
--$x Pre-decrement Decrements $x by one, then returns $x
PHP has two operators that are specially designed for strings.
Concatenation of $txt1
. Concatenation $txt1 . $txt2
and $txt2
Concatenation
.= $txt1 .= $txt2 Appends $txt2 to $txt1
assignment
22
PHP Array Operators
Expressions :
Regular expressions are nothing more than a sequence or pattern of characters itself. They
provide the foundation for pattern-matching functionality.
Using regular expression you can search a particular string inside a another string, you can
replace one string by another string and you can split a string into many chunks.
PHP offers functions specific to two sets of regular expression functions, each corresponding to a
certain type of regular expression. You can use any of them based on your comfort.
The structure of a POSIX regular expression is not dissimilar to that of a typical arithmetic
expression: various elements (operators) are combined to form more complex expressions.
23
The simplest regular expression is one that matches a single character, such as g, inside strings
such as g, haggle, or bag.
Lets give explanation for few concepts being used in POSIX regular expression. After that we
will introduce you with regular expression related functions.
Brackets
Brackets ([]) have a special meaning when used in the context of regular expressions. They are
used to find a range of characters.
[0-9]
1
It matches any decimal digit from 0 through 9.
[a-z]
2
It matches any character from lower-case a through lowercase z.
[A-Z]
3
It matches any character from uppercase A through uppercase Z.
[a-Z]
4
It matches any character from lowercase a through uppercase Z.
The ranges shown above are general; you could also use the range [0-3] to match any decimal
digit ranging from 0 through 3, or the range [b-v] to match any lowercase character ranging from
b through v.
Quantifiers
The frequency or position of bracketed character sequences and single characters can be denoted
by a special character. Each special character having a specific connotation. The +, *, ?, {int.
range}, and $ flags all follow a character sequence.
p+
1
It matches any string containing at least one p.
2 p*
24
It matches any string containing zero or more p's.
p?
3
It matches any string containing zero or more p's. This is just an alternative way to use
p*.
p{N}
4
It matches any string containing a sequence of N p's
p{2,3}
5
It matches any string containing a sequence of two or three p's.
p{2, }
6
It matches any string containing a sequence of at least two p's.
p$
7
It matches any string with p at the end of it.
^p
8
It matches any string with p at the beginning of it.
Examples
[^a-zA-Z]
1
It matches any string not containing any of the characters ranging from a through z and
A through Z.
p.p
2
It matches any string containing p, followed by any character, in turn followed by
another p.
^.{2}$
3
It matches any string containing exactly two characters.
<b>(.*)</b>
4
It matches any string enclosed within <b> and </b>.
25
p(hp)*
5
It matches any string containing a p followed by zero or more instances of the
sequence php.
For your programming convenience several predefined character ranges, also known as character
classes, are available. Character classes specify an entire range of characters, for example, the
alphabet or an integer set −
[[:alpha:]]
1
It matches any string containing alphabetic characters aA through zZ.
[[:digit:]]
2
It matches any string containing numerical digits 0 through 9.
[[:alnum:]]
3
It matches any string containing alphanumeric characters aA through zZ and 0 through
9.
[[:space:]]
4
It matches any string containing a space.
1 ereg()
The ereg() function searches a string specified by string for a string specified by pattern, returning
true if the pattern is found, and false otherwise.
2 ereg_replace()
The ereg_replace() function searches for string specified by pattern and replaces pattern with
replacement if found.
26
3 eregi()
The eregi() function searches throughout a string specified by pattern for a string specified by string.
The search is not case sensitive.
4 eregi_replace()
The eregi_replace() function operates exactly like ereg_replace(), except that the search for pattern
in string is not case sensitive.
5 split()
The split() function will divide a string into various elements, the boundaries of each element based
on the occurrence of pattern in string.
6 spliti()
The spliti() function operates exactly in the same manner as its sibling split(), except that it is not
case sensitive.
7 sql_regcase()
The sql_regcase() function can be thought of as a utility function, converting each character in the
input parameter string into a bracketed expression containing two characters.
Meta characters
1 preg_match()
The preg_match() function searches string for pattern, returning true if pattern exists, and false
otherwise.
2 preg_match_all()
3 preg_replace()
The preg_replace() function operates just like ereg_replace(), except that regular expressions
can be used in the pattern and replacement input parameters.
4 preg_split()
The preg_split() function operates exactly like split(), except that regular expressions are
accepted as input parameters for pattern.
5 preg_grep()
The preg_grep() function searches all elements of input_array, returning all elements matching
the regexp pattern.
6 preg_ quote()
28
Quote regular expression characters
Very often when you write code, you want to perform different actions for different conditions.
You can use conditional statements in your code to do this.
Syntax
if (condition) {
code to be executed if condition is true;
}
The example below will output "Have a good day!" if the current time (HOUR) is less than 20:
<!DOCTYPE html>
<html>
<body>
<?php
$t = date("H");
The if....else statement executes some code if a condition is true and another code if that
condition is false.
Syntax
if (condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}
The example below will output "Have a good day!" if the current time is less than 20, and "Have
a good night!" otherwise:
<!DOCTYPE html>
<html>
<body>
<?php
$t = date("H");
if ($t < "20") {
echo "Have a good day!";
} else {
echo "Have a good night!";
}
?>
</body>
</html>
OUTPUT: Have a good day!
The if....elseif...else statement executes different codes for more than two conditions.
Syntax
if (condition) {
code to be executed if this condition is true;
} elseif (condition) {
30
code to be executed if this condition is true;
} else {
code to be executed if all conditions are false;
}
The example below will output "Have a good morning!" if the current time is less than 10, and
"Have a good day!" if the current time is less than 20. Otherwise it will output "Have a good
night!":
<!DOCTYPE html>
<html>
<body>
<?php
$t = date("H");
echo "<p>The hour (of the server) is " . $t;
echo ", and will give the following message:</p>";
</body>
</html>
OUTPUT:
The hour (of the server) is 03, and will give the following message:
switch Statement
The switch statement is used to perform different actions based on different conditions.
Use the switch statement to select one of many blocks of code to be executed.
31
Syntax
switch (n) {
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
case label3:
code to be executed if n=label3;
break;
...
default:
code to be executed if n is different from all labels;
}
This is how it works: First we have a single expression n (most often a variable), that is
evaluated once. The value of the expression is then compared with the values for each case in the
structure. If there is a match, the block of code associated with that case is executed. Use break
to prevent the code from running into the next case automatically. The default statement is used
if no match is found.
<!DOCTYPE html>
<html>
<body>
<?php
$favcolor = "red";
switch ($favcolor) {
case "red":
echo "Your favorite color is red!";
break;
case "blue":
echo "Your favorite color is blue!";
break;
case "green":
echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither red, blue, nor green!";
}
?>
32
</body>
</html>
OUTPUT: Your favorite color is red!
PHP Loops
Often when you write code, you want the same block of code to run over and over again in a
row. Instead of adding several almost equal code-lines in a script, we can use loops to perform a
task like this.
while - loops through a block of code as long as the specified condition is true
do...while - loops through a block of code once, and then repeats the loop as long as the
specified condition is true
for - loops through a block of code a specified number of times
foreach - loops through a block of code for each element in an array
The while loop executes a block of code as long as the specified condition is true.
Syntax
The example below first sets a variable $x to 1 ($x = 1). Then, the while loop will continue to
run as long as $x is less than, or equal to 5 ($x <= 5). $x will increase by 1 each time the loop
runs ($x++):
<!DOCTYPE html>
<html>
<body>
<?php
$x = 1;
while($x <= 5) {
echo "The number is: $x <br>";
$x++;
}
?>
33
</body>
</html>
OUTPUT:
The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5
The do...while loop will always execute the block of code once, it will then check the condition,
and repeat the loop while the specified condition is true.
Syntax
do {
code to be executed;
} while (condition is true);
The example below first sets a variable $x to 1 ($x = 1). Then, the do while loop will write some
output, and then increment the variable $x with 1. Then the condition is checked (is $x less than,
or equal to 5?), and the loop will continue to run as long as $x is less than, or equal to 5:
<!DOCTYPE html>
<html>
<body>
<?php
$x = 1;
do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 5);
?>
</body>
</html>
OUTPUT:
The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5
34
Notice that in a do while loop the condition is tested AFTER executing the statements within the
loop. This means that the do while loop would execute its statements at least once, even if the
condition is false the first time.
The example below sets the $x variable to 6, then it runs the loop, and then the condition is
checked:
<!DOCTYPE html>
<html>
<body>
<?php
$x = 6;
do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 5);
?>
</body>
</html>
OUTPUT: The number is: 6
The for loop is used when you know in advance how many times the script should run.
Syntax
Parameters:
<!DOCTYPE html>
<html>
<body>
<?php
35
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
?>
</body>
</html>
OUTPUT:
The number is: 0
The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5
The number is: 6
The number is: 7
The number is: 8
The number is: 9
The number is: 10
The foreach loop works only on arrays, and is used to loop through each key/value pair in an
array.
Syntax
For every loop iteration, the value of the current array element is assigned to $value and the array
pointer is moved by one, until it reaches the last array element.
The following example demonstrates a loop that will output the values of the given array
($colors):
<!DOCTYPE html>
<html>
<body>
<?php
$colors = array("red", "green", "blue", "yellow");
36
}
?>
</body>
</html>
OUTPUT:
red
green
blue
yellow
PHP Functions:
The real power of PHP comes from its functions; it has more than 1000 built-in functions.
Besides the built-in PHP functions, we can create our own functions.
Syntax
function functionName() {
code to be executed;
}
Note: A function name can start with a letter or underscore (not a number).
Tip: Give the function a name that reflects what the function does!
37
In the example below, we create a function named "writeMsg()". The opening curly brace ( { )
indicates the beginning of the function code and the closing curly brace ( } ) indicates the end of
the function. The function outputs "Hello world!". To call the function, just write its name:
<!DOCTYPE html>
<html>
<body>
<?php
function writeMsg() {
echo "Hello world!";
}
writeMsg();
?>
</body>
</html>
OUTPUT:
Hello world!
Information can be passed to functions through arguments. An argument is just like a variable.
Arguments are specified after the function name, inside the parentheses. You can add as many
arguments as you want, just separate them with a comma.
The following example has a function with one argument ($fname). When the familyName()
function is called, we also pass along a name (e.g. Jani), and the name is used inside the function,
which outputs several different first names, but an equal last name:
<!DOCTYPE html>
<html>
<body>
<?php
function familyName($fname) {
echo "$fname Refsnes.<br>";
}
familyName("Jani");
familyName("Hege");
familyName("Stale");
familyName("Kai Jim");
38
familyName("Borge");
?>
</body>
</html>
OUTPUT:
Jani Refsnes.
Hege Refsnes.
Stale Refsnes.
Kai Jim Refsnes.
Borge Refsnes.
The following example has a function with two arguments ($fname and $year):
<!DOCTYPE html>
<html>
<body>
<?php
function familyName($fname, $year) {
echo "$fname Refsnes. Born in $year <br>";
}
familyName("Hege","1975");
familyName("Stale","1978");
familyName("Kai Jim","1983");
?>
</body>
</html>
OUTPUT:
Hege Refsnes. Born in 1975
Stale Refsnes. Born in 1978
Kai Jim Refsnes. Born in 1983
The following example shows how to use a default parameter. If we call the function setHeight()
without arguments it takes the default value as argument:
<!DOCTYPE html>
<html>
<body>
<?php
function setHeight($minheight = 50) {
echo "The height is : $minheight <br>";
}
setHeight(350);
setHeight();
setHeight(135);
setHeight(80);
39
?>
</body>
</html>
OUTPUT:
The height is : 350
The height is : 50
The height is : 135
The height is : 80
<!DOCTYPE html>
<html>
<body>
<?php
function sum($x, $y) {
$z = $x + $y;
return $z;
}
echo "5 + 10 = " . sum(5,10) . "<br>";
echo "7 + 13 = " . sum(7,13) . "<br>";
echo "2 + 4 = " . sum(2,4);
?>
</body>
</html>
OUTPUT:
5 + 10 = 15
7 + 13 = 20
2+4=6
Reading data from web form controls like text boxes, radio buttons, lists etc,
The example below displays a simple HTML form with two input fields and a submit button:
<!DOCTYPE HTML>
<html>
<body>
40
<form action="welcome.php" method="post">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
</body>
</html>
OUTPUT:
Name:
E-mail:
Submit
When the user fills out the form above and clicks the submit button, the form data is sent for
processing to a PHP file named "welcome.php". The form data is sent with the HTTP POST
method.
To display the submitted data you could simply echo all the variables. The "welcome.php" looks
like this:
<html>
<body>
Welcome <?php echo $_POST["name"]; ?><br>
Your email address is: <?php echo $_POST["email"]; ?>
</body>
</html>
Welcome John
Your email address is [email protected]
The same result could also be achieved using the HTTP GET method:
<!DOCTYPE HTML>
<html>
<body>
41
<form action="welcome_get.php" method="get">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
</body>
</html>
Name:
E-mail:
Submit
</body>
</html>
The code above is quite simple. However, the most important thing is missing. You need to
validate form data to protect your script from malicious code.
GET vs. POST
Both GET and POST create an array (e.g. array( key => value, key2 => value2, key3 => value3,
...)). This array holds key/value pairs, where keys are the names of the form controls and values
are the input data from the user.
Both GET and POST are treated as $_GET and $_POST. These are superglobals, which means
that they are always accessible, regardless of scope - and you can access them from any function,
class or file without having to do anything special.
$_GET is an array of variables passed to the current script via the URL parameters.
$_POST is an array of variables passed to the current script via the HTTP POST method.
42
When to use POST?
Information sent from a form with the POST method is invisible to others (all names/values are
embedded within the body of the HTTP request) and has no limits on the amount of information
to send.
Moreover POST supports advanced functionality such as support for multi-part binary input
while uploading files to server.
However, because the variables are not displayed in the URL, it is not possible to bookmark the
page.
Developers prefer POST for sending form data.
These pages will show how to process PHP forms with security in mind. Proper validation of
form data is important to protect your form from hackers and spammers!
The HTML form we will be working at in these chapters, contains various input fields: required
and optional text fields, radio buttons, and a submit button:
43
Gender Required. Must select one
First we will look at the plain HTML code for the form:
Text Fields
The name, email, and website fields are text input elements, and the comment field is a textarea.
The HTML code looks like this:
The gender fields are radio buttons and the HTML code looks like this:
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
The Form Element
When the form is submitted, the form data is sent with method="post".
The $_SERVER["PHP_SELF"] is a super global variable that returns the filename of the
currently executing script.
So, the $_SERVER["PHP_SELF"] sends the submitted form data to the page itself, instead of
jumping to a different page. This way, the user will get error messages on the same page as the
form.
44
What is the htmlspecialchars() function?
The htmlspecialchars() function converts special characters to HTML entities. This means that it
will replace HTML characters like < and > with < and >. This prevents attackers from
exploiting the code by injecting HTML or Javascript code (Cross-site Scripting attacks) in forms.
If PHP_SELF is used in your page then a user can enter a slash (/) and then some Cross Site
Scripting (XSS) commands to execute.
Now, if a user enters the normal URL in the address bar like
"http://www.example.com/test_form.php", the above code will be translated to:
So far, so good.
However, consider that a user enters the following URL in the address bar:
http://www.example.com/test_form.php/%22%3E%3Cscript%3Ealert('hacked')%3C/script%3E
45
This code adds a script tag and an alert command. And when the page loads, the JavaScript code
will be executed (the user will see an alert box). This is just a simple and harmless example how
the PHP_SELF variable can be exploited.
Be aware of that any JavaScript code can be added inside the <script> tag! A hacker can
redirect the user to a file on another server, and that file can hold malicious code that can alter
the global variables or submit the form to another address to save the user data, for example.
The htmlspecialchars() function converts special characters to HTML entities. Now if the user
tries to exploit the PHP_SELF variable, it will result in the following output:
<form method="post"
action="test_form.php/"><script>alert('hacked')</script>">
The first thing we will do is to pass all variables through PHP's htmlspecialchars() function.
When we use the htmlspecialchars() function; then if a user tries to submit the following in a text
field:
<script>location.href('http://www.hacked.com')</script>
- this would not be executed, because it would be saved as HTML escaped code, like this:
46
<script>location.href('http://www.hacked.com')</script>
We will also do two more things when the user submits the form:
1. Strip unnecessary characters (extra space, tab, newline) from the user input data (with the
PHP trim() function)
2. Remove backslashes (\) from the user input data (with the PHP stripslashes() function)
The next step is to create a function that will do all the checking for us (which is much more
convenient than writing the same code over and over again).
Now, we can check each $_POST variable with the test_input() function, and the script looks
like this:
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<?php
// define variables and set to empty values
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = test_input($_POST["name"]);
$email = test_input($_POST["email"]);
$website = test_input($_POST["website"]);
$comment = test_input($_POST["comment"]);
$gender = test_input($_POST["gender"]);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>PHP Form Validation Example</h2>
<form method="post" action="<?php echohtmlspecialchars($_SERVER["PHP_SELF"]);?>">
47
Name: <input type="text" name="name">
<br><br>
E-mail: <input type="text" name="email">
<br><br>
Website: <input type="text" name="website">
<br><br>
Comment: <textarea name="comment" rows="5"cols="40"></textarea>
<br><br>
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>
</body>
</html>
OUTPUT:
Name:
E-mail:
Website:
48
Comment:
Submit
Your Input:
ramesh
[email protected]
www.cmrec.ac.in
welcome
male
Notice that at the start of the script, we check whether the form has been submitted using
$_SERVER["REQUEST_METHOD"]. If the REQUEST_METHOD is POST, then the form has
been submitted - and it should be validated. If it has not been submitted, skip the validation and
display a blank form.
However, in the example above, all input fields are optional. The script works fine even if the
user does not enter any data.
The next step is to make input fields required and create error messages if needed.
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";
49
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["website"])) {
$website = "";
} else {
$website = test_input($_POST["website"]);
// check if URL address syntax is valid (this regular expression also
allows dashes in the URL)
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-
9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {
$websiteErr = "Invalid URL";
}
}
if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}
if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
$gender = test_input($_POST["gender"]);
}
}
50
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>
51
</body>
</html>
OUTPUT:
* required field.
ramesh
Name: *
check@g
E-mail: *
w w w .cm
Website:
Comment:
Submit
Your Input:
ramesh
[email protected]
www.cmrec.ac.in
ss
male
An HTTP cookie (also called web cookie, Internet cookie, browser cookie or simply cookie) is a small
piece of data sent from a website and stored on the user's computer by the user's web browser while the
user is browsing. Cookies were designed to be a reliable mechanism for websites to remember stateful
52
information (such as items added in the shopping cart in an online store) or to record the user's browsing
activity (including clicking particular buttons, logging in, or recording which pages were visited in the
past). They can also be used to remember arbitrary pieces of information that the user previously entered
into form fields such as names, addresses, passwords, and credit card numbers.
What is a Cookie?
A cookie is often used to identify a user. A cookie is a small file that the server embeds on the
user's computer. Each time the same computer requests a page with a browser, it will send the
cookie too. With PHP, you can both create and retrieve cookie values.
Syntax
Only the name parameter is required. All other parameters are optional.
The following example creates a cookie named "user" with the value "John Doe". The cookie
will expire after 30 days (86400 * 30). The "/" means that the cookie is available in entire
website (otherwise, select the directory you prefer).
We then retrieve the value of the cookie "user" (using the global variable $_COOKIE). We also
use the isset() function to find out if the cookie is set:
EXAMPLE:
<!DOCTYPE html>
<?php
$cookie_name = "user";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
?>
<html>
<body>
<?php
if(!isset($_COOKIE[$cookie_name])) {
53
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
<p><strong>Note:</strong> You might have to reload the page to see the value of the cookie.</p>
</body>
</html>
OUTPUT:
Cookie 'user' is set!
Value is: John Doe
Note: You might have to reload the page to see the value of the cookie.
Note: The setcookie() function must appear BEFORE the <html> tag.
Note: The value of the cookie is automatically URLencoded when sending the cookie, and
automatically decoded when received (to prevent URLencoding, use setrawcookie() instead).
To modify a cookie, just set (again) the cookie using the setcookie() function:
Example
<!DOCTYPE html>
<?php
$cookie_name = "user";
$cookie_value = "Alex Porter";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
?>
<html>
<body>
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
<p><strong>Note:</strong> You might have to reload the page to see the new value of the cookie.</p>
</body>
</html>
54
OUTPUT:
Cookie 'user' is set!
Value is: John Doe
Note: You might have to reload the page to see the new value of the cookie.
Delete a Cookie
To delete a cookie, use the setcookie() function with an expiration date in the past:
Example
<!DOCTYPE html>
<?php
// set the expiration date to one hour ago
setcookie("user", "", time() - 3600);
?>
<html>
<body>
<?php
echo "Cookie 'user' is deleted.";
?>
</body>
</html>
OUTPUT: Cookie 'user' is deleted.
The following example creates a small script that checks whether cookies are enabled. First, try
to create a test cookie with the setcookie() function, then count the $_COOKIE array variable:
Example
<!DOCTYPE html>
<?php
setcookie("test_cookie", "test", time() + 3600, '/');
?>
<html>
<body>
<?php
if(count($_COOKIE) > 0) {
echo "Cookies are enabled.";
} else {
echo "Cookies are disabled.";
55
}
?>
</body>
</html>
OUTPUT: Cookies are enabled.
PHP Sessions
A session is a way to store information (in variables) to be used across multiple pages.
When you work with an application, you open it, do some changes, and then you close it. This is
much like a Session. The computer knows who you are. It knows when you start the application
and when you end. But on the internet there is one problem: the web server does not know who
you are or what you do, because the HTTP address doesn't maintain state.
Session variables solve this problem by storing user information to be used across multiple pages
(e.g. username, favorite color, etc). By default, session variables last until the user closes the
browser.
So; Session variables hold information about one single user, and are available to all pages in
one application.
Tip: If you need a permanent storage, you may want to store the data in a database.
Session variables are set with the PHP global variable: $_SESSION.
Now, let's create a new page called "demo_session1.php". In this page, we start a new PHP
session and set some session variables:
Example
56
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>
</body>
</html>
Note: The session_start() function must be the very first thing in your document. Before any
HTML tags.
Next, we create another page called "demo_session2.php". From this page, we will access the
session information we set on the first page ("demo_session1.php").
Notice that session variables are not passed individually to each new page, instead they are
retrieved from the session we open at the beginning of each page (session_start()).
Also notice that all session variable values are stored in the global $_SESSION variable:
Example
<?php
session_start();
?>
<!DOCTYPE html>
<html>
57
<body>
<?php
// Echo session variables that were set on previous page
echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";
echo "Favorite animal is " . $_SESSION["favanimal"] . ".";
?>
</body>
</html>
OUTPUT:
Another way to show all the session variable values for a user session is to run the following code:
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
print_r($_SESSION);
?>
</body>
</html>
Most sessions set a user-key on the user's computer that looks something like this:
765487cf34ert8dede5a562e4f3a7e12. Then, when a session is opened on another page, it scans the
computer for a user-key. If there is a match, it accesses that session, if not, it starts a new session.
<?php
// to change a session variable, just overwrite it
$_SESSION["favcolor"] = "yellow";
print_r($_SESSION);
?>
</body>
</html>
OUTPUT: Array ( [favcolor] => yellow [favanimal] => cat )
To remove all global session variables and destroy the session, use session_unset() and
session_destroy():
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// remove all session variables
session_unset();
echo "All session variables are now removed, and the session is destroyed."
?>
</body>
</html>
OUTPUT:
All session variables are now removed, and the session is destroyed.
59
File Handling in PHP:
File handling is an important part of any web application. You often need to open and process a
file for different tasks.
PHP Manipulating Files
PHP has several functions for creating, reading, uploading, and editing files.
Be careful when manipulating files!
When you are manipulating files you must be very careful.
You can do a lot of damage if you do something wrong. Common errors are:
editing the wrong file, filling a hard-drive with garbage data, and deleting the
content of a file by accident.
Example
60
<?php
echo readfile("webdictionary.txt");
?>
Output:
AJAX = Asynchronous JavaScript and XML CSS = Cascading Style Sheets
HTML = Hyper Text Markup Language PHP = PHP Hypertext Preprocessor SQL
= Structured Query Language SVG = Scalable Vector Graphics XML =
EXtensible Markup Language236
The readfile() function is useful if all you want to do is open up a file and read its
contents.
The first parameter of fopen() contains the name of the file to be opened and the
second parameter specifies in which mode the file should be opened. The
following example also generates a message if the fopen() function is unable to
open the specified file:
Example
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
61
echo fread($myfile,filesize("webdictionary.txt"));
fclose($myfile);
?>
Tip: The fread() and the fclose() functions will be explained below.
The file may be opened in one of the following modes:
Modes Description
r Open a file for read only. File pointer starts at the beginning of the file
w Open a file for write only. Erases the contents of the file or creates a new file if it d
pointer starts at the beginning of the file
r+ Open a file for read/write. File pointer starts at the beginning of the file
62
Returns FALSE and an error if file already exists
fread($myfile,filesize("webdictionary.txt"));
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
echo fgets($myfile);
63
fclose($myfile);
?>
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
// Output one character until end-of-file
while(!feof($myfile)) {
echo fgetc($myfile);
}
fclose($myfile);
?>
64