Web Tech Unit 3 PDF
Web Tech Unit 3 PDF
Web Tech Unit 3 PDF
COM
UNIT-3
PHP performs system functions, i.e. from files on a system it can create, open, read, write, and close
them.
PHP can handle forms, i.e. gather data from files, save data to a file, thru email you can send data, return
data to the user.
You add, delete, and modify elements within your database thru PHP.
Access cookies variables and set cookies.
Using PHP, you can restrict users to access some pages of your website.
It can encrypt data.
Characteristics of PHP
1. Simplicity
2. Efficiency
3. Security
4. Flexibility
5. Familiarity
PHP Installation:
Download PHP for free here: http://www.php.net/downloads.php
In order to develop and run PHP Web pages three vital components need to be installed on your computer
system.
WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
Web Server - PHP will work with virtually all Web Server software, including Microsoft's Internet
Information Server (IIS) but then most often used is freely availble Apache Server. Download
Apache for free here: http://httpd.apache.org/download.cgi
Database - PHP will work with virtually all database software, including Oracle and Sybase but
most commonly used is freely available MySQL database. Download MySQL for free
here: http://www.mysql.com/downloads/index.html
PHP Parser - In order to process PHP script instructions a parser must be installed to generate
HTML output that can be sent to the Web Browser.
Apache uses httpd.conf file for global settings, and the .htaccess file for per-directory access
settings. Older versions of Apache split up httpd.conf into three files (access.conf, httpd.conf, and
srm.conf), and some users still prefer this arrangement.
Apache server has a very powerful, but slightly complex, configuration system of its own. Learn
more about it at the Apache Web site: www.apache.org
The following section describe settings in httpd.conf that affect PHP directly and cannot be set
elsewhere. If you have standard installation then httpd.conf will be found at /etc/httpd/conf:
Timeout
This value sets the default number of seconds before any HTTP request will time out. If you set
PHP's max_execution_time to longer than this value, PHP will keep grinding away but the user may
see a 404 error. In safe mode, this value will be ignored; you must use the timeout value in php.ini
instead
DocumentRoot
DocumentRoot designates the root directory for all HTTP processes on that server. It looks
something like this on Unix:
DocumentRoot ./usr/local/apache_1.3.6/htdocs.
AddType
The PHP MIME type needs to be set here for PHP files to be parsed. Remember that you can
associate any file extension with PHP like .php3, .php5 or .htm.
Action
You must uncomment this line for the Windows apxs module version of Apache with shared object
support:
WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
or on Unix flavors:
AddModule
You must uncomment this line for the static module version of Apache.
AddModule mod_php4.c
PHP Syntax:
Note:
PHP code is executed on the server, and the plain HTML result is sent to the browser.
A PHP scripting block always starts with <?php and ends with ?>. A PHP scripting block
can be placed anywhere in the document.
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
Note: Comment lines are used in the program to understand the code
WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
Variables are used for storing values, like text strings, numbers or arrays.
When a variable is declared, it can be used over and over again in your script.
All variables in PHP start with a $ sign symbol.
The correct way of declaring a variable in PHP: Eg: $var_name = value;
<?php
$txt="HelloWorld!";
$x=16;
?>
PHP is a Loosely Typed Language:
In PHP, a variable does not need to be declared before adding a value to it.
you do 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.
the PHP script assigns the text "Hello World" to a string variable called $txt:
Eg: <?php
$txt="Hello World";
echo $txt;
?>
The output of the code above will be:
Hello World
A data type refers to the type of data a variable can store. PHP has eight (8) different data types you
WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
Scalar types
boolean
integer
float
string
Compound types
array
object
Special types
resources
NULL
Boolean values:
In PHP the boolean data type is a primitive data type having one of two values: True or False.
This is a fundamental data type.
<?php
$male = False;
$r = rand(0, 1);
if ($male) {
echo "We will use name John\n";
} else {
echo "We will use name Victoria\n";
}
?>
$r = rand(0, 1);
WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
The rand() function returns a random number from the given integer boundaries. In our case 0 or
1.
We use the ternary operator to set a $male variable. The variable is based on the
random $r value. If $r equals to 1, the $male variable is set to True. If $r equals to 0, the $male
variable is set to False.
if ($male) {
echo "We will use name John\n";
} else {
echo "We will use name Victoria\n";
}
We print the name. The if command works with boolean values. If the variable $male is True, we
print the "We will use name John" to the console. If it has a False value, we print the other string.
The following script shows some common values that are considered to be True or False. For
example, empty string, empty array, 0 are considered to be False.
<?php
class Object {};
var_dump((bool) "");
var_dump((bool) 0);
var_dump((bool) -1);
var_dump((bool) "PHP");
var_dump((bool) array(32));
var_dump((bool) array());
var_dump((bool) "false");
var_dump((bool) new Object());
var_dump((bool) NULL);
?>
In this script, we inspect some values in a boolean context. The var_dump()function shows
information about a variable. The (bool) construct is called casting. In its casual context, the 0
value is a number. In a boolean context, it is False. The boolean context is when we use (bool)
WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
casting, when we use certain operators (negation, comparison operators) and when we use if/else,
while keywords.
$ php boolean.php
bool(false)
bool(false)
bool(true)
bool(true)
bool(true)
bool(false)
bool(true)
bool(true)
bool(false)
Integers
Integers are a subset of the real numbers. They are written without a fraction or a decimal
component. Integers fall within a set Z = {..., -2, -1, 0, 1, 2, ...} Integers are infinite.
In computer languages, integers are primitive data types. Computers can practically work only
with a subset of integer values, because computers have finite capacity. Integers are used to
count discrete entities. We can have 3, 4, 6 humans, but we cannot have 3.33 humans. We can
have 3.33 kilograms.
Integers can be specified in three different notations in PHP. Decimal, hexadecimal and octal.
Octal values are preceded by 0, hexadecimal by 0x.
<?php
$var1 = 31;
$var2 = 031;
$var3 = 0x31;
echo "$var1\n";
WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
echo "$var2\n";
echo "$var3\n";
?>
We assign 31 to three variables using three notations. And we print them to the console.
$ php notation.php
31
25
49
The default notation is the decimal. The script shows these three numbers in decimal.
Integers in PHP have a fixed maximum size. The size of integers is platform dependent. PHP
has built-in constants to show the maximum size of an integer.
$ uname -mo
i686 GNU/Linux
$ php -a
Interactive shell
On my 32bit Ubuntu system, an integer value size is four bytes. The maximum integer value is
2147483647.
In Java and C, if an integer value is bigger than the maximum value allowed, integer overflow
happens. PHP works differently. In PHP, the integer becomes a float number. Floating point
numbers have greater boundaries.
<?php
WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
$var = PHP_INT_MAX;
echo var_dump($var);
$var++;
echo var_dump($var);
?>
We assign a maximum integer value to the $var variable. We increase the variable by one. And
we compare the contents.
$ php boundary.php
int(2147483647)
float(2147483648)
As we have mentioned previously, internally, the number becomes a floating point value.
In Java, the value after increasing would be -2147483648. This is where the term integer
overflow comes from. The number goes over the top and becomes the smallest negative integer
value assignable to a variable.
If we work with integers, we deal with discrete entities. We would use integers to count apples.
<?php
# number of baskets
$baskets = 16;
In our script, we count the total amount of apples. We use the multiplication operation.
WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
$ php apples.php
There are total of 384 apples
Floating point numbers represent real numbers in computing. Real numbers measure continuous
quantities. Like weight, height or speed. Floating point numbers in PHP can be larger than
integers and they can have a decimal point. The size of a float is platform dependent.
<?php
$a = 1.245;
$b = 1.2e3;
$c = 2E-10;
$d = 1264275425335735;
var_dump($a);
var_dump($b);
var_dump($c);
var_dump($d);
?>
In this example, we have two cases of notations, that are used by scientists to denote floating
point values. Also the $d variable is assigned a large number, so it is automatically converted to
float type.
$ php floats.php
float(1.245)
float(1200)
float(2.0E-10)
float(1264275425340000)
WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
According to the documentation, floating point numbers should not be tested for equality. We
will show an example why.
$ php -a
Interactive shell
In this example, we compare two values that seem to be identical. But they yield unexpected
result.
Let's say a sprinter for 100m ran 9.87s. What is his speed in km/h?
<?php
# 100m is 0.1 km
$distance = 0.1;
# 9.87s is 9.87/60*60 h
?>
WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
$ php sprinter.php
The average speed of a sprinter is 36.4741641337
This is the output of the sprinter script. 36.4741641337 is a floating point number.
Strings
String is a data type representing textual data in computer programs. Probably the single
most important data type in programming.
Since string are very important in every programming language, we will dedicate a whole
chapter to them. Here we only drop a small example.
<?php
$a = "PHP ";
$b = 'PERL';
?>
We can use single quotes and double quotes to create string literals.
$ php strings.php
PHP PERL
The script outputs two strings to the console. The \n is a special sequence, a new line. The
effect of this character is like if you hit the enter key when typing text.
Arrays
Array is a complex data type which handles a collection of elements. Each of the
elements can be accessed by an index. In PHP, arrays are more diverse. Arrays can be
treated as arrays, lists or dictionaries. In other words, arrays are all what in other
languages we call arrays, lists, dictionaries.
WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
Because collections are very important in all computer languages, we dedicate two
chapters to collections - arrays. Here we show only a small example.
<?php
print_r($names);
?>
The array keyword is used to create a collection of elements. In our case we have names.
The print_r function prints a human readable information about a variable to the console.
$ php init.php
Array
(
[0] => Jane
[1] => Lucy
[2] => Timea
[3] => Beky
[4] => Lenka
)
Output of the script. The numbers are indeces by which we can access the names.
Objects
So far, we have been talking about built-in data types. Objects are user defined data
types. Programmers can create their data types that fit their domain. More about objects
in chapter about object oriented programming, OOP.
Resources
WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
Resources are special data types. They hold a reference to an external resource. They are
created by special functions. Resources are handlers to opened files, database connections
or image canvas areas.
NULL
There is another special data type - NULL. Basically, the data type means non existent,
not known or empty.
<?php
$a;
$b = NULL;
$c = 1;
unset($c);
$d = 2;
?>
In our example, we have four variables. Three of them are considered to be NULL. We
use the is_null() function to determine, if the variable is NULL.
$ php null.php
$a is null
$b is null
WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
$c is null
<?php
$txt1="Hello World!";
$txt2="What a nice day!";
echo $txt1 . " " . $txt2;
?>
The output of the code above will be: Hello World! What a nice day!
Eg: <?php
echo strlen("Hello world!");
?>
Eg: <?php
echo strpos("Hello world!","world");
?>
The output of the code above will be: 6(position starts with ZERO)
Note: if match is found then it return character position other wise returns
FALSE
WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
PHP Operators:
PHP Operators
This section lists the different operators used in PHP.
Arithmetic Operators
Assignment Operators
Comparison Operators
WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
Logical Operators
Conditional operators:
if...else statement - use this statement if you want to execute a set of code when a condition is
true and another if the condition is not true
elseif statement - is used with the if...else statement to execute a set of code if one of several
condition are true
switch statement - is used 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..elseif..else code.
If you want to execute some code if a condition is true and another code if a condition is false, use the
if....else statement.
Syntax
if (condition)
code to be executed if condition is true;
else
code to be executed if condition is false;
WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
Example
The following example will output "Have a nice weekend!" if the current day is Friday, otherwise it will
output "Have a nice day!":
<html>
<body>
<?php
$d=date("D");
if ($d=="Fri")
echo "Have a nice weekend!";
else
echo "Have a nice day!";
?>
</body>
</html>
If more than one line should be executed if a condition is true/false, the lines should be enclosed within
curly braces:
<html>
<body>
<?php
$d=date("D");
if ($d=="Fri")
{
echo "Hello!<br />";
echo "Have a nice weekend!";
echo "See you on Monday!";
}
?>
</body>
</html>
If you want to execute some code if one of several conditions are true use the elseif statement
Syntax
if (condition)
code to be executed if condition is true;
elseif (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!":
<html>
<body>
<?php
$d=date("D");
WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
if ($d=="Fri")
echo "Have a nice weekend!";
elseif ($d=="Sun")
echo "Have a nice Sunday!";
else
echo "Have a nice day!";
?>
</body>
</html>
If you want to select one of many blocks of code to be executed, use the Switch statement.
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 lable to
match the resulting value. If a matching value is found then the code associated with the matching label will
be executed or if none of the lables match then statement will will execute any specified default code.
WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
<html>
<body>
<?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 ?";
}
?>
</body>
</html>
We will discuss about continue and break keywords used to control the loops execution.
The for statement is used when you know how many times you want to execute a statement or a block of
statements.
Syntax
for (initialization; condition; increment)
{
code to be executed;
}
WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
The initializer is used to set the start value for the counter of the number of loop iterations. A variable
may be declared here for this purpose and it is tradional to name it $i.
Example
The following example makes five iterations and changes the assigned value of two variables on each pass
of the loop:
<html>
<body>
<?php
$a = 0;
$b = 0;
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
This example decrements a variable value on each iteration of the loop and the counter increments until it
reaches 10 when the evaluation is false and the loop ends.
<html>
<body>
WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
<?php
$i = 0;
$num = 50;
The do...while statement will execute a block of code at least once - it then will repeat the loop as long as a
condition is true.
Syntax
do
{
code to be executed;
}while (condition);
Example
The following example will increment the value of i at least once, and it will continue incrementing the
variable i as long as it has a value of less than 10:
<html>
<body>
<?php
$i = 0;
$num = 0;
do
{
$i++;
}while( $i < 10 );
echo ("Loop stopped at i = $i" );
?>
</body>
</html>
Loop stopped at i = 10
WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
The foreach statement is used to loop through arrays. For each pass the 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
<html>
<body>
<?php
$array = array( 1, 2, 3, 4, 5);
foreach( $array as $value )
{
echo "Value is $value <br />";
}
?>
</body>
</html>
Value is 1
Value is 2
Value is 3
Value is 4
Value is 5
The PHP break keyword is used to terminate the execution of a loop prematurely.
The break statement is situated inside the statement block. If gives you full control and whenever you want
to exit from the loop you can come out. After coming out of a loop immediate statement to the loop will be
executed.
Example
In the following example condition test becomes true when the counter value reaches 3 and loop terminates.
WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
<html>
<body>
<?php
$i = 0;
Loop stopped at i = 3
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 blokc 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 bceoms true it just skip the
code and next valuye is printed.
<html>
<body>
<?php
$array = array( 1, 2, 3, 4, 5);
foreach( $array as $value )
{
if( $value == 3 )continue;
echo "Value is $value <br />";
}
?>
</body>
</html>
Value is 1
Value is 2
Value is 4
Value is 5
WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
PHP Arrays:
An array stores multiple values in one single variable.
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, which can store multiple values in one single variable.
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="Saab";
$cars2="Volvo";
$cars3="BMW";
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 best solution here is to use an array!
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 Arrays
A numeric array stores each array element with a numeric index.
There are two methods to create a numeric array.
1. In the following example the index are automatically assigned (the index starts at 0):
$cars=array("Saab","Volvo","BMW","Toyota");
WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
$cars[0]="Saab";
$cars[1]="Volvo";
$cars[2]="BMW";
$cars[3]="Toyota";
Example
In the following example you access the variable values by referring to the array name and index:
<?php
$cars[0]="Saab";
$cars[1]="Volvo";
$cars[2]="BMW";
$cars[3]="Toyota";
echo $cars[0] . " and " . $cars[1] . " are Swedish
cars.";
?>
Associative Arrays
An associative array, each ID key is associated with a value.
When storing data about specific named values, a numerical array is not always the best way to do it.
With associative arrays we can use the values as keys and assign values to them.
Example 1
Example 2
This example is the same as example 1, but shows a different way of creating the array:
WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
$ages['Peter'] = "32";
$ages['Quagmire'] = "30";
$ages['Joe'] = "34";
<?php
$ages['Peter'] = "32";
$ages['Quagmire'] = "30";
$ages['Joe'] = "34";
Multidimensional Arrays
In a multidimensional 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.
Example
$families = array
(
"Griffin"=>array
(
"Peter",
"Lois",
"Megan"
),
"Quagmire"=>array
(
"Glenn"
),
"Brown"=>array
(
WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
"Cleveland",
"Loretta",
"Junior"
)
);
The array above would look like this if written to the output:
Array
(
[Griffin] => Array
(
[0] => Peter
[1] => Lois
[2] => Megan
)
[Quagmire] => Array
(
[0] => Glenn
)
[Brown] => Array
(
[0] => Cleveland
[1] => Loretta
[2] => Junior
)
)
Example 2
PHP Strings:
They are sequences of characters, like "PHP supports string operations".
WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
Singly quoted strings are treated almost literally, whereas doubly quoted strings replace
variables with their values as well as specially interpreting certain character sequences.
<?
$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.
To concatenate two string variables together, use the dot (.) operator:
<?php
$string1="Hello World";
$string2="1234";
echo $string1 . " " . $string2;
?>
WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
If we look at the code above you see that we used the concatenation operator two times. This is because we
had to insert a third string.
Between the two string variables we added a string with a single character, an empty space, to separate the
two variables.
<?php
echo strlen("Hello world!");
?>
12
The length of a string is often used in loops or other functions, when it is important to know when the string
ends. (i.e. in a loop, we would want to stop the loop after the last character in the string)
The strpos() function is 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.
<?php
echo strpos("Hello world!","world");
?>
As you see 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.
PHP Functions:
The real power of PHP comes from its functions.
In PHP, there are more than 700 built-in functions.
A function is a piece of code which takes one more input in the form of parameter and does some processing
and returns a value.
WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
You already have seen many functions like fopen() and fread() etc. They are built-in functions but PHP
gives you option to create your own functions as well.
In fact you hardly need to create your own PHP function because there are already more than 1000 of built-
in library functions created for different area and you just need to call them according to your requirement.
Please refer to PHP Function Reference for a complete set of useful functions.
Its very easy to create your own PHP function. Suppose you want to create a PHP function which will simply
write a simple message on your browser when you will call it. Following example creates a function called
writeMessage() and then calls it just after creating it.
Note that while creating a function its name should start with keyword function and all the PHP code should
be put inside { and } braces as shown in the following example below:
<html>
<head>
<title>Writing PHP Function</title>
</head>
<body>
<?php
/* Defining a PHP Function */
function writeMessage()
{
echo "You are really a nice person, Have a nice time!";
}
/* Calling a PHP Function */
writeMessage();
?>
</body>
</html>
PHP gives you option to pass your parameters inside a function. You can pass as many as parameters your
like. These parameters work like variables inside your function. Following example takes two integer
parameters and add them together and then print them.
<html>
<head>
<title>Writing PHP Function with Parameters</title>
</head>
WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
<body>
<?php
function addFunction($num1, $num2)
{
$sum = $num1 + $num2;
echo "Sum of the two numbers is : $sum";
}
addFunction(10, 20);
?>
</body>
</html>
It is possible to pass arguments to functions by reference. This means that a reference to the variable is
manipulated by the function rather than a copy of the variable's value.
Any changes made to an argument in these cases will change the value of the original variable. You can
pass an argument by reference by adding an ampersand to the variable name in either the function call or
the function definition.
<html>
<head>
<title>Passing Argument by Reference</title>
</head>
<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>
Original Value is 15
WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
Original Value is 21
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.
You can return more than one value from a function using return array(1,2,3,4).
Following example takes two integer parameters and add 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>
<head>
<title>Writing PHP Function which returns value</title>
</head>
<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>
You can set a parameter to have a default value if the function's caller doesn't pass it.
Following function prints NULL in case use does not pass any value to this function.
<html>
<head>
<title>Writing PHP Function which returns value</title>
</head>
<body>
<?php
function printMe($param = NULL)
{
print $param;
}
printMe("This is test");
printMe();
?>
WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
</body>
</html>
This is test
It is possible to assign function names as strings to variables and then treat these variables exactly as you
would the function name itself. Follwoing example depicts this behaviour.
<html>
<head>
<title>Dynamic Function Calls</title>
</head>
<body>
<?php
function sayHello()
{
echo "Hello<br />";
}
$function_holder = "sayHello";
$function_holder();
?>
</body>
</html>
Hello
Example
The example below contains an HTML form with two input fields and a submit button:
<html>
<body>
WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
</body>
</html>
When a user fills out the form above and click on the submit button, the form data is sent to a PHP
file, called "welcome.php":
<html>
<body>
</body>
</html>
Welcome John!
You are 28 years old.
The PHP $_GET and $_POST variables will be explained in the next chapters.
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.
WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
Opening a file
Reading a file
Writing a file
Closing a file
The PHP fopen() function is used to open a file. It requires two arguments stating first the file name and
then mode in which to operate.
Files modes can be specified as one of the six options in this table.
Mode Purpose
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.
Reading a file
Once a file is opend 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.
WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
The following example assigns the content of a text file to a variable then displays those contents on the
web page.
<html>
<head>
<title>Reading a file using PHP</title>
</head>
<body>
<?php
$filename = "/home/user/guest/tmp.txt";
$file = fopen( $filename, "r" );
if( $file == false )
{
echo ( "Error in opening file" );
exit();
}
$filesize = filesize( $filename );
$filetext = fread( $file, $filesize );
fclose( $file );
</body>
</html>
Writing a file
A new file can be written or text can be appended to an existing file using the PHP fwrite()function. This
function requires two arguments specifying a file pointer and the string of data that is to be written.
Optionally a third intger argument can be included to specify the length of the data to write. If the third
argument is included, writing would will stop after the specified length has been reached.
The following example creates a new text file then writes a short text heading insite it. After closing this file
its existence is confirmed using file_exist() function which takes file name as an argument
<?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>
WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
</head>
<body>
<?php
if( file_exist( $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>
WWW.VIDYARTHIPLUS.COM V+ TEAM