Module1 Notes (Srinivasulu M)
Module1 Notes (Srinivasulu M)
Module -1
Introduction to PHP and Building Web applications with PHP
Why PHP?
Overview of 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.
Dept. of MCA, UBDTCE, Davanagere Page 2
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>
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.
Examples :
Examples outputs
echo strlen("Hello 11
world");
echo strpos("Hello 8
world!", "r");
$string="Bangalore"; galo
echo substr($string,3,4);
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 .
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);
Control statements
Relational Operators
PHP has 8 relational operators:
The usual 6 (==, !=, >, >=, <, <=)
=== (which is true if both operands have the same value and type)
!== (which is the opposite of ===)
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
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>
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
$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"; }
?>
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.
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
?>
<!-- sorting.php - An example to illustrate several of the sorting functions --> Original Array
<html xmlns = "http://www.w3.org/1999/xhtml"> [Sonam] => 31
<head> <title> Sorting </title> </head> [Aliya]=>27
<body>
[Mallik ]=> abc
<?php
$original = array("Sonam"=>31,"Aliya"=>27,"Pooja"=>42, [Pooja] =>42
"Mallik"=>"abc" , "Pallavi"=>"xyz"); [Pallavi] => xyz
?> Array sorted with
sort
<h4> Original Array </h4> [0] => abc
<?php [1 ]=> xyz
foreach ($original as $key => $value)
print ("[$key] => $value <br />"); [2 ]=>27
[3] => 31
$new = $original; [4] =>42
sort($new); Array sorted with
?> asort
[Mallik ]=> abc
<h4> Array sorted with sort </h4>
<?php [Pallavi] => xyz
foreach ($new as $key => $value) [Aliya]=>27
print ("[$key] => $value <br />"); [Sonam] => 31
$new = $original; [Pooja] =>42
asort($new); Array sorted with
?>
ksort
<h4> Array sorted with asort </h4> [Aliya]=>27
<?php [Mallik]=>abc
foreach ($new as $key => $value) [Pallavi] => xyz
print ("[$key] => $value <br />"); [Pooja] =>42
$new = $original; [Sonam] => 31
ksort($new);
?>
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);
?>
Pattern matching.
PHP includes two different kinds of string pattern matching using regular expressions.
They are:
preg_match function
preg_split function
The preg_match function takes two parameters.
The first of which is the Perl-style regular expression as a string.
The second parameter is the string to be search.
The preg_match( ) function searches string for pattern, returning true if pattern exists, and
false otherwise.
Example:
<?php Output:
$college="Master of computer applications“;
if(preg_match("/of/", $college)) true
{ print "true"; }
else
{ print "false"; }
?>
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.
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
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.
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.
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
<?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 :
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( ).
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
// 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.
There is no function named unsetcookie( ) session_unset( ); is used to remove all session
variables.
Using databases
The PHP function mysql_connect connect a script to a MYSQL server.
This function takes three parameters, all of which are optional.
The first is the host that is running MYSQL. The default is localhost.
The second parameter is the username for MYSQL.
The third parameter is the password for the database.
Example:
$db=mysql_connect()
Or
$db=mysql_connect($hostname, $username,$password) ;
If the connect operation could fail, in which case the value returned would be false.
The call to mysql_connect usually is used in conjunction with die.
Example:
When running MySQL from the command line, a database must be selected as the
current database.
mysql_select_db('test_db');
if(! $retval )
{ die('Could not enter data: ' . mysql_error()); }
Handling XML.
PHP has excellent facilities for manipulating XML.
SimpleXML is a PHP extension that allows us to easily manipulate and get XML data.
SimpleXML provides an easy way of getting an element's name, attributes and textual
content if you know the XML document's structure or layout.
SimpleXML turns an XML document into a data structure you can iterate through like a
collection of arrays and objects.
The PHP simplexml_load_string() function is used to read XML data from a string.
The PHP simplexml_load_file() function is used to read XML data from a file.
Example:4 SimpleXMLElement->asXML()
It takes the properties of the SimpleXMLElement object and returns an XML document which contains
them.
<?php
$note ="<Student>
<StudentName>KIRAN</StudentName>
<StudentID>1rn19mca30</StudentID>
<Sem>IV</Sem>
<Subject>A.WEB</Subject>
</Student>";
$mca = new SimpleXMLElement($note);
echo $mca->asXML( );
?>
Output: KIRAN 1rn19mca30 IV A.WEB
$mca = simplexml_load_string($note);
foreach($mca->children() as $child)
{ echo “Child node: “ . $child . “<br />”; }
?>
Example:6
The attributes() function returns attributes and values within an XML tag.
The xpath() function runs an XPath query on the XML document.
This function returns an array of SimpleXMLElement on success, and FALSE of failure.
Details.xml Output:
Demo.php
<?php
$web = simplexml_load_file(“Details.xml”);
$result = $web->xpath(“Sem”);
Print_r($result);
?>