PHP Final Material

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 68

SHREE MARUTI VIDHYAMANDIR COLLEGE OF BUSSINESS MANGEMNET AND

COMPUTER SCIENCE – B.C.A BHAVNAGAR


PaperNo. Paper Code Subject Name Credit
CC-405 22700 Web Application Development using PHP 4

Unit Detailed syllabus Marks

Unit-1 Introduction 18

► Fundamental of webpage, website and apache server


► Static and Dynamic Website
► Introduction of PHP-Features, Advantages and Limitations
► Data Type, Variable, Constant
► Operator in PHP
Unit-2 Basic of PHP 18

► Conditional Statement
► Looping Statement
► Array- Types of Array(Numeric, Associative, Multi-dimensional)
► PHP Server variables
► Built-in-functions:
o String(print(),echo(),chr(),trim(),ltrim(),rtrim(),soundex(),str_word_count(),
strcmp(),stristr(),strstr(),strlen(), strpos(), strrev(), substr(), strtoupper(), strtolower(),
ucfirst(),ucword(),sucbstr_replace())
o Mathematical(abs(),sqrt(),log(),floor(),ceil(),pow(), max(),min())
o Date/Time(Date(),time(),getdate(),gettimeofday(), localtime(),checkdate())
Unit-3 Working with form , Cookie and Session 17

► Form elements- TextBox, TextArea, Password,RadioButton, Check Box, Combo Box, Image
► Buttons – Submit and Reset
► Uploading File to web server
► POST & GET method
► PHP include and require statement
► Basic of Cookie-Setting Cookies, Accessing Cookies, Deleting Cookies.
► Basic of Session- Starting a Session, Destroying a session.
Unit-4 Database Connectivity and Error Handling 17

► PHP-MySQL architecture
► Database interaction –Creating and connecting database
► Executing commands- Selecting, Inserting, Updating, Deleting
► Small application development
► Error Handling- Try, Catch and Throw block, die() function
► Page redirection in PHP
Reference Book :

1. Ivan Bayross,Sharanam Shah:PHP 5.1 For Beginners,Sh off Publishers &Distributors(SPD)


2. Janet Valade: PHP5 & MYSQL Projects, Wiley Dreamtech
3. Dave W. Mercer: Beginning PHP5,Wiley India Edition
4. Steven Holzer: The Complete Reference PHP,Tata McGRAW-HiLL,New Delhi.

CC-405 Web Application Development using PHP Page 1


SHREE MARUTI VIDHYAMANDIR COLLEGE OF BUSSINESS MANGEMNET AND
COMPUTER SCIENCE – B.C.A BHAVNAGAR
Unit-1 Introduction

► Fundamental of webpage, website and apache server


► Static and Dynamic Website
► Introduction of PHP-Features, Advantages and Limitations
► Data Type, Variable, Constant
► Operator in PHP

 Fundamental of webpage, website and apache server

 Web Page

A Web page is a document on the world wide web “With its own address”.

A web pages are delivered by web server to the user and displayed in web browser to act as a “retrieval
unit” for the information stored in within it.

A website consist of many web pages linked together under a common domain name.

A web page is a document written in HTML and can be viewed on any web browser.it is contained within
the web srever,which can be accessed by entering the URL(Uniform Resource Locator) for that web page,
and once it loaded,it appears on the user’s web browser.

A web page may contain text,links for other pages,graphics, videos etc.

The Web browser is connected to the Web server, where the website’s contents are hosted through
HTTP.
 Website
► Website is a collection of related web pages that may contain text, images, audio and video. The first
page of a website is called home page. Each website has specific internet address (URL) that you need to
enter in your browser to access a website.
► A website is a collection of Web pages that share a single domain name. Websites can be created and
maintained by an individual, group, business or organization to serve a variety of purposes.
► Website is hosted on one or more servers and can be accessed by visiting its homepage using a
computer network. A website is managed by its owner that can be an individual, company or an
organization.
► The first website was created in 1990 by Tim Berners-Lee, a British physicist at CERN. 3 years later, in
1993, CERN announced that everyone could access and use the World Wide Web for free.
► Every page is a single HTML document, and all of them are connected through hyperlinks (or simply
“link”) which can be combined in a navigation bar for ease of use.
► Originally, websites were categorized by their top-level domains. Some examples include:
► Government agency websites = .gov
► Educational institutions’ websites = .edu
► Nonprofit organizations’ websites = .org
► Commercial websites = .com
► Information sites = .info

CC-405 Web Application Development using PHP Page 2


SHREE MARUTI VIDHYAMANDIR COLLEGE OF BUSSINESS MANGEMNET AND
COMPUTER SCIENCE – B.C.A BHAVNAGAR
► A website can be of two types:
o Static Website
o Dynamic Website

Static website

Static website is the basic type of website that is easy to create. You don't need the knowledge of web
programming and database design to create a static website. Its web pages are coded in HTML.

The codes are fixed for each page so the information contained in the page does not change and it looks
like a printed page.

► Advantages of a static website

Faster page loading speed


Quick creation
Potential for enhanced security
► Disadvantages of a static website
Limited scalability
Less efficient management

Dynamic website

Dynamic website is a collection of dynamic web pages whose content changes dynamically. It accesses
content from a database or Content Management System (CMS). Therefore, when you alter or update
the content of the database, the content of the website is also altered or updated.

Dynamic website uses client-side scripting or server-side scripting, or both to generate dynamic content.

Client side scripting generates content at the client computer on the basis of user input. The web
browser downloads the web page from the server and processes the code within the page to render
information to the user.

CC-405 Web Application Development using PHP Page 3


SHREE MARUTI VIDHYAMANDIR COLLEGE OF BUSSINESS MANGEMNET AND
COMPUTER SCIENCE – B.C.A BHAVNAGAR
In server side scripting, the software runs on the server and processing is completed in the server then
plain pages are sent to the user.

► Advantages of a dynamic website vs a static website


Easily updated
A better user experience
► Disadvantages of a dynamic website
It takes more resources to create
Performance issues
 What is Web Server
► Mail servers, database servers, web servers, and file servers use different types of server software. All
these applications may access a lot of files saved on the physical server and apply them for many
objectives.
► The aim of the web servers is to deliver websites over the internet. It behaves as a middleman among the
client machines and servers to achieve that aim. It can pull the content through the server over every user
request. Also, it delivers this request to the web.
► One of the most critical tasks of any web server is to provide services to various different users of the web
at the same time. Web servers execute files specified in a different type of programming languages like
Java, Python, PHP, and many others. Web servers turn these files into static HTML files. It provides
services to these files within the web server browser. Web browser can be defined as a tool for decent
client-server communication.
 Apache Server
► Apache is free and open-source software of web server that is used by approx 40% of websites all over
the world. Apache HTTP Server is its official name. It is developed and maintained by the Apache Software
Foundation. Apache permits the owners of the websites for serving content over the web. It is the reason
why it is known as a "web server." One of the most reliable and old versions of the Apache web server
was published in 1995.
► If someone wishes to visit any website, they fill-out the name of the domain in their browser address bar.
The web server will bring the requested files by performing as the virtual delivery person.
 Working Of Apache
► Apache is not any physical server; it is software that executes on the server. However, we define it as a
web server. Its objective is to build a connection among the website visitor browsers (Safari, Google
Chrome, Firefox, etc.) and the server. Apache can be defined as cross-platform software, so it can work on
Windows servers and UNIX.

CC-405 Web Application Development using PHP Page 4


SHREE MARUTI VIDHYAMANDIR COLLEGE OF BUSSINESS MANGEMNET AND
COMPUTER SCIENCE – B.C.A BHAVNAGAR
► When any visitor wishes for loading a page on our website, the homepage, for instance, or our "About Us"
page, the visitor's browser will send a request on our server. Apache will return a response along with
each requested file (images, files, etc.). The client and server communicate by HTTP protocol, and Apache
is liable for secure and smooth communication among t both the machines.

 Fundamental of PHP
► PHP was originally created by Rasmus Lerdorf in 1995.
► It was used by him to maintain his personal web pages PHP code can embedded with HTML very easily no
need to call an external file to process data.
► PHP needs interpreter to process and convert its code into binary.
► PHP code is interpreted by a web server with a PHP processor module which generates the resulting web
page.
► Full form of PHP is hypertext preprocessor.
► It was previously known as personal home page
► PHP is one type of server side scripting language so PHP code executes on server rather than on client
► PHP is basically used to create dynamic web pages
► Dynamic web page's content vary according to place, time, user and behavior of user To generate such
type of website or webpage one neck-to use server side scripting language and many more tools &
technology like HTML JavaScript, CSS, AJAX, etc.
► PHP is one of the most popular and widely used accepted server side scripting language.
► PHP is a server-side scripting language, which is used to design the dynamic web applications with MySQL
database.
► It handles dynamic content, database as well as session tracking for the website. o You can create sessions
in PHP.
► It can access cookies variable and also set cookies.
► It helps to encrypt the data and apply validation.
 Features of PHP
► PHP is open source, free to download and use
► PHP is on different platforms (Windows, Linux, UNIX PHP is compatible with many servers, PHP supports
popular database servers (MySQL, Intermix, Grace Sybase, Solid PostgreSQL, Genere ODBC.ctc.)
► PHP has extremely useful text processing feature PHP is easy to learn.
► PHP combined with MySQL can develop in windows and serve on a unix platform)
► Online help and technical documentation is available.
► PHP a wide range of protocol
 Advantages of PHP
► Some of PHP's main competitors are Perl, Microsoft Active Server Pages (ASP), Java Server Pages (JSP).
► In comparison to these products, PHP has many strengths including the followings
1 High performance
2 Interfaces to many different database systems
3 Built-in libraries for many common web tasks
4 Low cost

CC-405 Web Application Development using PHP Page 5


SHREE MARUTI VIDHYAMANDIR COLLEGE OF BUSSINESS MANGEMNET AND
COMPUTER SCIENCE – B.C.A BHAVNAGAR
5 Easy of learning and use 6 Portability
7. Availability of source code
(1) Performance
► PHP is very efficient using a single inexpensive serve; you can serve millions of hits per day.

(2) Database integration


► PHP has a native connection available to many database systems In addition to MySQL You can directly
connect to SQL, MySQL, Oracle, Informix, InterBase, and Sybase databases, among others.
► Using the open database connectivity standard (ODBC), you can connect to any database that provides on
ODBC driver. This includes Microsoft products, and database others.
(3) Built-in libraries
► Because PHP was designed for performing many useful Web-related tasks.
► You can generate GIF images on the-lly, connect to other network services, send email, work with cookies
and generate PDF documents, all with just a few lines of code.
(4) Cost
► You can download the latest version at any time from http://www.php.net for no charge.
► PHP is free.
(5) Learning PHP
► The syntax of PHP is based another programming languages, primarily and Perl.
► If you already know C or Perl, or C-loke language such as C++ or Java, you will be productive using PHP
almost immediately.
(6) Portability
► PHP is available for many different operating systems! You can write PHP code on the free UNIX like
operating systems such as Linux and FreeBSD, commercial UNIX versions such as Solaris and or on different
versions of Microsoft Windows.
► Your code will usually work without modification on a different system running PHP.
(7) Source code
► you have access to the source code of PHD) Unlike commercial, closed-source products, if there is
something you want modified or added to the language, you are free to do this.
► You do not need to wait for the manufacturer to release patches.
► You don't need to worry about the manufacturer going out of business or deciding to stop supporting a
product.
 Disadvantages of PHP
► It has a weak type, which can cause incorrect data and knowledge to users.
► It is not suitable for giant content-based web applications.
► PHP doesn’t allow change or modification in the core behavior of online applications.
► It is not that secure due to its open-source, because the ASCII text file is often easily available.
 Data types
► PHP has several types of variables. All holds a specific class of information, except one. The PHP variable
types are:

CC-405 Web Application Development using PHP Page 6


SHREE MARUTI VIDHYAMANDIR COLLEGE OF BUSSINESS MANGEMNET AND
COMPUTER SCIENCE – B.C.A BHAVNAGAR
(1) Integer
► Integer variables hold whole numbers, either positive or negative.
► There is a minimum and a maximum limit to the size of integers. Le. -2147483647 to 2147483647.
► Any numbers lower than -2147483647 and higher than 2147483647 are automatically converted to
floats. For ex. 0, -50, 229653 etc.
(2) Float
► Float variables hold fractional numbers as well as very high integer numbers. For ex, 3,5,-55,36,
2147483647000 etc.
(3) String
► String variables hold a sequence of characters that are always internally NULL terminated Strings can be
as short or as long as desired. There is no limit to the size of strings.
► For ex. ”C", "PHP”,” Windows Apache Mysql Php” etc.
(4) Boolean
► Boolean variables hold TRUE or FAISE Bend the scenes these are just integers.
► PHP considers the number o to be FALSE and everything else to be TRUE...
► For ex, TRUE, FALSE, 01etc.
(5) Array
► Array variables hold group of multiple values.
► They are a great way of storing variables that naturally collect together such as colors, day to the week,
members of a team or items in a shopping basket etc.
(6) Object
► Object variables are complex variables that have multiple values.
► They also have their own functions (ie methods) for accessing or manipulating their content.
(7) Resource
► Resource variables are variables that hold anything that is not PHP data.
► This could be picture data loaded from a file, the result of an SQL query etc.
► A resource type variable is used like any other variable with the key difference being that they should be
freed up when not required.
 Variables
► Variables are nothing but identifiers which point to a memory location (RAM) in which data is stored.
► Variables in PHP are quite different from compiled languages such as C and Java. This is because PHP
variables are weakly typed. This means that when a variable is being defined their data type is not declared
prior their use. The PHP variable takes its data type from the user defined value that is being stored in it. As
a result, a PHP variable can change its type as often as needed.
► A PHP variable must be named/declared starting with the $ character followed by a letter. The rest of the
variable name can consist of a mix of both alphabets and numbers.
► The underscore (_) character can also be used in variable names. It is used as a replacement for space as
space is a character that cannot be used when naming a PHP variable.
► The following are the valid examples of variables.
$age=23;
$balance=10000.76;
$gender=M;
$First name=”abc";
► There is no limit on the size of the variables in PHP.

CC-405 Web Application Development using PHP Page 7


SHREE MARUTI VIDHYAMANDIR COLLEGE OF BUSSINESS MANGEMNET AND
COMPUTER SCIENCE – B.C.A BHAVNAGAR
► PHP do not require variables to be declared Before Being initialized. They can simply be populated with a
value and put into action whenever and wherever required.
 Constants
► A constant like variables temporary placeholder in memory that holds a value. Unlike variable the value of a
constant never changes.
► For ex. PI (3.14) or the value of midnight (12:00 am) are examples of constants applicable in a real life
scenario.
► The names for constants have the same rules as variables except that they do not have the leading dollar
sign..
► To declare a constants the define() function is used. It requires the name of the constant and the value that
is required to be assigned to that constant.
► A constant may be a string, an integer or a floating point value.
► For ex, define("AUTHOR", "Maruti");
define("HOUR”,12);
define("PI”,3.14);
► The constant name is always in uppercase. String values must be enclosed in quotation marks. Although
they can be created anywhere in the script, it is considered good practice to put them at the beginning of
the script.
► Unlike variables, constants, once defined are globally accessible. Constants need not be declared again and
again in each new function and PHP script.
► Unlike variables a script cannot change the value of a constant.

 Operators
► An operator is any symbol used to perform an operation on a value. PHP operators can be classified into
the following three categories:
(1) Unary Operators
(2) Binary Operators
(3) Ternary operators
 Unary Operators
i. Negation Operators
Operator Meaning Example Description Result
! Logical Negation $x=2, !($x==2) TRUE if the operand evaluates to TRUE
FALSE, FALSE if the operand evaluates
to TRUE
~ Bitwise Negation $x=2, $y=~$x One is added to the bits of $x and also $y=-3
reverse it's sign.

ii. Increment/Decrement Operator


Operator Meaning Example Description Result
$x++ Post Increment $x=2, $y=$x++ $x is assigned first to $y And then it $x=3
will be incremented by 1 $y=2
++$x Pre Increment $X=2,$y=++$x $x is incremented by 1 first and then it $x=3
will be assigned to $Y $y=3

CC-405 Web Application Development using PHP Page 8


SHREE MARUTI VIDHYAMANDIR COLLEGE OF BUSSINESS MANGEMNET AND
COMPUTER SCIENCE – B.C.A BHAVNAGAR
$x-- Post Decrement $x=2, $y=$x-- $x is assigned first to $y And then it $x=1
will be decremented by 1 $y=2
--$x Pre Decrement $X=2,$y=--$x $x is decremented by 1 first and then $x=1
it will be assigned to $Y $y=1

(iii) Cast Operators


Operator Meaning Example Description Result
Int Integer $n=(int)12.24 $n is assigned the integer value $n=12

(2) Binary Operators


(i) Arithmetic/Numeric Operators
Operator Meaning Example Description Result
+ Addition $x=2,$y=2 Sum of $x and $y 4
$x+$y
- Subtraction $x=2,$y=2 Difference of $x and $y 0
$x-$y
* Multiplication $x=2,$y=2 Product of $x and $y 4
$x*$y
/ Division $x=2,$y=2 Division of $x and $y 1
$x/$y
% Modulus $x=2,$y=2 Remainder of $x and $y 0
$x%$y

(ii) Assignment Operators


Operator Meaning Example Description Result
= Equals to $y=2,$x=$y The value of $y is assigned to $x $x=2

+= Plus Equals to $x=10,$y=2 ,$x+=$y $x+=$y is same as $x=$x+$y $x=12


-= Minus Equals to $x=10,$y=2 ,$x-=$y $x+=$y is same as $x=$x-$y $x=8
*= Multiply Equals to $x=10,$y=2 ,$x*=$y $x+=$y is same as $x=$x*$y $x=20
/= Divided Equals to $x=10,$y=2 ,$x/=$y $x+=$y is same as $x=$x/$y $x=5
.= Dot Equals to $x=10,$y=2 ,$x.=$y $x+=$y is same as $x=$x.$y $x=102
%= Modulus Equals to $x=10,$y=2 ,$x%=$y $x+=$y is same as $x=$x%$y $x=0

(iii) Concatenation Operator


Operator Meaning Example Description Result
. Dot(Concatenation) “Sita”.”Ram” It concates two strings “SitaRam”
(iv) Comparison Operators
Operator Meaning Example Description Result
== Is Equals to $x=1,$y=2 If $x is equals to $y False
$x==$y
!= Is not Equals to $x=1,$y=2 If $x is not equals to $y True
$x!=$y

CC-405 Web Application Development using PHP Page 9


SHREE MARUTI VIDHYAMANDIR COLLEGE OF BUSSINESS MANGEMNET AND
COMPUTER SCIENCE – B.C.A BHAVNAGAR
< Is less than $x=2,$y=1 If $x is less than $y False
$x<$y
<= Is Less Than or $x=1,$y=1 If $x is less than or equals to $y True
Equals to $x<=$y
> Is greater than $x=2,$y=1 If $x is greater than $y True
$x>$y
>= Is greater than or $x=1,$y=1 If $x is greater than or equals to $y True
Equals to $x>=$y
=== Is Identical to $x=1, $y=”1” If $x is identical to $y False
$x===$y
!== Is not Identical $x=1, $y=”1” If $x is not identical to $y True
to $x!==$y

(v) Logical Operators


Operator Meaning Example Description Result
&&,and AND $x=15,$y=10,$z=20 If $x is greater than $y and less than True
$x > $y and $x<$z $z
||,Or Or $x=5,$y=10,$z=20 If $x is greater than $y or less than True
$x > $y or $x<$z $z
(vi) Bitwise Operators
Operator Meaning Example Description Result
& Bitwise AND $x=12,$y=9 It compares all the bits in $x against $y and $z=8
$z=$x & $y returns a result with all the joint bits.
! Bitwise OR $x=12 , $y=9 It compares all the bits in $x against $y and $z=13
$z=$x | $y returns a result with all the bits set in either
of them.
^ Bitwise XOR $x=12,$y=9 It compares all the bits in $x against $y and $z=5
$z= $x^$y returns a result with all the bits set in either
of them but not both.
<< Bitwise Shift Left $x=12,$y=2 It shifts the bits of $x,$y steps to left (each $z=48
$z= $x<<$y step means “multiply by two”)
>> Bitwise Shift Right $x=12,$y=2 It shifts the bits of $x,$y steps to right (each $z=3
$z= $x>>$y step means “divide by two”)

(3) Ternary Operator


Operator Meaning Example Description Result
Condition Ternary $x=20 If $x is less than or x is >15 X is >15
?(true):false (conditional) $Ans=($x<=15)? equals to 15 then $Ans="x is
<=15" else $Ans="x is > 15"
“x is <=15” : ”x is >15”

CC-405 Web Application Development using PHP Page 10


SHREE MARUTI VIDHYAMANDIR COLLEGE OF BUSSINESS MANGEMNET AND
COMPUTER SCIENCE – B.C.A BHAVNAGAR
 What is the difference between two types of quotes in string variables?
► When assigning a string value to a variable it must be enclosed in quotes. Either single quotes (") or double
quotes ("").
► Single quotes used only when user wants to print any string which does not contain any variable.
► For ex:
<?php
echo 'This is a simple string which does not contain any variable;
?>
► While double quotes are used only when user wants to print any string which contains variables or HTML
tags.
For ex.
<?php
$str="Double quoted string";
echo "<br>This is a $str which having a variable str and break tag for newline";
?>
 Explain: PHP is loosely typed language.
In PHP a variable does not need to be declared before using it.
<?php
$n=10;
?>
► In the above example, there is no need to tell the PHP that which type of the variable is. PHP automatically
converts the variable to the correct data type. Depending on how they are set.
► In a strongly typed-programming language, you have to declare the data type before the name of the
variable and then only you can use it.
► In PHP the variable is declared automatically when you use it.
 Explain the concept of variable variables in PHP.
► Variable variables allow accessing the contents of a variable without knowing its name directly. This is like
indirectly referring a variable.
For ex.
<?php
$version=5.1;
$name="version";
print "The version of PHP is $$name";
?>
► The output of the above code will be: The version of PHP is 5.1
► Here using $version which is quite straight forward, while using $$name PHP will look up the contents of
$name, convert it to a string, then look up the variable of the same name and return its value.
► In above example, $name contains the string version and so PHP will look up the variable named $version
and output its value in this case it will be 5.1.
► Similarly,
► <?php
$version=5.1;
$name="version";
$php="name";
$language="php";
print "The version of PHP is <br/>";

CC-405 Web Application Development using PHP Page 11


SHREE MARUTI VIDHYAMANDIR COLLEGE OF BUSSINESS MANGEMNET AND
COMPUTER SCIENCE – B.C.A BHAVNAGAR
print $version."<br/>";
print $$name."<br/>";
print $$$php."<br/>";
print $$$$language<br>”;
?>
► Output of the above code will be:
The version of PHP is
5.1
5.1
5.1
5.1
 What is Here Document?
► HERE documents special form of I/O redirection to feed a command list to an interactive program of
command.
► It gives a way of including large blocks of text instead of using multiple statements.
► For ex:
<?php
$name="Maruti college”;
$wish="Best Of Luck";
echo <<<EOF
This is a demo of here document
which contains text, variables and html tags.<br/>
Hello friends, this is $name wishes to all of you $wish for your examinations.
EOF;
?>
Output of the above code will be:
► This is a demo of here, document which contains text, variables and html tags. Hello friends, this is Maruti
College wishes to all of you Best Of Luck for your examinations.
► Similarly,
<?php
$name="Maruti College";
$str=<<<EOF
Key to Happiness <br/>
Always be happy whether you will get success or failure in your life.<br>-By $name.
EOF;
echo $str;
?>
Output of the above code will be:
Key to Happiness Always be happy whether you will get success or failure in your life.
-By Maruti College.
► The text within a here document is interpreted according the same substitution rules as a double-quoted
string, so variables, HTML tags and escape characters can also be included.
 Scope of variable
► A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside a function.
► A variable declared within a function has a LOCAL SCOPE and can only be accessed within that function.
► The following example tests variables with local and global scopes
<?php
$x=5; //global scope

CC-405 Web Application Development using PHP Page 12


SHREE MARUTI VIDHYAMANDIR COLLEGE OF BUSSINESS MANGEMNET AND
COMPUTER SCIENCE – B.C.A BHAVNAGAR
function myTest()
{
$y=10; // local scope
echo “<p> Test variables inside the function: <p>”;
echo “Variable X is : $x”;
echo “<br>”;
echo "Variable y is : $y”;
}
myTest();
echo "<p>Test variables outside the function <p>";
echo "Variable x is : $x”;
echo "<br>";
echo "Variable y is: Sy":
?>
► In the example above there are two variables $x and $y and a function myTest(). $x is a global variable since
it is declared outside the function and $y is a local variable since it is created inside the function.
► When we output the values of the two variables inside the myTest() function, it prints the value of $y as it is
the locally declared, but cannot print the value of $x since it is created outside the function.
► Then, when we output the values of the two variables outside the myTest() function, it prints the value of $x,
but cannot print the value of $y since it is a local variable and it is created inside the myTest() function.

 How to declare and access global variable in PHP?


► In PHP global variables must be declared global inside a function if they are going to be used in that
function.
► Using global
<?php
$a = 1;
$b=2;
function Sum()
(
global $a, $b;
$b=$a+ $b;
}
Sum();
echo $b;
?>
► The above script will output 3.by declaring $a and $b global within the function, all references to either
variable will refer to the global version. There is no limit to the number of global variables that can be
manipulated by a function.
► A second way to access variables from the global scope is to use the special PHP-defined $GLOBALS array.
The previous example can be rewritten as:

CC-405 Web Application Development using PHP Page 13


SHREE MARUTI VIDHYAMANDIR COLLEGE OF BUSSINESS MANGEMNET AND
COMPUTER SCIENCE – B.C.A BHAVNAGAR
► Using $GLOBALS
<?php
$a=1;
$b = 2;
function Sum();
{
$GLOBALS['b'] = $GLOBALS['a']+ $GLOBALS['b'];
}
Sum();
echo $b;
?>
The $GLOBALS array is an associative array with the name of the global variable being the key and the
contents of that variable being the value of the array element.
 How to declare and access static variable in PHP?
► A static variable exists only in a local function scope, but it does not lose its value when program
execution leaves this scope.
<?php
function test()
{
static $a = 0;
echo $a;
$a++;
}
?>
► Here, $a is initialized only in first-call of function and every time the test() function is called it will print the
value of $a and increment it.
► Static variables also provide one way to deal with recursive functions.
► Declaring static variables
<?php
function test()
{
static $int = 0; //correct
static $int=1+2; //wrong (as it is an expression)
static $int=sqrt(121); // wrong (as it is an expression too)
$int++;
echo $int;
}
?>
► Static declarations are resolved in compile time.

CC-405 Web Application Development using PHP Page 14


SHREE MARUTI VIDHYAMANDIR COLLEGE OF BUSSINESS MANGEMNET AND
COMPUTER SCIENCE – B.C.A BHAVNAGAR
Unit-2 Basic of PHP
► Conditional Statement
► Looping Statement
► Array- Types of Array(Numeric, Associative, Multi-dimensional)
► PHP Server variables
► Built-in-functions:
o String(print(),echo(),chr(),trim(),ltrim(),rtrim(),soundex(),str_word_count(),
strcmp(),stristr(),strstr(),strlen(), strpos(), strrev(), substr(), strtoupper(), strtolower(),
ucfirst(),ucword(),sucbstr_replace())
o Mathematical(abs(),sqrt(),log(),floor(),ceil(),pow(), max(),min())
o Date/Time(Date(),time(),getdate(),gettimeofday(), localtime(),checkdate())
 PHP Server Variables
► All web servers capture and hold information such as the URL from which the user request came from,
which browser is being used and so on. This information is stored in server variables.
► In PHP, $_SERVER is a reserved variable that contains all such web server information. The following
example will display the information such as:
► URL the server request came from
► User's browser name
► User's IP address
<?php
echo "Referrer: ".$_SERVER["HTTP_HOST”+,"<br/>";
echo “Browser : “.$_SERVER*“HTTP_USER_AGENT"+."<br/>";
echo "IP Address : “.$_SERVER*“REMOTE_ADDR"+”.<br/>";
?>
Output: Referrer: localhost
Browser: Mozilla/4.0
IP Address: 127.0.0.1
► The variable $_SERVER is just one variable that PHP automatically makes available to programmers.
► The complete list of PHP server variables can be obtained by running the following PHP script which displays
all the server variables with their values.
► <?php
phpinfo(INFO_VARIABLES);
?>
► Some of the variables with their values are as follows:

Variable Value
$_SERVER["SERVER ADMIN"] admin@127.0.0.1
$_SERVER["REMOTE_PORT] 1604
$_SERVER*"REQUEST_METHOD”+ GET
$_SERVER*“PHP_SELF"+ /index.php
$_SERVER["REQUEST_TIME"] 1366860955

CC-405 Web Application Development using PHP Page 15


SHREE MARUTI VIDHYAMANDIR COLLEGE OF BUSSINESS MANGEMNET AND
COMPUTER SCIENCE – B.C.A BHAVNAGAR
$_SERVER["DOCUMENT_ROOT"] C:/Program Files/PHP/www
$_SERVER["REMOTE ADDR”+ 127.0.0.1
$SERVER["SERVER_ADDR"] 127.0.0.1
$SERVER["SERVER NAME”+ 127.0.0.1
$_SERVER["SERVER_SOFTWARE"] Apache/2.4.2 (Win32) PHP/5.4.6
$_SERVER["GATEWAY INTERFACE"] CGI/1.1
$_SERVER["SERVER_PORT"] 8000
$_SERVER["REQUEST SCHEME"] http
 PHP Superglobal Variables
► Superglobals are variables that are automatically available throughout all program code, in all scopes.
► These variables require no declaration they can simply be accessed.
► Superglobal variables provide:
 Useful information about the environment
 Allow access to HTML form variables or parameters
 Access to cookies stored on a client
 Keeping track of sessions and file uploads
They are as follows:
(1) $_GET
► $_GET is used for data passed using the HTTP GET METHOD, which includes variables passed as part of the
URL.
► For ex. www.maruticollege.com/index.php?book=PHP&author=Geeta
► The GET method is conventionally used when the processing script has no lasting observable effect, such as
changing a value in a database table.
(2) $_POST
► $_POST is used for data passed using the HTTP POST method, which does not includes any variables passed
part of the URL .
► For ex www.maruticollege.com/index.php
► The POST method is conventionally or when the contents of an HTML form are going to change values in a
database table or make some other permanent change.
(3) $_REQUEST
► $_REQUEST holds variables provided to the script via the GET POST and COOKIE input mechanisms.
► The presence and the order of variable inclusion in this array are defined according to the PHP
variables_order configuration directive. It is preferable to use this specific superglobal variable, if it is not
known how the variables are being passed (ie. which method GET or POST is being used) for a particular
script.
► Additionally, this superglobal variable also contains all the information contained in $ COOKIE.
► $_REQUEST can be put into action simply by replacing $_GET or $_POST with $_REQUEST and the result
would be identical.

CC-405 Web Application Development using PHP Page 16


SHREE MARUTI VIDHYAMANDIR COLLEGE OF BUSSINESS MANGEMNET AND
COMPUTER SCIENCE – B.C.A BHAVNAGAR
(4) $_FILES
► $_FILES holds variables provided to the script via HTTP post file uploads to provide feedback to the script.
(5) $_COOKIES
► COOKIE contains all variables passed from HTTP cookies.
(6) $_SESSION
► $_SESSION holds variables which are currently registered to a script's session,
(7) $_GLOBALS
► This is a final superglobal variable that can be used for forms. This would mean it is a superglobal, as it
contains references to all variables in the script's global scope.
► Replacing $_GET or $_POST with $GLOBALS in the script would also have the identical results.
► The keys of this array are the names of the global variables.
(8) $_SERVER
► It holds the information of all the variables set by the server or otherwise directly related to the execution
environment of the current script.
(9) $_ENV
► $_ENV holds variables provided to the script via the environment.
 Conditional Statements
(1) if statement
Use the if statement to execute some code only if a specified condition is true.
Syntax
If(condition)
Code to be executed if condition is true;
The following example will output "The value of i is less than 20".
<?php
$i=10;
if($i<20)
echo "The value of less than 20”;
?>
(2) if else statement
Use the if...else statement to execute some code if a condition is true and another code if a condition is
false.
Syntax
If(condition)
Code to be executed if condition is true;
else
Code to be executed if condition is false;

CC-405 Web Application Development using PHP Page 17


SHREE MARUTI VIDHYAMANDIR COLLEGE OF BUSSINESS MANGEMNET AND
COMPUTER SCIENCE – B.C.A BHAVNAGAR
The following example will output “The value of i is less than 20".
<?php
$i=30;
if($i<=20)
echo "The value of i is less than or equals to 20";
else
echo "The value of i is greater than 20";
?>
(3) else if ladder statement
Use the if....elseif...else statement to select one of several blocks of code to be executed.
Syntax
if(condition)
Code to be executed if condition is true;
elseif(condition)
Code to be executed if condition is false;
Else
Code to be executed if condition is false;
The following example will output "The value of i is equals to 20".
<?php
$i=20;
if($i<20)
echo "The value of i is less than 20";
else if($i>20)
echo "The value of i is greater than 20";
else
echo "The value of i is equals to 20";
?>
(4) nested if statement
Use the nested if. .. else statement to select one of several blocks which also contains the selection of
blocks nested to it of code to be executed..
Syntax
if(condition)
{
if(condition)
Code to be executed if condition is true;
else
Code to be executed if condition is false;
}
else

CC-405 Web Application Development using PHP Page 18


SHREE MARUTI VIDHYAMANDIR COLLEGE OF BUSSINESS MANGEMNET AND
COMPUTER SCIENCE – B.C.A BHAVNAGAR
{
If(Condition)
Code to be executed if condition is true;
else
code to be executed if condition is false;
}
The following example will output "Largest value is 20"
<?php
$a=5,$b=10,$c=20;
if($a> $b)
{
if($a>$c)
echo "Largest value is $a";
else
echo "Largest value is $c";
}
else
{
if($c>$b)
echo "Largest value is $c";
else
echo "Largest value is $b";
}
?>
(5) switch statement
Use the switch statement to select one of many blocks of code to be executed.
Syntax:
switch ($n)
{
case label1:
Code to be executed if n=label1;
break;
case label2:
Code to be executed if n=label2;
break;
default:
Code to be executed-if n is different from bath label1 and label2;
}

CC-405 Web Application Development using PHP Page 19


SHREE MARUTI VIDHYAMANDIR COLLEGE OF BUSSINESS MANGEMNET AND
COMPUTER SCIENCE – B.C.A BHAVNAGAR
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 a
match, the block of code with that case is executed. Use break to prevent the code from running into
the next case automatically. The default statement is used it no match is found.
<?php
$d=date("D");
switch($d)
{
case "sun":
print "It is Sunday";
break;
case "mon":
print "It is Monday";
break;
case "tue":
print "It is Tuesday";
break;
case "wed":
print "It is Wednesday":
break;
case "thu":
print "It is Thursday";
break;
case "fri":
print "It is Friday";
break;
case "sat":
print "It is Saturday";
break;
default:
print "No number between 1 and 7";
}
 Looping Statements
(1) for loop
► The for loop is used when you know in advance how many times the script should run.
► Syntax:
for (initializaion; condition; increment)
{
code to be executed;
}

CC-405 Web Application Development using PHP Page 20


SHREE MARUTI VIDHYAMANDIR COLLEGE OF BUSSINESS MANGEMNET AND
COMPUTER SCIENCE – B.C.A BHAVNAGAR
► The for loop is used when you know in advance how many times the script should run.
► Parameters:
initialization: Mostly used to set a counter (but can be any code to be executed once at the beginning of
the loop)
condition: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. if it evaluates to
FALSE, the loop ends.
increment: Mostly used to a counter (but can be any code to be executed at the end of the loop)

Each of the parameters above can be empty, or have multiple expressions (separated by commas),
The example below defines a loop that starts with i=1. The loop will continue to run as long as is less
than, or equal to 5. I will increase by 1 each time the loop runs:
<?php
for ($i=1; $i<5; $i++)
echo "The number is “.$i."<br />";
?>
(2) while loop
The while loop executes a block of code while a condition is true.
Syntax
initializaion;
while (condition)
{ code to be executed;
increment/decrement;
}
The example below defines a loop that starts with i=1. The loop will continue to run as long as i is less
than, or equal to 5. i will increase by 1 each time the loop runs:
<? php
$i=1;
while($i<=5)
{
echo "The number is ".$i."<br />";
$i++;
} ?>
3)do while loop
The do...while statement will always execute the block of code once, it will then check the condition,
and repeat the loop while the condition is true. Syntax
initialization;
do
{
code to be executed;
increment/decrement;

CC-405 Web Application Development using PHP Page 21


SHREE MARUTI VIDHYAMANDIR COLLEGE OF BUSSINESS MANGEMNET AND
COMPUTER SCIENCE – B.C.A BHAVNAGAR
}while (condition);
The example below defines a loop that starts with 1-1. It will then increment i with 1, and write some
output. Then the condition is checked, and the loop will continue to run as long as t is less than, or equal
to 5:
<?php
$i=1;
do
{
echo "The number is “.$i."<br/>
$i++;
}while ($i<=15);
(4) foreach loop.
The foreach loop is used to loop through arrays.
Syntax
foreach ($array as $value)
{ code to be executed;
}
For every loop iteration, the value of the current array element is assigned to $value (and the array
pointer is moved by one) - so on the next loop iteration, you'll be looking at the next array value.
<?php
$x=array("one", "two", "three");
foreach ($x as $value)
{
echo $value.<br/>;
}
?>
 Array
► 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.
► PHP, there are three kind of arrays:

CC-405 Web Application Development using PHP Page 22


SHREE MARUTI VIDHYAMANDIR COLLEGE OF BUSSINESS MANGEMNET AND
COMPUTER SCIENCE – B.C.A BHAVNAGAR
Numeric array - Ah array with a numeric index
Associative array - An array where each ID key is associated with a value
Multidimensional array - An array containing one or more arrays
(1) Numeric Array
► A numeric array stores each array element with a numeric index.
► There are two methods to create a numeric array.
► In the following example the index are automatically assigned (the index starts at 0):
$cars=array("Saab","Volvo", "BMW", "Toyota");
► In the following example we assign the index manually:
$cars[0]="Saab"; Scars[1]="Volvo";
$cars[2]="BMW";
$cars[3]="Toyota":
► 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.";
?>
► The code above will output Saab and Volvo are Swedish cars.
(2) Associative Array
► 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. In this example
we use an array to assign ages to the different persons:
$ages = array("Amar"=>24, "Akbar"=>23, "Anthony"=>25);
► This example is the same as example 1, but shows a different way of creating the array:
$ages*'Amar'+=”24”;
$ages*'Akbar’+="23";
$ages['Anthony']="25";
► The ID keys can be used in a script:
<?php
$ages['Amar']="24";
$ages['Akbar']"23" ;
$ages["Anthony']="25";
echo "Amar is $ages['Amar']] years old.";
?>

CC-405 Web Application Development using PHP Page 23


SHREE MARUTI VIDHYAMANDIR COLLEGE OF BUSSINESS MANGEMNET AND
COMPUTER SCIENCE – B.C.A BHAVNAGAR
► The code above will output Amit is 24 years old.
(3) Multidimensional Array
► 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.
► In this example we create a multidimensional array, with automatically assigned ID keys:
<?php
$IPL=array("Mumbai" => array("Sachin", "Harbhjan", "Malinga"),
"Chennai=>array("Dhoni", "Raina"),
"Calcutta"-> array("Gambhir"));
echo "$IPL("Mumbai'][2] is not an Indian Player";
print_r($IPL);
► The array above would look like this if written to the output:
Malinga is not an Indian.
Array([Mumbai]=>Array([0] => Sachin, [1]=>Harbhjan,[2]=>Malinga),
[Chennai->Array([0]=>Dhoni, [1]=>Raina),
[Calcutta)->Array([0]=>Gambhir))
 User Defined Functions
(1) No Arguments Return Value
► This function doesn't take any arguments and doesn't return value.
► For example,
<?php
function add()
{
$a=10;
$b-20;
echo $a+$b;
}
add(); ?>
(2) No Arguments With Return Value
► This function doesn't take any arguments but returns a value.
► For ex.
<?php
function sub()
{
$a=10;
$b=20;
return ($a-$b);
echo sub():
} ?>

CC-405 Web Application Development using PHP Page 24


SHREE MARUTI VIDHYAMANDIR COLLEGE OF BUSSINESS MANGEMNET AND
COMPUTER SCIENCE – B.C.A BHAVNAGAR
(3) With Arguments No Return Value
► This function takes arguments but doesn't return any value.
► For ex.
<?php
function mul($a, $b)
{
echo $a*$b;
}
$a=10; $b=20;
mul($a, $b);
?>
(4) With Arguments With Return Value
► This function takes arguments and returns a value.
► For ex.
<?php
function div($a, $b)
{
return ($a/$b);
}
$a=10; $b=20;
echo div($a, $b);
?>
 Built In Functions
 String functions
1. echo
It is used to display one or more strings. In another words we can say that the echo() function outputs
one or more string.
Syntax:
echo (string $arg1 [, string $... ])
Example :
<?php
$str = "Hello world!";
echo $str;
?>
2. Print
One or more strings to be sent to output.
Syntax:
print(strings)
Example:

CC-405 Web Application Development using PHP Page 25


SHREE MARUTI VIDHYAMANDIR COLLEGE OF BUSSINESS MANGEMNET AND
COMPUTER SCIENCE – B.C.A BHAVNAGAR
<?php
$str = "Hello world!";
print $str;
?>
3. Chr
the chr() function returns a character from the specified ASCII value.
Syntax:
chr(ascii)
Example:
<?php
echo chr(52) . "<br>"; // Decimal value
echo chr(052) . "<br>"; // Octal value
echo chr(0x52) . "<br>"; // Hex value
?>
Output:
4
*
R
4. Trim
The trim() function removes whitespace and other predefined characters from both sides of a string.
Syntax : trim(string,charlist)
Parameter Description
String Required. Specifies the string to check
Charlist Optional. Specifies which characters to remove from the string. If omitted, all of the
following characters are removed:

 "\0" - NULL
 "\t" - tab
 "\n" - new line
 "\x0B" - vertical tab
 "\r" - carriage return
 " " - ordinary white space

Example:
<?php
$str = "\n\n\n Hello World!\n\n\n";
echo "Without trim: " . $str;
echo "<br>";
echo "With trim: " . trim($str);
?>

CC-405 Web Application Development using PHP Page 26


SHREE MARUTI VIDHYAMANDIR COLLEGE OF BUSSINESS MANGEMNET AND
COMPUTER SCIENCE – B.C.A BHAVNAGAR
Output:
Without trim:Hello World!
With trim: Hello World!
 Ltrim : The ltrim() function removes whitespace or other predefined characters from the left side of
a string.
Syntax: ltrim(string,charlist)
Example:
<?php
$str = "\n\n\nHello World!";
echo "Without ltrim: " . $str;
echo "<br>";
echo "With ltrim: " . ltrim($str);
?>
Output :
Without ltrim: Hello World!
With ltrim: Hello World!
 Rtrim:
The rtrim() function removes whitespace or other predefined characters from the right side of a
string.
Syntax : rtrim(string,charlist)
Example:
<?php
$str = "Hello World!\n\n\n";
echo "Without rtrim: " . $str;
echo "<br>";
echo "With rtrim: " . rtrim($str);
?>
5. Str_word_count:
The str_word_count() function counts the number of words in a string.
Syntax: str_word_count(string,return,char)

Parameter Description
String Required. Specifies the string to check
Return Optional. Specifies the return value of the str_word_count() function.
Possible values:
0 - Default. Returns the number of words found
1 - Returns an array with the words from the string
2 - Returns an array where the key is the position of the word in the string, and value is
the actual word
Char Optional. Specifies special characters to be considered as words.

CC-405 Web Application Development using PHP Page 27


SHREE MARUTI VIDHYAMANDIR COLLEGE OF BUSSINESS MANGEMNET AND
COMPUTER SCIENCE – B.C.A BHAVNAGAR
Example:
<html>
<body>
<?php
print_r(str_word_count("Hello world!",1));
?>
</body>
</html>
Output:
Array ( [0] => Hello [1] => world )
If second argument is 0 then it returns number of words in string.
Like output will be : 2.
If we write 2 in second argument then output will be :
Array ( [0] => Hello [6] => world )
Example of char parameter:
<html>
<body>
<?php
print_r(str_word_count("Hello world & good morning!",1));
print "<br>";
print_r(str_word_count("Hello world & good morning!",1,"&"));
?>
</body>
</html>
Output:
Array ( [0] => Hello [1] => world [2] => good [3] => morning )
Array ( [0] => Hello [1] => world [2] => & [3] => good [4] => morning )
6. Strcmp
The strcmp() function compares two strings.
Syntax: strcmp(string1,string2)
Parameter Description
string1 Required. Specifies the first string to compare
string2 Required. Specifies the second string to compare
Example:
<html>
<body>
<?php
echo strcmp("Hello world!","Hello world!")."<br>"; // the two strings are equal
echo strcmp("Hello world!","Hello")."<br>"; // string1 is greater than string2

CC-405 Web Application Development using PHP Page 28


SHREE MARUTI VIDHYAMANDIR COLLEGE OF BUSSINESS MANGEMNET AND
COMPUTER SCIENCE – B.C.A BHAVNAGAR
echo strcmp("Hello world!","Hello world! Hello!")."<br>"; // string1 is less than string2
?>
</body>
</html>
Output:
0
7
-7
7. stristr
The stristr() function searches for the first occurrence of a string inside another string.
This function is case - insensitive.
syntax: stristr(string,search,before_search)
Parameter Description
String Required. Specifies the string to search
Search Required. Specifies the string to search for. If this parameter is a number, it will search
for the character matching the ASCII value of the number
before_search Optional. A boolean value whose default is "false". If set to "true", it returns the part of
the string before the first occurrence of the search parameter.
Example:
<html>
<body>
<?php
echo stristr("Hello world!","WORLD",true);
?>
</body>
</html>
Output:
Hello
Note: If it is false then return world.
8. strstr
The strstr() function searches for the first occurrence of a string inside another string.
Note: This function is binary-safe.
Note: This function is case-sensitive.
Syntax: strstr(string,search)
Parameter Description
String Required. Specifies the string to search
Search Required. Specifies the string to search for. If this parameter is a number, it will search for
the character matching the ASCII value of the number

CC-405 Web Application Development using PHP Page 29


SHREE MARUTI VIDHYAMANDIR COLLEGE OF BUSSINESS MANGEMNET AND
COMPUTER SCIENCE – B.C.A BHAVNAGAR
Example:
<html>
<body>
<?php
echo strstr("Hello world!","world",true);
?>
</body>
</html>
Output
Hello
9. strlen
The strlen() function returns the length of a string.
Syntax: strlen(string)
Parameter Description
String Required. Specifies the string to check
Example :
<html>
<body>
<?php
echo strlen("Hello world!"); ?>
<p><b>Note:</b> Whitespaces and exclamation marks are also a part of the string ("HelloWorld" would
return 10).</p>
</body>
</html>
output:
12
Note: Whitespaces and exclamation marks are also a part of the string ("HelloWorld" would return 10).
10. strpos
The strrpos() function finds the position of the last occurrence of a string inside another string.
Syntax: strpos(string,find,start)
Parameter Description
String Required. Specifies the string to search
Find Required. Specifies the string to find
Start Optional. Specifies where to begin the search. If start is a negative number, it counts from
the end of the string.
Example
<html>
<body>
<?php

CC-405 Web Application Development using PHP Page 30


SHREE MARUTI VIDHYAMANDIR COLLEGE OF BUSSINESS MANGEMNET AND
COMPUTER SCIENCE – B.C.A BHAVNAGAR
echo strrpos("I love php, I love php too!","php");
?>
</body>
</html>
Output : 19
11. strrev
The strrev() function reverses a string.
Syntax: strrev(string)
Parameter Description
String Required. Specifies the string to reverse
Example
<?php
echo strrev("Hello World!");
?>
</body>
</html>
Output
!dlroW olleH
12. substr
The substr() function returns a part of a string.
Syntax : substr(string,start,length)
Parameter Description
String Required. Specifies the string to return a part of
Start Required. Specifies where to start in the string
A positive number - Start at a specified position in the string
A negative number - Start at a specified position from the end of the string
0 - Start at the first character in string
Length Optional. Specifies the length of the returned string. Default is to the end of the string.
A positive number - The length to be returned from the start parameter
Negative number - The length to be returned from the end of the string
If the length parameter is 0, NULL, or FALSE - it return an empty string
Example:
<html>
<body>
<?php
echo substr("Hello world",6,3);
?>
</body>
</html>

CC-405 Web Application Development using PHP Page 31


SHREE MARUTI VIDHYAMANDIR COLLEGE OF BUSSINESS MANGEMNET AND
COMPUTER SCIENCE – B.C.A BHAVNAGAR
Output:
wor
13. strtoupr
The strtoupper() function converts a string to uppercase.
Synatx: strtoupper(string)
Parameter Description
String Required. Specifies the string to convert
Example:
<html>
<body>
<?php
echo strtoupper("Hello WORLD!");
?>
</body>
</html>
14. strtolower
The strtolower() function converts a string to lowercase.
Syntax: strtolower(string)
Example:
<html>
<body>
<?php
echo strtolower("Hello WORLD.");
?>
</body>
</html>
15. ucfirst
The ucfirst() function converts the first character of a string to uppercase.
Syntax: ucfirst(string)

Parameter Description
String Required. Specifies the string to convert
Example:
<html>
<body>
<?php
echo ucfirst("hello world!");
?>
</body>

CC-405 Web Application Development using PHP Page 32


SHREE MARUTI VIDHYAMANDIR COLLEGE OF BUSSINESS MANGEMNET AND
COMPUTER SCIENCE – B.C.A BHAVNAGAR
</html>
Output:
Hello world!
16. ucword
The ucwords() function converts the first character of each word in a string to uppercase.
Synatx: ucwords(string, delimiters)
Parameter Description
String Required. Specifies the string to convert
Delimiters Optional. Specifies the word separator character
Example:
<?php
echo ucwords("hello world");
?>
Output
Hello World
17. substr
The substr() function returns a part of a string.
Syntax: substr(string,start,length)
Parameter Description
String Required. Specifies the string to return a part of
Start Required. Specifies where to start in the string
A positive number - Start at a specified position in the string
A negative number - Start at a specified position from the end of the string
0 - Start at the first character in string
Length Optional. Specifies the length of the returned string. Default is to the end of the string.
A positive number - The length to be returned from the start parameter
Negative number - The length to be returned from the end of the string
If the length parameter is 0, NULL, or FALSE - it return an empty string
Example
<html>
<body>
<?php
echo substr("Hello world",6);
?>
</body>
</html>
Output:
World

CC-405 Web Application Development using PHP Page 33


SHREE MARUTI VIDHYAMANDIR COLLEGE OF BUSSINESS MANGEMNET AND
COMPUTER SCIENCE – B.C.A BHAVNAGAR
18. strreplace
The str_replace() function replaces some characters with some other characters in a string.
This function works by the following rules:
If the string to be searched is an array, it returns an array
If the string to be searched is an array, find and replace is performed with every array element
Syntax: str_replace(find,replace,string)
Parameter Description
find Required. Specifies the value to find
Replace Required. Specifies the value to replace the value in find
String Required. Specifies the string to be searched
Example
<html>
<body>
<p>Search the string "Hello World!", find the value "world" and replace it with "Peter":</p>
<?php
echo str_replace("world","Peter","Hello world!");
?>
</body>
</html>
Output
Search the string "Hello World!", find the value "world" and replace it with "Peter":
Hello Peter!
 Mathematical functions
The math functions can handle values within the range of integer and float types.
1. Abs
The abs() function returns the absolute (positive) value of a number.
Syntax : abs(number)

Parameter Description
Number Required. Specifies a number. If the number is of type float, the return type is also float,
otherwise it is integer
Example
<html>
<body>
<?php
echo(abs(6.7) . "<br>");
echo(abs(-6.7) . "<br>");
echo(abs(-3) . "<br>");
echo(abs(3));

CC-405 Web Application Development using PHP Page 34


SHREE MARUTI VIDHYAMANDIR COLLEGE OF BUSSINESS MANGEMNET AND
COMPUTER SCIENCE – B.C.A BHAVNAGAR
?>
</body>
</html>
Output
6.7
6.7
3
3
2. Sqrt
The sqrt() function returns the square root of a number.
Syntax : sqrt(number)
Example:
<html>
<body>
<?php
echo(sqrt(0) . "<br>");
echo(sqrt(1) . "<br>");
echo(sqrt(9) . "<br>");
echo(sqrt(0.64) . "<br>");
echo(sqrt(-9));
?>
</body>
</html>
Output
0
1
3
0.8
NAN
3. Log
The log() function returns the natural logarithm of a number, or the logarithm of number to base.
Syntax : log(number)
Example
<html>
<body>
<?php
echo(log(2.7183) . "<br>");
echo(log(2) . "<br>");
echo(log(1) . "<br>");

CC-405 Web Application Development using PHP Page 35


SHREE MARUTI VIDHYAMANDIR COLLEGE OF BUSSINESS MANGEMNET AND
COMPUTER SCIENCE – B.C.A BHAVNAGAR
?>
</body>
</html>
Output
1.000006684914
0.69314718055995
0
4. Floor
The floor() function rounds a number DOWN to the nearest integer, if necessary, and returns the result.
Syntax: floor(number)
Example
<html>
<body>
<?php
echo(floor(0.60) . "<br>");
echo(floor(0.40) . "<br>");
echo(floor(5) . "<br>");
echo(floor(5.1) . "<br>");
echo(floor(-5.1) . "<br>");
echo(floor(-5.9));
?>
</body>
</html>
Output
0
0
5
5
-6
-6
5. Ceil
The ceil() function rounds a number UP to the nearest integer, if necessary.
Syntax : ceil(number)
Parameter Description
Number Required. Specifies the value to round up
Example
<html>
<body>
<?php

CC-405 Web Application Development using PHP Page 36


SHREE MARUTI VIDHYAMANDIR COLLEGE OF BUSSINESS MANGEMNET AND
COMPUTER SCIENCE – B.C.A BHAVNAGAR
echo(ceil(0.60) . "<br>");
echo(ceil(0.40) . "<br>");
echo(ceil(5) . "<br>");
echo(ceil(5.1) . "<br>");
echo(ceil(-5.1) . "<br>");
echo(ceil(-5.9));
?>
</body>
</html>
6. Pow
The pow() function returns x raised to the power of y.
Syntax: pow(x,y)
Parameter Description
x Required. Specifies the base to use
y Required. Specifies the exponent
<?php
echo(pow(2,4) . "<br>");
echo(pow(-2,4) . "<br>");
echo(pow(-2,-4) . "<br>");
echo(pow(-2,-3.2));
?>
Output
16
16
0.0625
NAN
7. Max
The max() function returns the highest value in an array, or the highest value of several specified values
Syntax : max(array_values);
or
max(value1,value2,...);
Parameter Description
array_values Required. Specifies an array containing the values
value1,value2,... Required. Specifies the values to compare (must be at least two values)
Example
<html>
<body>
<?php
echo(max(2,4,6,8,10) . "<br>");

CC-405 Web Application Development using PHP Page 37


SHREE MARUTI VIDHYAMANDIR COLLEGE OF BUSSINESS MANGEMNET AND
COMPUTER SCIENCE – B.C.A BHAVNAGAR
echo(max(22,14,68,18,15) . "<br>");
echo(max(array(4,6,8,10)) . "<br>");
echo(max(array(44,16,81,12)));
?>
</body>
</html>
Output
10
68
10
81
8. Min
The min() function returns the lowest value in an array, or the lowest value of several specified values.
Syntax : min(array_values);
or
min(value1,value2,...);
Parameter Description
array_values Required. Specifies an array containing the values
value1,value2,... Required. Specifies the values to compare (must be at least two values)
Example:
<html>
<body>
<?php
echo(min(2,4,6,8,10) . "<br>");
echo(min(22,14,68,18,15) . "<br>");
echo(min(array(4,6,8,10)) . "<br>");
echo(min(array(44,16,81,12)));
?>
</body>
</html>
Output
2
14
4
12
 Date and time functions
The date/time functions allow you to get the date and time from the server where your PHP script runs.
You can then use the date/time functions to format the date and time in several ways.
Note: These functions depend on the locale settings of your server. Remember to take daylight saving
time and leap years into consideration when working with these functions.

CC-405 Web Application Development using PHP Page 38


SHREE MARUTI VIDHYAMANDIR COLLEGE OF BUSSINESS MANGEMNET AND
COMPUTER SCIENCE – B.C.A BHAVNAGAR
1) Date
The date() function formats a local date and time, and returns the formatted date string.
Syntax : date(format)
Parameter Description
Format Required. Specifies the format of the outputted date string. The following character can be used
d - The day of the month (from 01 to 31)
D - A textual representation of a day (three letters)
a - Lowercase am or pm
A - Uppercase AM or PM
B - Swatch Internet time (000 to 999)
g - 12-hour format of an hour (1 to 12)
G - 24-hour format of an hour (0 to 23)
Example
<html>
<body>
<?php
// Prints the day
echo date("l") . "<br>";
// Prints the day, date, month, year, time, AM or PM
echo date("l jS \of F Y h:i:s A") . "<br>";
?>
Output
Sunday
Sunday 17th of December 2023 01:26:38 PM
2) time
The time() function returns the current time in the number of seconds since the Unix Epoch (January 1
1970 00:00:00 GMT).
Syntax: time()
Example
<html>
<body>
<?php
$t=time();
echo($t . "<br>");
echo(date("Y-m-d",$t));
?>
</body>
</html>
Output

CC-405 Web Application Development using PHP Page 39


SHREE MARUTI VIDHYAMANDIR COLLEGE OF BUSSINESS MANGEMNET AND
COMPUTER SCIENCE – B.C.A BHAVNAGAR
1702819532
2023-12-17
3) getdate
The getdate() function returns date/time information of a timestamp or the current local date/time.
Syntax : getdate()
Example:
<?php
print_r(getdate());
?>
Output
Array ( [seconds] => 12 [minutes] => 31 [hours] => 13 [mday] => 17 [wday] => 0 [mon] => 12 [year] =>
2023 [yday] => 350 [weekday] => Sunday [month] => December [0] => 1702819872 )
∆ get to me of today
The gettimeofday() function returns the current time.
Syntax: gettimeofday(return_float)
Parameter Description
return_float Optional. When set to TRUE, a float instead of an array is returned. Default is FALSE
Example
<html>
<body>
<?php
// Print the array from gettimeofday()
print_r(gettimeofday());
echo "<br><br>";
// Print the float from gettimeofday()
echo gettimeofday(true) . "<br><br>";
?>
Output
Array ( [sec] => 1702820162 [usec] => 318471 [minuteswest] => 0 [dsttime] => 0 )
4) local time
The localtime() function returns the local time.
Syntax : localtime(timestamp)

Parameter Description
Timestamp Optional. Specifies a Unix timestamp that defaults to the current local time, time(), if no
timestamp is specified
is_assoc Optional. Specifies whether to return an associative or indexed array. FALSE = the array
returned is an indexed array. TRUE = the array returned is an associative array. FALSE is
default.

CC-405 Web Application Development using PHP Page 40


SHREE MARUTI VIDHYAMANDIR COLLEGE OF BUSSINESS MANGEMNET AND
COMPUTER SCIENCE – B.C.A BHAVNAGAR
The keys of the associative array are:
[tm_sec] - seconds
[tm_min] - minutes
[tm_hour] - hour
[tm_mon] - month of the year (January=0)
[tm_year] - Years since 1900
[tm_wday] - Day of the week (Sunday=0)
[tm_yday] - Day of the year
[tm_isdst] - Is daylight savings time in effect
Example
<?php
print_r(localtime());
echo "<br><br>";
print_r(localtime(time(),true));
?>
Output
Array ( [0] => 18 [1] => 39 [2] => 13 [3] => 17 [4] => 11 [5] => 123 [6] => 0 [7] => 350 [8] => 0 )
Array ( [tm_sec] => 40 [tm_min] => 40 [tm_hour] => 13 [tm_mday] => 17 [tm_mon] => 11 [tm_year] =>
123 [tm_wday] => 0 [tm_yday] => 350 [tm_isdst] => 0 )

5) checkdate
The checkdate() function is used to validate a Gregorian date.
Syntax: checkdate(month, day, year)
Parameter Description
Month Required. Specifies the month as a number between 1 and 12
Day Required. Specifies the day as a number between 1 and 31
Year Required. Specifies the year as a number between 1 and 32767
Example
<html>
<body>
<?php
var_dump(checkdate(12,31,2023));
echo "<br>";
var_dump(checkdate(2,29,2003));
echo "<br>";
var_dump(checkdate(2,29,2004));
?>
</body>
</html>

CC-405 Web Application Development using PHP Page 41


SHREE MARUTI VIDHYAMANDIR COLLEGE OF BUSSINESS MANGEMNET AND
COMPUTER SCIENCE – B.C.A BHAVNAGAR
Output
bool(true)
bool(false)
bool(true)

CC-405 Web Application Development using PHP Page 42


SHREE MARUTI VIDHYAMANDIR COLLEGE OF BUSSINESS MANGEMNET AND
COMPUTER SCIENCE – B.C.A BHAVNAGAR

Unit-3 Working with form , Cookie and Session


► Form elements- TextBox, TextArea, Password,RadioButton, Check Box, Combo Box, Image
► Buttons – Submit and Reset
► Uploading File to web server
► POST & GET method
► PHP include and require statement
► Basic of Cookie-Setting Cookies, Accessing Cookies, Deleting Cookies.
► Basic of Session- Starting a Session, Destroying a session.

 Introduction of HTML

In order to design a web page we need to write code to design it. This code is known as scripting language.
There are two types of scripting language. Server side Scripting Language and Client side Scripting Language.
HTML is basically client side Scripting language. In order to design static web sites (Sites that do not have
any database or does not store any client information are called static web sites) HTML is used. In order to
design dynamic web sites one has to use the server side scripting language that could be either ASP or PHP.
With server side scripting language we can store, retrieve, delete and edit the data.

HTML pages are of two types:

Static Pages:

Static pages, as the name indicates, comprise static content (text or images). So you can only see the
contents of a web page without being able to have any interaction with it.

Dynamic Pages:

Dynamic pages are those where the content of the web page depend on user input. So interaction with
the user is required in order to display the web page. For example, consider a web page which requires a
number to be entered from the user in order to find out if it is even or odd. When the user enters the
number and clicks on the appropriate button, the number is sent to the web server, which in turn
returns the result to the user in an page.

Forms - GUI Based Web page

HTML also provides some tags to create user interfaces like forms, textboxes, checkboxes, radio buttons,
pull down menu, password field, etc, to create different elements of user interface following tags are
used...

CC-405 Web Application Development using PHP Page 43


SHREE MARUTI VIDHYAMANDIR COLLEGE OF BUSSINESS MANGEMNET AND
COMPUTER SCIENCE – B.C.A BHAVNAGAR
 <FORM> ... </FORM>

► Forms are a mechanism that allows users to enter different information through the controls given in the
forms and submit that information to server, Because of this they are used to create interactive web pages.

► The <FORM> tag comes at the beginning of any form. When you create a <FORM> tag, you also define the
script it uses and how it sends data using the ACTION and METHOD attributes:

Attribute Description

ACTION This attribute points the form to an URL that will accept the form's information and do
something with it. If you don't specify an ACTION, it sends the information back to the same
URL, the page came from.

METHOD This attribute tells the form how to send its information to the URL specified in ACTION. The
most common method is POST, which sends all the information from the form separately
from the URL. The other option for METHOD is GET, which attaches the information from
the form to the end of the URL.

► Differences between GET and POST methods

GET POST

1. All the values passed to the target page will be 1. The values will be passed to the target page
displayed in the address bar without displaying into the address bar.

2. This method is less secure. 2. This method is more secure.

3. There is limitation in passing the number of 3. There isn't such limitation in passing the values.
values in this method.

For example:

<FORM ACTION="url of a webpage to which values must be passed" METHOD="GET/POST">

…….

</FORM>

There are some tags to create different controls in a page like...

 <INPUT>

The <INPUT> tag is used to indicate where user input is expected. This tag is used to create TEXTBOXES,
PASSWORD FIELDS, RADIO BUTTONS, CHECK BOXES and ACTION BUTTONS (SUBMIT, RESET) etc.

The attributes for the <INPUT> tag are the following:

CC-405 Web Application Development using PHP Page 44


SHREE MARUTI VIDHYAMANDIR COLLEGE OF BUSSINESS MANGEMNET AND
COMPUTER SCIENCE – B.C.A BHAVNAGAR
Attribute Description

NAME This defines the name for the data. This field is required for all the types 0of input except
Submit and Clear.

SIZE This is the size of the input field in number of characters for text or password.

MAXLENGTH This specifies the maximum number of characters to be allowed for a text or password
field.

VALUE For a text or password field, it defines the default text displayed. For a check box or radio
button, it specifies the value that is returned to the server if the box or button is
selected. For the Submit and Reset buttons, it defines the text inside the button.

CHECKED This sets a check box or radio button to on. It has no meaning for any other type of
<INPUT> tag

TYPE This sets the type of input field you want to display.

► Creating a Textbox (Single Line Textbox)

The most common value of this attribute of the <INPUT> tag is TEXT. This attribute is used to create a
single line textbox. <INPUT TYPE=TEXT> creates a text box. Attributes are....

Attribute Description

Size This is the size of the input field in number of characters for text

MAXLENGTH This specifies the maximum number of characters to be allowed for a text.

Name This defines the unique name for the text box.

CODE OUTPUT

<HTML>
<HEAD> <TITLE> TEXT BOX</TITLE> </HEAD>
<BODY>
<FORM> Username:
USERNAME:
<INPUT TYPE=TEXT SIZE=10 MAXLENGTH=15
NAME="USERNAME">
</FORM>
</BODY>
</HTML>

CC-405 Web Application Development using PHP Page 45


SHREE MARUTI VIDHYAMANDIR COLLEGE OF BUSSINESS MANGEMNET AND
COMPUTER SCIENCE – B.C.A BHAVNAGAR
 Creating Multi Line Text box:

• With <TEXTAREA>, you can provide a field for someone to enter multiple lines of information. By
default, a <TEXTAREA> form shows a blank field four rows long and 40 characters wide. You can make it
any size you want by using the ROWS and COLS attributes in the tag. You can also specify some default
text by simply entering it between the <TEXTAREA> and </TEXTAREA> tags.

It's attributes are as follows:

Attribute Description

NAME This is required. It defines the name for the data.

ROWS This sets the number of rows in the field.

COLS This sets the width of the field in characters.

WRAP It is used if you want to enable word wrap within a control, so that if a word doesn't have
enough space to fit itself it will be shifted into next line without breaking.

MAXLENGTH This specifies the maximum number of characters to be allowed for a text area.

Code Output

<HTML>
<HEAD><TITLE>TEXT
AREA</TITLE></HEAD>
<BODY><FORM>REMARKS: here, you can make any remarks.
<TEXTAREA ROWS=6 COLS=40 MAXLENGTH=500
NAME="REMARKS" WRAP>
HERE, YOU CAN MAKE ANY REMARKS.
REMARKS:
</TEXTAREA>
</FORM></BODY></HTML>

 Creating a Password Field

Very similar to the TYPE-TEXT is the TYPE-PASSWORD. It is exactly the same, except that for security it
displays" ***instead of the actual input.

<INPUT TYPE=PASSWORD> creates a password field. Attributes are...

CC-405 Web Application Development using PHP Page 46


SHREE MARUTI VIDHYAMANDIR COLLEGE OF BUSSINESS MANGEMNET AND
COMPUTER SCIENCE – B.C.A BHAVNAGAR
Attributes Description

SIZE This is the size of the input field in number of characters for password field.

MAXLENGTH This specifies the maximum number of characters to be allowed for a password field.

Name This defines the unique name for the password field.

Code OUTPUT

<HTML>
<HEAD><TITLE>PASSWORDFEILD
</TITLE></HEAD>
<BODY>
<FORM>
USERNAME <INPUT TYPE=TEXT SIZE=10 MAXLENGTH=15 USERNAME:
NAME="USERNAME">
<BR><BR> PASSWORD:
PASSWORD: <INPUT TYPE-PASSWORD SIZE=10 MAXLENGTH=15
NAME="PASSWORD">
</FORM>
</BODY>
</HTML>

 Creating Checkbox

CHECKBOX displays a simple check box that can be checked or left empty; use a check box when the
choice is yes or no and doesn't depend on anything else. Possible attributes to include with the TYPE,
include NAME (required). VALUE, and CHECKED (which defaults the check box as checked). Check boxes
are useful when you have a list of options, more than one, of which can be selected at a time CHECKBOX.
Attributes are.....

Attribute Description

NAME This defines the unique name for the Check box

VALUE This specifies the value to be passed to the target page if the checkbox is selected

CHECKED This is used if we want default selection on any checkbox, it is optional.

CC-405 Web Application Development using PHP Page 47


SHREE MARUTI VIDHYAMANDIR COLLEGE OF BUSSINESS MANGEMNET AND
COMPUTER SCIENCE – B.C.A BHAVNAGAR
CODE OUTPUT

<HTML><FORM><H2>HOBBIES</H2>
CRICKET<input TYPE-CHECKBOX VALUE=Cricket
CHECKED> Hobbies
MUSIC<INPUT TYPE=CHECKBOX VALUE=Music><BR>
 Cricket Music
DANCING<INPUT TYPE=CHECKBOX VALUE=Dancing>
SINGING<INPUT TYPE=CHECKBOX  Dancing Singing
VALUE=Singing><BR>
</FORM> </HTML>

 Creating Radio Buttons

RADIO BUTTON is a more complex version of a check box, allowing only one of a related set to be chosen.
You can group radio buttons together by using the NAME attribute; this keeps all buttons in the same
group under one NAME. Possible attributes to include with the TYPE, include NAME (required), VALUE,
and CHECKED.

Attribute Description

NAME This defines the unique name for the radio button

VALUE This specifies the value to be passed to the target page if radio button is selected

CHECKED This is used if we want default selection on any radio button, it is optional.

CODE OUTPUT

<HTML><FORM>
<head><title>radio button <title></head>
<body> GENDER
<form>
Gender <br><br>  MALE  FEMALE
<input type=radio name=”gender” value=”MALE”
checked> MALE
<input type=radio name=”gender” value=
“FEMALE”>FEMALE
</body>
</FORM> </HTML>

CC-405 Web Application Development using PHP Page 48


SHREE MARUTI VIDHYAMANDIR COLLEGE OF BUSSINESS MANGEMNET AND
COMPUTER SCIENCE – B.C.A BHAVNAGAR
 Creating List Box

The <SELECT> element shows a list of choices in either a pop-up menu or a scrolling list. It's set up as an
opening and closing tag with a number of choices listed in between. Just like the <TEXTAREA> element,
the <SELECT> tag requires you to define a name. You can specify how many choices to show at once by
using the SIZE attribute. The attributes for the <SELECT> element are as follows:

Attribute Description

NAME This is required. It defines the name for the pull-down menu.

SIZE This attribute determines how many choices to show. If you omit SIZE or set it to 1, the
choices are shown as a drop-down list. If you set it to 2 or higher, it shows the choices in a
scroll box. If you set SIZE larger than the number of choices you have within <SELECT>, a
nothing choice is added. When the end user chooses this, it's returned as an empty field.

MULTIPLE This allows multiple selections. If you specify multiple, a scrolling window displays-
regardless of the number of choices or the setting of SIZE. To select more than one option,
it has to be clicked with CTRL key.

You present the choices the end user can make within the <SELECT> and </SELECT> tags. The choices
are listed inside the <OPTION> tag. The attributes for the <OPTION> tag are the following:

Attribute Description

Value This is the value to be assigned for the choice, which is what is sent back to the script, and
doesn't have to be the same as what is presented to the end user.

SELECTED If you want one of the choices to be a default, use the SELECTED option in the <OPTION>
tag.

CODE OUTPUT

<HTML> EDUCATION:
<HEAD> <TITLE>List Box </TITLE></HEAD>
B.C.A
<BODY> <FORM> EDUCATION:
EDUCATION:
<SELECT SIZE=4 NAME="EDUCATION”
B.C.A ^
MULTIPLE> B.B.A
V
<OPTION VALUE=BCA SELECTED>B.C.A.</OPTION>
B.A
<OPTION VALUE=BCA>B.C.A</OPTION>
<OPTION VALUE-BBA >B.B.A</OPTION>
<OPTION VALUE-BA >B.A.</OPTION>

CC-405 Web Application Development using PHP Page 49


SHREE MARUTI VIDHYAMANDIR COLLEGE OF BUSSINESS MANGEMNET AND
COMPUTER SCIENCE – B.C.A BHAVNAGAR
<OPTION VALUE-BCOM>B.COM</OPTION>
</SELECT> </FORM></BODY>
</HTML>
 Creating Submit Button

SUBMIT displays a push button with the preset function of sending the data in the form to the server to be
processed by a server-side script. You can use the VALUE attribute with SUBMIT to provide text other than
Submit Query (the default) for the button.

CODE OUTPUT

<HTML>
<HEAD> <TITLE>SUBMIT.HTM</TITLE>
</HEAD>
<BODY> <FORM>
SUBMIT Query
<INPUT TYPE="SUBMIT"> <BR>
<INPUT TYPE="SUBMIT"
Send
VALUE="SEND">
</FORM><BODY>
</HTML>
 Creating Reset Button

Display’s a push button with the preset function of clearing all the data in the form to its original value.
You can use the VALUE attribute with the RESET tag to provide text other than Reset (the default) for the
button.

CODE OUTPUT

<HTML>
<HEAD><TITLE>RESET.HTM</TITLE> Username ABC
</HEAD> Password
<BODY> <FORM>
Reset
USERNAME:
<INPUT TYPE=TEXT SIZE=10 MAXLENGTH=15
NAME="USERNAME" VALUE=ABC> <BR> Clear
PASSWORD:
<INPUT TYPE=PASSWORD SIZE=10
MAXLENGTH=15 NAME="PASSWORD">
<BR><INPUT TYPE="RESET">
<BR>
<INPUT TYPE="RESET" VALUE="CLEAR">
</FORM><BODY></HTML>

CC-405 Web Application Development using PHP Page 50


SHREE MARUTI VIDHYAMANDIR COLLEGE OF BUSSINESS MANGEMNET AND
COMPUTER SCIENCE – B.C.A BHAVNAGAR

The following code demonstrates the use of GET method, ACTION and SUBMITS buttons.

CODE OUTPUT

<HTML>
<HEAD> <TITLE>FORMDEMO.HTM Username ABC
</TITLE></HEAD> Password
<BODY>
Send
<FORM ACTION="BLANK.HTML" METHOD="GET">
USERNAME: <INPUT TYPE=TEXT SIZE=10 MAXLENGTH=15
NAME="USERNAME" VALUE=ABC > <BR> Clear
PASSWORD:
<INPUT TYPE=PASSWORD SIZE=10 MAXLENGTH=15
NAME="PASSWORD">
<BR>
ACTION calls the BLANK HTML File when
<INPUT TYPE="SUBMIT" VALUE="SEND"> <BR>
you click on Submit Button.
<INPUT TYPE="RESET" VALUE="CLEAR">
</FORM>
<BODY>
</HTML>

<HTML>
<BODY>
File called by ACTION.
</BODY>
</HTML>

 Uploading Files to Web server


To allow users to upload files from a form can be very useful.
Look at the following HTML form for uploading files:
<html> <body>
<form method="post" enctype="multipart/form-data">
<label for="file">Filename: </label>
<input type="file" name="file" > <br>
<input type="submit" name="submit" value="Submit">
</form>
</body> </html>

CC-405 Web Application Development using PHP Page 51


SHREE MARUTI VIDHYAMANDIR COLLEGE OF BUSSINESS MANGEMNET AND
COMPUTER SCIENCE – B.C.A BHAVNAGAR
Notice the following about the HTML form above:
The enctype attribute of the <form> tag specifies which content-type to use when submitting the form.
"multipart/form-data" is used when a form requires binary data, like the contents of a file, to be
uploaded.
The type="file" attribute of the <input> tag specifies that the input should be processed as a file. For
example, when viewed in a browser, there will be a browse-button next to the field.
By using the global PHP $_FILES array you can upload files from a client computer to the remote server.
The first parameter is the form's Input name and the second Index can be either "name", "type", "size",
"tmp_name" or "error". Like this:

$_FILES["file"]["name"] - the name of the uploaded file


$_FILES["file"]["type"]- the type of the uploaded file
$FILES["file"]["size"] - the size in bytes of the uploaded file.
$_FILES["file"]["tmp_name"] - the name of the temporary copy of the file stored on the server
$_FILES["file"]["error"] - the error code resulting from the file upload

This is a very simple way of uploading files. For security reasons, you should add restrictions on what the
user is allowed to upload.
In the following example we add some restrictions to the file upload. The user may only upload gif or
jpeg files and the file size must be under 20 kb and the temporary copy of the uploaded files will be
placed in the PHP temp folder on the server.
These temporary copied files will disappeared when the script ends. To store the uploaded file we need
to copy it to a different location:
<?php
if ((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") ||
($_FILES["file"]["type"] == "image/pjpeg")) && ($_FILES["file"]["size") < 20000))
{
if ($_FILES["file"]["error") > 0)
echo "Return Code: ".$_FILES["file"]["error"]."<br />";
else
(
echo "Upload: ".$_FILES["file"]["name"]."<br />";
echo "Type:".$_FILES["file"]["type"]."<br />";
echo "Size:". ($_FILES["file"]["size"]/1024). " Kb<br />";
echo "Temp file: ".$_FILES["file"]["tmp_name"]."<br/>";
if (file_exists("upload/".<$_FILES["file"]["name"]))

CC-405 Web Application Development using PHP Page 52


SHREE MARUTI VIDHYAMANDIR COLLEGE OF BUSSINESS MANGEMNET AND
COMPUTER SCIENCE – B.C.A BHAVNAGAR
echo $_FILES["file"]["name"]." already exists.”;
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/".$_FILES["file"]["name"]);
echo "Stored in: "."upload/".$_FILES["file"]["name"];
}
}
else
echo "Invalid file;
?>
The script above checks if the file already exists, if it does not, it copies the file to the specified folder.
Note: This example saves the file to a new folder called "upload".
 PHP Include and Require Statements

 require will produce a fatal error (E_COMPILE_ERROR) and stop the script
 include will only produce a warning (E_WARNING) and the script will continue
 So, if you want the execution to go on and show users the output, even if the include file is missing, use
the include statement. Otherwise, in case of Framework or a complex PHP application coding,always use
the require statement to include a key file to the flow of execution. This will help avoid compromising
your application's security and integrity, just in-case one key file is accidentally missing.
 Assume we have a file called "vars.php", with some variables defined:
<?php
$color='red';
$car='BMW';
?>
 Then, if we include the "vars.php" file, the variables can be used in the calling file:
 Example
<html>
<body>
<h1>Welcome to my home page!</h1>
<?php
include 'vars.php';
echo "I have a $color $car.";
?>
</body>
</html>
 PHP include vs. require
 The require statement is also used to include a file into the PHP code.

CC-405 Web Application Development using PHP Page 53


SHREE MARUTI VIDHYAMANDIR COLLEGE OF BUSSINESS MANGEMNET AND
COMPUTER SCIENCE – B.C.A BHAVNAGAR
 However, there is one big difference between include and require; when a file is included with
the include statement and PHP cannot find it, the script will continue to execute:
Example
<html>
<body>
<h1>Welcome to my home page!</h1>
<?php
include 'noFileExists.php';
echo "I have a $color $car.";
?>
</body>
</html>
 If we do the same example using the require statement, the echo statement will not be
executed because the script execution dies after the require statement returned a fatal error:
 Example
<html>
<body>
 <h1>Welcome to my home page!</h1>
<?php
require 'noFileExists.php';
echo "I have a $color $car.";
?>
</body>
</html>
 Use require when the file is required by the application.
 Use include when the file is not required and application should continue when file is not found.

 PHP Cookies
► PHP cookie is a small piece of information which is stored at client browser. It is used to recognize the
user.
► Cookie is created at server side and saved to client browser. Each time when client sends request to the
server, cookie is embedded with request. Such way, cookie can be received at the server side.
► In short, cookie can be created, sent and received at server end.
► Note: PHP Cookie must be used before <html> tag.
Create Cookies With PHP
► A cookie is created with the setcookie() function.
► Syntax
setcookie(name, value, expire, path, domain, secure, httponly);
► Only the name parameter is required. All other parameters are optional.
► PHP Create/Retrieve a Cookie
► 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).

CC-405 Web Application Development using PHP Page 54


SHREE MARUTI VIDHYAMANDIR COLLEGE OF BUSSINESS MANGEMNET AND
COMPUTER SCIENCE – B.C.A BHAVNAGAR
► 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
$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]))
{
echo "Cookie named '" . $cookie_name . "' is not set!";
}
else
{
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
</body>
</html>
► Note: The setcookie() function must appear BEFORE the <html> tag.
Modify a Cookie Value
► To modify a cookie, just set (again) the cookie using the setcookie() function:
► Example
<?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];
}
?>

CC-405 Web Application Development using PHP Page 55


SHREE MARUTI VIDHYAMANDIR COLLEGE OF BUSSINESS MANGEMNET AND
COMPUTER SCIENCE – B.C.A BHAVNAGAR
</body>
</html>
Delete a Cookie
To delete a cookie, use the setcookie() function with an expiration date in the past:
Example
<?php
// set the expiration date to one hour ago
setcookie("user", "", time() - 3600);
?>
<html>
<body>
<?php
echo "Cookie 'user' is deleted.";
?>
</body>
</html>

 PHP Session
► PHP session is used to store and pass information from one page to another temporarily (until user close
the website).
► PHP session technique is widely used in shopping websites where we need to store and pass cart
information e.g. username, product code, product name, product price etc from one page to another.
► PHP session creates unique user id for each browser to recognize the user and avoid conflict between
multiple browsers.
► 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.

Start a PHP Session


► A session is started with the session_start() function.
► 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:

<?php
// Start the session

CC-405 Web Application Development using PHP Page 56


SHREE MARUTI VIDHYAMANDIR COLLEGE OF BUSSINESS MANGEMNET AND
COMPUTER SCIENCE – B.C.A BHAVNAGAR
session_start();
?>
<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.
Get PHP Session Variable Values
► 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>
<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>
► Another way to show all the session variable values for a user session is to run the following code:
► Example

<?php
session_start();
?>
<html>
<body>
<?php

CC-405 Web Application Development using PHP Page 57


SHREE MARUTI VIDHYAMANDIR COLLEGE OF BUSSINESS MANGEMNET AND
COMPUTER SCIENCE – B.C.A BHAVNAGAR
print_r($_SESSION);
?>
</body>
</html>

► Destroy a PHP Session


► To remove all global session variables and destroy the session, use session_unset() and session_destroy():
► Example
<?php
session_start();
?>
<html>
<body>
<?php
// remove all session variables
session_unset();
// destroy the session
session_destroy();
?>
</body>
</html>

CC-405 Web Application Development using PHP Page 58


SHREE MARUTI VIDHYAMANDIR COLLEGE OF BUSSINESS MANGEMNET AND
COMPUTER SCIENCE – B.C.A BHAVNAGAR
Unit-4 Database Connectivity and Error Handling
► PHP-MySQL architecture
► Database interaction –Creating and connecting database
► Executing commands- Selecting, Inserting, Updating, Deleting
► Small application development
► Error Handling- Try, Catch and Throw block, die() function
► Page redirection in PHP
 MySQL
► An open source, Enterprise-level, multi-threaded, relational database management system that stores
and retrieves data using the Structured Query Language. It is very popular and much cheaper than oracle.
Advantages of MySQL
► MySQL server can handle very large databases.
► Offers rich and very useful set of functions.
► Easy Connectivity, speed and security make MySQL very well suited accessing database on a network.
► Multi-threaded request-handling using kernel thread.
► Very actively developed.
► Memory leak proof.
► Each user can install MySQL focally.
► Easy to use shell for creating tables, querying tables, etc.
► Easy to use with Java JDBC.
Interaction between PHP & MySQL
► PHP's strongest feature is its capability interface with a database. Connecting a database to the internet
has never been so easy.
► PHP supports many of the most popular database servers on the market, including MySQL.
► The cross platform scripting language PHP allows the creation of Internet/Intranet based user interfaces
that interact in real time with MySQL database tables.
► MySQL is a database server, normally used with PHP, which gives Internet/Intranet users a way to access
information stored in a database.
► Dynamic web pages can be generated with the help of PHP MySQL combination.
 Php mySQL architecture

Web Server

Web page
MySQL PHP
Database

CC-405 Web Application Development using PHP .php file Page 59


SHREE MARUTI VIDHYAMANDIR COLLEGE OF BUSSINESS MANGEMNET AND
COMPUTER SCIENCE – B.C.A BHAVNAGAR
► The above diagram depicts:
(1) Visitor's
► Web browser requests a web page (.php file) using a standard URL
(2) Web Server (Apache or IIS)
► Recognizes the requested file is a PHP script
► The web server therefore interprets the file using php engine
(3) PHP Engine
► Process the page request
► Fetches the data from the MySQL database.
(4) MySQL Database
► Responds by sending the requested content to the PHP script
(5) PHP Engine
► The PHP script stores the content into one or more PHP variables
► The PHP engine ends up by splitting out the data fetched dynamically from MySQL and sends as
a nicely formatted HTML page to the web server.
(6) Web Server (Apache or IIS)
► Sends the HTML to the visitor's web browser as pure HTML file.
(7) Visitor's
► Web browser will get the requested web page using standard URL.
 This means PHP as a server side scripting language speaks both languages.
Le MySQL (with the database) and HTML (with the client).
 PHP API
► All interaction between PHP and the MySQL database engine is through the PHP-MySQL extension, a
comprehensive set of built in PHP functions for accessing MySQL.
► The PHP-MySQL functions allow accessing MySQL database servers.
► The built-in database API functions make database programming with PHP quite easy.
Database Connectivity (using PHP API functions)
(1) mysql_connect()
► It's used to establish the connection with MySQL.
► Syntax: mysql_connect("hostname","username", "password")
► E.g. mysql_connect("localhist","root","");
(2) mysql_select_db()
► MySQL It's used to make connection with database in MySQL.
► Syntax: mysql_select_db("Databasename")

CC-405 Web Application Development using PHP Page 60


SHREE MARUTI VIDHYAMANDIR COLLEGE OF BUSSINESS MANGEMNET AND
COMPUTER SCIENCE – B.C.A BHAVNAGAR
► E.g. mysql_select_db("Student");
(3) mysql_query()
► It's used to run any SQL query on database server from the php page.
► It returns the result in resource.
► Syntax: mysql_query("querystring") E.g. mysql_query("select from table1");
(4) mysql_fetch_array()
► It's used to fetch the records one by one from the result (which is returned by mysql_query()
function).
► These records are retrieved in the form of array of fields so that user can access the values of
each and every field separately.
► Syntax: mysql_fetch_array(result)
► E.g. $result-mysql_query("select from table1"); $row mysql_fetch_array($result);
(5) mysql_num_rows()
► It returns the number of rows (records) that have been selected from table into the result
(which is returned by mysql_query() function).
► Syntax: mysql_num_rows(result)
► E.g. $result-mysql_query("select from table1"); $count=mysql_num_rows($result);
(6) mysql_affected_rows()
► It returns the number of affected rows (records) that have been (Inserted into (Updated to)/
(Deleted from)/ (Selected from) table into the result (which is returned by mysql_query()
function).
► Syntax: mysql_affected_rows($result)
► e.g. $result=mysql_query("delete from table1");
$count=mysql_affected_rows($result);
(7) mysql_close()
► It's used to close the established connection with MySQL.
► Syntax: mysql_close(conn)
► E.g. $conn=mysql_connect("localhist","root","");
mysql_close($conn);0
(8) die()
► It's used to return the error (if any occurs) at the time of interaction between PHP and MySQL.
► The error message passed to die function can be user defined message string or it can be
message string returned by the mysql_error() built-in function.
► Syntax: die("Error message") / die(mysql_error())
mysql_connect("localhist","root","") or die("Connection failed ... ");

CC-405 Web Application Development using PHP Page 61


SHREE MARUTI VIDHYAMANDIR COLLEGE OF BUSSINESS MANGEMNET AND
COMPUTER SCIENCE – B.C.A BHAVNAGAR
(9) mysql_error()
► It returns an app opriate error (if any occurs) at the time of interaction between PHP and MySQL.
► It's generally used in die() function.
► E.g. mysql_connect("localhist", "root","") or die(mysql_error());
 Connecting Database & Executing Commands (Database Interaction with MySql)
mysql_connect("localhost","root","") or die(mysql_error()); mysql_select_db("studentdb")or
die(mysql_error());
// To Insert a record
mysql_query("insert into stud values (1,'Bhavesh', 'Gaytrinagar','Bhavnagar, Male English,7802810752")
or die(mysql_error());
// To Update a record
mysql_query("update stud sname='Amit',contact_no=7802810751' where rollno-1") or die(mysql_error):
// To Select a record
Sresult= mysql_query("select from stud where rollno=1") or die(mysql_error()).
$row mysql_fetch_array($result);
print_r($row);
// To Select and display multiple records
Sresult= mysql_query("select from stud") or die(mysql_error()); while($row mysql_fetch_array($result))
print_r($row);
// To Delete a record
mysql_query("delete from stud where rollno=1") or die(mysql_error());
In above queries we can use variable names which having the data in place of static data so that we can
store the user defined data.
Small Application Development
 Login form
► Login.php
<?php
session_start();
?>
<html> <form method="post">
Username:<input type="text" name="uname"/> <br/>
Password: <input type="password" name="pwd"/><br/>
<input type="submit" value="Login" name="login"/>
</form> </html>

CC-405 Web Application Development using PHP Page 62


SHREE MARUTI VIDHYAMANDIR COLLEGE OF BUSSINESS MANGEMNET AND
COMPUTER SCIENCE – B.C.A BHAVNAGAR
<?php
if(isset($_REQUEST["login"]))
{
extract($_REQUEST);
mysql_connect("localhost","root","") or die("Connection failed");
mysql_select_db("MYDB1") or die("Database not found");
$result=mysql_query(“select * from login where Uname=’$uname’ and Pwd=’$pwd’ ”) or
die("Record not selected");
if(mysql_num_rows($result)>0)
{
$_SESSION['user']=$uname;
header("Location:Home.php? name=".$uname");
}
else
echo "Invalid user";
?>
► Home.php
<?php
session_start();
if(empty($_SESSION["user"]))
header("Location:index.php");
else
echo "Welcome".$_REQUEST["name"];
if(isset($_REQUEST["logout"]))
{
Unset($_SESSION*“user”+);
Header(“location:index.php”);
}
?>
<html> <form>
<input type="submit" name="logout" value="Logout"/>
</form> </html>

CC-405 Web Application Development using PHP Page 63


SHREE MARUTI VIDHYAMANDIR COLLEGE OF BUSSINESS MANGEMNET AND
COMPUTER SCIENCE – B.C.A BHAVNAGAR
 Error Handling
PHP provides different ways to handle errors:
1. Display errors
2. Logging.errors
3. Ignore errors
4. Acting on errors/ Exceptions
► Displaying errors is usually beneficial in a development environment and logging them is usually more
appropriate in a production environment. Some errors can be safely ignored and demand action. The
exact mix of error handling techniques a programmer employs depends on individual needs.
1. Displaying errors
► When a need arise to display error is sent to the standard output stream, which in the case of web page
means that it is sent to the browser. Displaying errors is very helpful for development because it enables
a programmer to get instant feedback what went wrong with a script without having to look through a
long log file. An error message that the PHP interpreter generates falls into one of the following
categories:
Types of errors:
1) Syntax or Parse errors 2) Fatal errors
3) Warnings 4) Notices
5) Logical errors 6) Environment errors
7) Runtime errors 8) core errors
9) Compile errors 10) User defined errors
 Error levels in PHP
► PHP errors are categorized by an error level ranging from notices to fatal errors. The error levels tell the
programmer how serious the error is. PHP defines some constants that can be used and applied to set the
value of error_reporting so that only errors of certain types get reported.
► These constants are:
► E_ALL:- For all errors except strict notices.
► E_PARSE:- parse errors
► E_ERROR:- For fatal errors.
► E_WARNING:- For warning messages.
► E_NOTICE:- For notices.
► E_STRICT:- For strict notices. This error level is the only included in the E ALL constant. STRICT
messages ensure that a programmer definitely is informed about us functions and so on in PHP
code.

CC-405 Web Application Development using PHP Page 64


SHREE MARUTI VIDHYAMANDIR COLLEGE OF BUSSINESS MANGEMNET AND
COMPUTER SCIENCE – B.C.A BHAVNAGAR
2. Logging Error
A log is a text file saved on a webserver. An appropriate error message is appended to this file by the
webserver every time when error occurs. Error logs track every error or warning. A good error handling
strategy requires that error be logged without interfering with the user interface so that a website
administrator can analyze the errors and correct them. Errors can be logged using three different
methods:
► Set the error logging option manually in php.ini file
► Set the error logging option at runtime using error_log()
► Use of trigger_error()
1. Setting error logging option manually in php.ini file.
► PHP allows the programmer to create such an environment via manually editing php.ini file. Only one
<filename>.log file is bound to the system path. This will hold all system generated error messages. PHP
internally supports both logging to a file and logging via syslog through two settings in the php.ini file.
i. Logging errors to file.
► Open the php.ini file an ASCII editor like notepad,
► Set the display errors directive to Off.
► Ensure the log errors directive is set to on.
► Search for the line; error_log=filename
► Uncomment the line and provide a valid path to where the error log file can be placed in which all errors
can be appended/ captured:
► error_log= “c:/wamp/logs/php_error.log"
► Save changes made in php.ini file and restart the Apache Service.
(ii) Logging errors via syslog
► Open the php.ini file an ASCII editor like notepad.
► Set the display errors directive to Off.
► Ensure the log errors directive is set to on
► Search for the line: error_log= "c:/wamp/logs/php_error.log"
► Comment this directive by palcing semi column (;) and delete the path.
► Search the line: error_log=syslog.
► Uncomment the directive error_log having the value syslog.
► The errors logged via syslog technique can be viewed using an Event Viewer available as a System
Software in any O/S. For example to view these errors in Windows XP open Event Viewer.
2) Setting error logging option at runtime in php.ini file
► PHP provides the built in error_log() for logging any errors when they occur. Using error logt error
messages will be logged directly into log files at the Web server rather than being dispatched to a web
browser. error_log() function appends a user defined error messages into log file which resides specified
in directory on the Web Server. These log files can be viewed later, on demand.

CC-405 Web Application Development using PHP Page 65


SHREE MARUTI VIDHYAMANDIR COLLEGE OF BUSSINESS MANGEMNET AND
COMPUTER SCIENCE – B.C.A BHAVNAGAR
► Syntax:
Int error log(string <message>,int <messgageType>[,string <Destination>][,string <extraheaders>])
► Where, Message is the error message that must be appended into the log file.
► Message Type is the type of error message being logged. The message type as follows:
► 0-depending on what the log configuration directive is set to in php.ini the error message will either be
routed to the operating system's system logging mechanism or a file. This is default option.
► 1-The error message is sent by email to the email address in the destination parameter. This is the only
message type where a fourth parameter, Extraheaders used.
► 2- The error message is sent through the PHP debugging connection. This option is only available if remote
debugging has been enabled. In this case, the destination parameter specifies the host name or IP address
and optionally, port number of the socket receiving the debug information.
► 3- The error message is appended to a destination file. A newline is automatically added to the end of the
message string.
► Example:
<?php
$file= "data.txt";
if(is_file($file))
print ("file $file is exist");
else
error_log("File does not exist",3,"C:/csr/errors/logerrors.log");
3) Using trigger_error()
► Trigger_error() generates a user-level error, warning or notice message. trigger_error() is used to trigger a
user-level error condition, which can be used by the built-in error handler, It is also useful when
programmer needs to generate a particular resource to an exception at runtime.
Syntax:
bool trigger_error( string <ErrorMessage>, [int <ErrorType>]);
► Where, ErrorMessage:- Assigns a user defines error message for the error. It's limited to 1024 characters
in length.
► ErrorType: Assigns selected error type to an error. It only works with the E_USER family of constants and
will default to E_USER_NOTICE.
► trigger error() returns False if a wrong ErrorType is specified and True otherwise.
Example:
<?php
$divisor=0;
if($divisor==0)
trigger_error("cannot divide by zero", E_USER_ERROR); ?>

CC-405 Web Application Development using PHP Page 66


SHREE MARUTI VIDHYAMANDIR COLLEGE OF BUSSINESS MANGEMNET AND
COMPUTER SCIENCE – B.C.A BHAVNAGAR
3. Ignoring Error
► PHP allows selective suppression of error reporting when errors occur with the syntax. If programmer
wants to open a file that may not exist and suppress any errors that arise, this can be done using syntax
given on the next page.
Syntax:
@ code of PHP program:
Example:
<?php $fp=@fopen(“data.txt”,”r”); ?>
4. Acting on Error (Exceptions)
► An exception is an event that occurs during the execution of a program that disturbs the normal flow of its
instructions. They provide a way to react to exceptional circumstances such as runtime errors in a program
by transferring control to special functions called handlers. When error occurs within a method, the
method creates an object and handles it off to the runtime system. The object, called an exception object,
contains information about the error, including its type and the state of the program when the error
occurred. Creating an exception object and handling it to the runtime system is called throwing exception.
An exception can be thrown, tried and caught within a PHP code block.
► Exceptions are handled using:
1) Try block
2) Catch block
3) Throw statement
1) Try block
► A block of PHP code for execution, which must include at least one catch block. The first step in
constructing an exception handler is to enclose the code that might throw an exception within a try block.
Syntax:
try
{ //some code
}
► If an exception occurs within try block, an exception handler associated with it handles that exception. To
associate an exception handler with a try block, the programmer must put a catch block after it.
2) Catch block
► Each catch block, is an exception handler and handles the type of exception indicated by its argument. The
catch block contains code that is executed if and when the exception handler is invoked. When an
exception is thrown, PHP code following the statement will not be executed and PHP will attempt to find
the first matching catch block.
► Syntax:
try
{

CC-405 Web Application Development using PHP Page 67


SHREE MARUTI VIDHYAMANDIR COLLEGE OF BUSSINESS MANGEMNET AND
COMPUTER SCIENCE – B.C.A BHAVNAGAR
//some code
}
catch(ExceptionType Name)
,………………….-
3) Throw statement
Syntax:
throw <Some throwable object>;
Example:
<?php
$num=10;
try
{
if($num<20)
throw new exception("value is less than 20");
echo "the entered value is correct";
}
catch(exception $x)
{
//echo "value must be greater than 20";
echo "Error message:".$x->getMessage();
}
?>



CC-405 Web Application Development using PHP Page 68

You might also like