AWP Module2 PHP
AWP Module2 PHP
AWP Module2 PHP
Module -2
Introduction to PHP and Building Web applications with PHP
Why PHP?
• When the browser requests an XHTML document that includes PHP script, the Web server
determines that a document includes PHP script by the filename extensions such as .php,
.php3, or .phtml and calls the PHP processor.
• PHP processor takes PHP document file as input file and produces as XHTML document file.
Copy mode :
On the server side when the PHP processor finds XHTML code (which may include client side
script) in the input file, it simply copies it to the output file.
Interpret mode :
On the server side when it encounters a PHP script in the input file, it interprets it and sends
any output of the script to the output file.
ROOPA.H.M, Dept of MCA, RNSIT Page 2
Module 2 [16MCA42] Advanced Web Programming
• The output from a PHP script must be XHTML or embedded client-side script.
• The output file is sent to the requesting browser. The client never sees the PHP script. If the
user clicks view source while browser is displaying the document, only the XHTML will be
shown.
• This causes the contents of the file table2.inc to be copied into the document where the call
appears.
• The included file can contain XHTML markup or client-side scripts, as well as PHP code.
• Any PHP script it includes must be the content of a <?php tag, even if the include appears in
the content of a <?php tag.
• The PHP interpreter changes from interpret to copy mode when an include is encountered.
<!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>
PHP Variables :
• A variable starts with the $ sign, followed by the name of the variable.
• A variable name must start with a letter or the underscore character.
• A variable name cannot start with a number.
• A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
• Variable names are case-sensitive ($age and $AGE are two different variables)
• Variables are not declared in PHP; they have a value and type of NULL until they are assigned
a value, in which case, they take the type of the value.
• When an unbounded variable (without an assigned value) is used, its value of NULL is coerced
to a 0 or an empty string, depending on its context.
Example : IsSet($myVariable);
PHP has four scalar data types: – Boolean, integer, double and string.
PHP has two compound data types: – array and object.
PHP has two special types: – resource and NULL.
• PHP characters are single bytes(UNICODE is not supported). A single character of string
length is 1.
• String literals are defined with either single (’) or double quotes (") delimiters.
• In single quoted string literals, escape characters such as \n, are not recognized as anything
special and the values of embedded variables are not substituted.
• To have variable values and escape sequences used in a string, enclose them in double
quotes.
• In double-quoted string literals, escape sequences are recognized and embedded variables are
replaced by their current values.
Example :
$sum=10; Output:
print ’the total \n is:$sum’; the total \n is :$sum
print "the total is:$sum"; the total is :10
• Boolean values are either TRUE or FALSE, both of which are case insensitive.
• Other scalar types in boolean context:
• Integer values of 0 are interpreted as false; and others as true.
• Empty Strings or string "0" are interpreted false; and others are true.
• Doubles that are exactly 0.0 are false; others are true.
String Operations:
Strings can be treated like arrays to access individual characters by specifying its position in
braces.
String operators are shown below:
Examples :
Examples outputs
echo strlen("Hello 11
world");
echo strpos("Hello 8
world!", "r");
$string="Bangalore"; galo
echo substr($string,3,4);
$string="bangalore"; BANGALORE
echo
strtoupper($string);
echo 0
strcmp("rnsit","rnsit");
$str = "mca,rnsit,mca"; ,rnsit,
echo trim($str,"mca");
2. An explicit conversion can be done using the functions intval, doubleval or strval
Ex: intval($sum); //produces 4 .
3. The settype function can convert the first parameter to the type indicated by the second
parameter
Ex: settype($sum, "integer"); //produces 4
gettype:
• A program can determine the type of a variable in two ways:
• using the gettype function which returns the type as a string (which can also be "unknown")
• using one of the functions :
• is_int, is_integer, is_long ( which test for integers)
• is_double, is_real and is_float (which test for doubles)
• is_bool and is_string .
2.5 Output
• Any output from a PHP script becomes part of the document that the PHP processor is
building. Output must be in the form of an XHTML document.
The control string is a template that includes specifiers as to how the other parameters will be
printed:
%10s a character field of 10 characters
%6d an integer field of 6 character
%5.2f a float or double field of 5 characters and 2 decimal place
Example:
$day = "Tuesday";
$high = 79;
printf("The high on %7s was %3d", $day, $high);
Boolean Operators
• There are 6 Boolean operators (in order of precedence) : !, &&, ||, and, or, xor
Selection Statements
• The control structures in PHP are very similar to C/C++/Java.
• The control expression (or condition) can be any type and is coerced to Boolean.
• The control statements include:
if and if-else
while and do..while
for and foreach
if Statements :
The if statement in PHP is like that of C, although there is also an elseif. An if statement can
include any number of elseif clauses. The condition can be of any type but it is coerced to
Boolean.
Example:
Loop Statements
PHP has while, for and do-while loops that works exactly like those in JavaScript, as well as a
foreach statement.
Example :
Switch Statements
Example:
switch ( $bordersize )
{
case "0": print "<table>"; break;
case "1": print "<table border = "1">"; break;
case "4": print "<table border = "4">"; break;
case "8": print "<table border = "8">"; break;
default: print "Error – invalid value:", " $bordersize <br />";
}
<?php
for($number=1; $number<=10;
$number++)
{
$root = sqrt($number);
$square = pow($number, 2);
$cube = pow($number, 3);
print ("<tr align = 'center'>
<td> $number </td>");
print ("<td> $root </td> <td>
$square </td>");
print ("<td> $cube </td>");
}
?>
</table>
</body>
</html>
2.7 Arrays
• In PHP, there are two types of arrays:
Indexed arrays
Associative arrays or Hashes
Array Creation:
There are two ways:
1. By Assignment
2. By array() Construct
1. By Assignment:
$list1[0] = 17; # if $list1 does not exist, it creates and initializes the array
$list2[] = 5; # if Not previously defined this is the 0th element
$list2 [1] = "Today is my birthday!";
$list2 [] = 42 # stored in $list[2];
2. By array() Construct :
Arrays in PHP can be created by using the array() construct
Examples:
count( ) function: is used to return the length (the number of elements) of an array.
sizeof( ) function: returns the number of elements in an array.
unset( ) function: is used to delete entire array or a single element in the array.
array_keys ( ) and array_values( ) function: is used for the keys and the values can be
separately extracted from the array.
array_key_exists( ) function: The existence of an element in an array with a specific key can
be determined using array_key_exists, which returns a Boolean.
implode( ) and explode( ) function: Strings can be converted to arrays and vice versa using
explode and implode.
– explode : allows a string to be separated into different array elements
– implode : allows the elements of an array to be joined into a string
Examples Outputs
<?php
$cars = array("Volvo", "BMW", "Toyota");
3
echo count($cars);
?>
<?php
$list = array("Bob", "Fred", "Alan", "Bozo");
$len = sizeof($list); length = 4
Print "length = $len";
?>
<?php
$list = array(2, 4, 6, 8);
unset ($list[2]); 2,4,8
print_r( $list);
?>
<?php
$highs=array("Mon"=>74,"Tue"=>70,"Wed"=>67);
keys: Array ( [0] => Mon [1] => Tue
$days=array_keys($highs);
[2] => Wed )
$temps = array_values($highs);
print " keys: ";
Values : Array ( [0] => 74 [1] => 70
print_r($days);
[2] => 67 )
print "Values : ";
print_r($temps)
?>
<?php
$highs =
array("Mon"=>74,"Tue"=>70,"Wed"=>67);
The key exist
if (array_key_exists("Tue", $highs) )
{ print "The key exist"; }
?>
<?php
$rnsit=array(45,78,12,34);
$bms=25;
if(is_array($bms) )
false
{ print "true"; }
else
{ print "false"; }
?>
<?php
$people = array("vijay", "rakesh", "venu",
"pratheek");
if (in_array("venu", $people) )
Match found
{ echo "Match found"; }
else
{ echo "Match not found"; }
?>
<?php
$str = "rnsit mca dept";
$words = explode(" ", $str);
Array ( [0] => rnsit [1] => mca
Print_r( $words);
[2] => dept )
$str = implode(" ", $words);
rnsit mca dept
Print_r($str);
?>
Internally, the elements of an array are stored in a linked list of cells, Where each cell
includes both key and the value of the element.
The cell themselves are stored in memory through a key hashing function.So that they are
randomly distributed in a reserved block of storage.
Accesses to elements through string keys are implemented through the hashing function.
However, the elements all have links that connect them in the order in which they were
created.
The following figure shows the internal logical structure of an array. It shows how the two
different access methods could be supported.
current( ) : Every array has an internal pointer that references one element of the array,
which is initially pointing to the first element. It can accessed using the current function.
next( ):next function moves the next pointer to the next element in the array, if it is already
pointing to the last element, it returns false.
each( ) :it returns 2-element array, consisting of the key and "current" element's value.
o It only returns false if the current pointer has gone beyond the end of the array.
o The keys of these values are "key" and "value"
prev( ): the function prev returns the value of the previous element in the array.
key( ): the function key returns the key of the current element.
array_push( ) and array_pop( ) :allow the programmer to implement a stack.
foreach( ): allows each element in the array to be processed.
There are two forms:
o foreach (array as scalar_var) loop body
o foreach (array as key => value) loop body
Examples Outputs
<?php
$cities = array ("Bangalore", "Chennai");
$city = current ($cities); The first city is Bangalore
print "The first city is $city <br />";
?>
<?php
$city = current ($cities);
print "$city <br />"; Bangalore
while ($city = next ($cities)) Chennai
print "$city <br />";
?>
<?php
$salaries=array("a"=>4250,"b"=>5120,
"c"=>3790);
while ($employee = each ($salaries)) a salary is 4250
{ $name = $employee ["key"]; b salary is 5120
$sal = $employee ["value"]; c salary is 3790
print ("$name salary is $sal: <br/>");
}
?>
<?php
$cities = array_push ($cities,"Andhra");
Bangalore Chennai Andhra
print_r($cities);
?>
<?php
foreach ($cities as $temp)
Bangalore Chennai Andhra
print "$temp";
?>
<?php
$lows = array("Mon" =>32,"Tue"=>36); Temperature on Mon was 32
foreach ($lows as $day => $temp)
print "Temperature on $day was $temp"; Temperature on Tue was 36
?>
2.8 Functions
The general form of a function is:
• The main program passes actual parameters; the function receives formal parameters.
• The number of actual and formal parameters do not have to match.
– Excess formal parameters are unbounded.
– Excess actual parameters are ignored.
• Parameters are passed by value. If the function needs to return more than one variable, a
reference to the variable can be passed.
Scope of Variables
In PHP, variables can be declared anywhere in the script. The scope of a variable is the part of
the script where the variable can be referenced/used.
echo "Variable x outside function is: echo "Variable x outside function is:
$x"; $x";
?> ?>
Output: Output:
Variable x inside function is: Variable x inside function is: 5
Variable x outside function is: 5 Variable x outside function is:
Output: 15 Output: 0 1 2
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:
Ex:
<?php
function setHeight($minheight = 50)
{
echo "The height is : $minheight <br> ";
}
setHeight(350);
setHeight();
setHeight(135);
setHeight(80);
?>
Example:
<?php Output:
$college="Master of computer applications“;
if(preg_match("/of/", $college)) true
{ print "true"; }
else
{ print "false"; }
?>
• When PHP is used for form handling, the PHP scripts is embedded in an XHTML document.
• Based on the request method, we have to use implicit arrays for form values, $_POST and
$_GET.
• 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 elements and values
are the input data from the user.
• These($_GET and $_POST) 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.
Form.html Form.php
<html> <html>
<body> <body>
<form action="form.php" method="post"> Welcome
Name:<input type="text" name="name"><br> <?php echo $_POST["name"]; ?><br>
E-mail:<input type="text" name="email"><br>
<input type="submit" value="submit"> Your email address is:
</form> <?php echo $_POST["email"]; ?>
</body> </body>
</html> </html>
• 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 “form.php". The form data is sent with the HTTP POST
method.
2.11 Files
• PHP is a server-side technology, it is able to create, read and write files on the server system.
• PHP can deal with files residing on any server system on the internet, using HTTP and FTP
protocols.
All file operation in PHP is implemented as functions:
1. Opening and closing files
2. Reading from a file
3. Writing from a file
4. Locking files
fopen :
• The fopen function is used for to open a file, it takes two parameters, the filename, including
the path to it and a use indicator, which specifies the operation or operations that must be
performed on the file. Both parameters are given as string.
• Every open file has an internal pointer that is used to indicate where the next file operation
should take place within the file, we call this pointer the file pointer.
• The fopen function returns the reference to the file for the file variable.
r Open a file for read only. File pointer starts at the beginning of the file
r+ Open a file for read/write. File pointer starts at the beginning of the file
Open a file for write only. Erases the contents of the file or creates a new file if it
w
doesn't exist. File pointer starts at the beginning of the file
Open a file for read/write. Initializes the file pointer to the beginning of the file;
w+ creates the file if it does not exist. Always initializes the file pointer to the
beginning of the file before the first write, destroying any existing data.
Open a file for write only. The existing data in file is preserved. File pointer starts at
a
the end of the file. Creates a new file if the file doesn't exist
Open a file for read/write. Creating the file if necessary; new data is written to the
a+
end of the existing data.
file_exists:
The file_exists function takes a single parameter, the file’s name. It returns TRUE if the file
exists, FALSE otherwise.
Example: if( file_exists("count.dat") )
fclose :
A file is closed with the fclose function, which takes a file variable as its only parameter.
Example: fclose($file_var);
fread:
The fread function reads part or all of a file and returns a string of what was read.
This function takes two parameters, a file variable and the number of bytes to be read.
The reading operation stops when the specified number of bytes has been read or when
it reaches end-of-file.
If the whole file is to be read at once. the file's length is given as the second parameter to
fread.
The filesize function takes a single parameter, the name of the file(not the file variable).
Example: $file_string = fread ($file_var, filesize("count.dat"));
file:
One alternative to fread is file, which takes a filename as its parameter and returns an
array of all lines of the file.
Advantage of file is that the file open and close operations are not necessary.
Example: $file_lines = file("count.dat");
file_get_contents :
This function reads the entire contents of the file, which takes the file's name its
parameter.
It does not require to call fopen function.
Example: $file_string1 = file_get_contents ( "count.dat" );
fgets
A single line of a file can be read with fgets, which takes two parameters, the file
variable and a limit on the length of the line to be read.
Example: $line = fgets($file_var, 100);
The above statement reads characters from count.dat until it finds a newline character,
encounters the end-offile marker, or has read 99 characters.
fwrite:
The fwrite function takes two parameters, a file variable and the string to be written to
the file.
The fwrite function returns the number of bytes written.
Example: $bytes_written = fwrite ($file_var, $new_file);
The above statements writes the string value in $new_file to the file referenced with
$file_var and places the number of bytes written in $bytes_written.
2.13 Cookies
• A cookie is a small text 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.
• The first parameter, which is mandatory, is the cookie’s name given as a string. All other
parameters are optional.
• The second, if present, is the new value for the cookie, also a string.
• The third parameter, when present, is the expiration time in seconds for the cookie, given
as an integer.
• The default value for the expiration time is zero, which specifies that the cookie is destroyed
at the end of the current session.
• So, the cookie expiration time is given as the value returned from time plus some number.
• Cookies variables are set with the PHP global variable: $_COOKIE.
Example-1
<?php
setcookie("rnsit","webclass" , time()+3600*24); //3600 = 1hour
?>
Here, this call creates a cookie named rnsit whose value is webclass and lifetime is one day.
Create/Retrieve a Cookie
• The following example creates a cookie named "rnsit" with the value "webclass ". 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 :
<?php
Note: The setcookie() function must appear BEFORE the <html> tag.
Delete a Cookie
To delete a cookie, use the setcookie() function with an expiration date in the past:
Example :
2.14 Sessions
• A session is a way to store information (in variable) to be used across multiple pages.
• Unlike a cookie, the information is not stored on the user’s computer.
• A session arrays often store a unique session ID for a session.
• Session files are usually stored in /tmp/ on the server, and named sess_{session_id}.
• A session is started with the session_start( ) function.
• Session variables are set with the PHP global variable: $_SESSION.
• To remove all session variables use session_unset( ).
• To destroy the session use session_destroy( ).
Favourites.html Output:
<?php
session_start( ); Session variables are set.
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "dog";
echo "Session variables are set.";
?>
</body>
</html>
• 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:
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Echo session variables that were set on previous example Favourites.html
</body>
</html>
Output: Favorite color is : green
Favorite animal is : dog
• 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>
Output: Array ( [favcolor] => green [favanimal] => dog )
• Destroy a PHP Session : To remove all global session variables and destroy the session,
use session_unset( ) and session_destroy( ).
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php session_unset(); // remove all session variables
session_destroy(); // destroy the session
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.
Cookies Sessions
Cookies are client-side files that contain user Sessions are server-side files that contain
information user information
We have to set cookie max life time manually Session Max life time is 1440 Seconds(24
with php code with setcookie Minutes) as defined in php.ini file
In php $_COOKIE super global variable is In php $_SESSION super global variable is
used to manage cookie. used to manage session.
You don't need to start Cookie as It is stored Before using $_SESSION, you have to write
in your local machine. session_start();
Official MAX Cookie size is 4KB You can store as much data as you like
within in sessions.The only limits you can
reach is the maximum memory a script can
consume at one time, which by default is
128MB.