You are on page 1of 27

UNIT IV

ERROR HANDLING

4.1 Introduction
An error is a type of mistake. We can say an error is a condition of
having incorrect or false knowledge or an error is defined as an
unexpected, invalid program state from which it is impossible to
recover.
Error can also be defined as "a deviation from accuracy or
correctness". A "mistake" is an error caused by a fault: the fault being
misjudgment, carelessness, or forgetfulness. An error message with
filename, line number and a message describing the error is sent to the
browser.
4.2 Types of error
Basically there are four types of errors in PHP, which are as follows:

 Parse Error (Syntax Error)


 Fatal Error
 Warning Error
 Notice Error

1. Parse Errors (syntax errors)


The parse error occurs if there is a syntax mistake in the script; the
output is Parse errors. A parse error stops the execution of the script.
There are many reasons for the occurrence of parse errors in PHP. The
common reasons for parse errors are as follows:
Common reason of syntax errors are:

 Unclosed quotes
 Missing or Extra parentheses
 Unclosed braces
 Missing semicolon
Example

<?php
echo "Cat";
echo "Dog"
echo "Lion";
?>
Output
In the above code we missed the semicolon in the second line. When
that happens there will be a parse or syntax error which stops execution
of the script, as in the following image:

2. Fatal Errors
Fatal errors are caused when PHP understands what you've written,
however what you're asking it to do can't be done. Fatal errors stop the
execution of the script. If you are trying to access the undefined
functions, then the output is a fatal error.
Example
<?php
function fun1()
{
echo "Vineet Saini";
}
fun2();
echo "Fatal Error !!";
?>
Output
In the above code we defined a function fun1 but we call another
function fun2 i.e. func2 is not defined. So a fatal error will be produced
that stops the execution of the script. Like as in the following image.

3. Warning Errors
Warning errors will not stop execution of the script. The main reason for
warning errors are to include a missing file or using the incorrect
number of parameters in a function.
Example

<?php
echo "Warning Error!!";
include ("Welcome.php");
?>
Output
In the above code we include a welcome.php file, however the
welcome.php file does not exist in the directory. So there will be a
warning error produced but that does not stop the execution of the script
i.e. you will see a message Warning Error !!. Like in the following
image:

4. Notice Errors
Notice that an error is the same as a warning error i.e. in the notice error
execution of the script does not stop. Notice that the error occurs when
you try to access the undefined variable, then produce a notice error.
Example
<?php
$a="Vineet kumar saini";
echo "Notice Error !!";
echo $b;
?>
Output
In the above code we defined a variable which named $a. But we call
another variable i.e. $b, which is not defined. So there will be a notice
error produced but execution of the script does not stop, you will see a
message Notice Error !!. Like in the following image:

4.3 Handling Errors


Sometimes your application will not run as it supposed to do, resulting
in an error. There are a number of reasons that may cause errors, for
example:
 The Web server might run out of disk space
 A user might have entered an invalid value in a form field
 The file or database record that you were trying to access may not exist
 The application might not have permission to write to a file on the disk
 A service that the application needs to access might be temporarily
unavailable

These types of errors are known as runtime errors, because they occur at
the time the script runs. They are distinct from syntax errors that need to
be fixed before the script will run.
A professional
Error Level application
Value must have the capabilities to handle such
Description
runtime error gracefully. Usually this means informing the user about
the problem more clearly
E_ERROR 1 and A precisely.
fatal run-time error, that can't be recovered
from. The execution of the script is stopped
Understanding Error Levels
Usually, when there's a problem that prevents a script from running
properly, the PHP engine triggers an error. Each error is represented by
an integer value and an associated constant. The following table list
some of the common error levels:
immediately.
E_WARNING 2 A run-time warning. It is non-fatal and most
errors tend to fall into this category. The
execution of the script is not stopped.
E_NOTICE 8 A run-time notice. Indicate that the script
encountered something that could possibly an
error, although the situation could also occur
when running a script normally.
E_USER_ERROR 256 A fatal user-generated error message. This is
like an E_ERROR, except it is generated by
the PHP script using the
function trigger_error() rather than the PHP
engine.
E_USER_WARNING 512 A non-fatal user-generated warning message.
This is like an E_WARNING, except it is
generated by the PHP script using the
function trigger_error() rather than the PHP.
engine
E_USER_NOTICE 1024 A user-generated notice message. This is like
an E_NOTICE, except it is generated by the
PHP script using the
function trigger_error() rather than the PHP
engine.
E_STRICT 2048 Not strictly an error, but triggered whenever
PHP encounters code that could lead to
problems or forward incompatibilities
E_ALL 8191 All errors and warnings, except
of E_STRICT prior to PHP 5.4.0.
The PHP engine triggers an error whenever it encounters a problem with
your script, but you can also trigger errors yourself to generate more user
friendly error messages. This way you can make your application more
sofisticated. The following section describes some of common methods
used for handling errors in PHP:

Basic Error Handling Using the die() Function


Consider the following example that simply tries to open a text file for
reading only.
Example
<?php
// Try to open a non-existent file
$file = fopen("sample.txt", "r");
?>
If the file does not exist you might get an error like this:
Warning: fopen(sample.txt) [function.fopen]: failed to open stream: No
such file or directory in C:\wamp\www\project\test.php on line 2
If we follow some simple steps we can prevent the users from getting
such error message.
Example
<?php
if(file_exists("sample.txt")){
$file = fopen("sample.txt", "r");
} else{
die("Error: The file you are trying to access doesn't exist.");
}
?>
Now if you run the above script you will get the error message like this:
Error: The file you are trying to access doesn't exist.
As you can see by implementing a simple check whether the file exist or
not before trying to access it, we can generate an error message that is
more meaningful to the user.
The die() function used above simply display the custom error message
and terminate the current script if 'sample.txt' file is not found.
4.4 Exception Handling in PHP

An exception is unexpected program result that can be handled by the


program itself. Exception Handling in PHP is almost similar to
exception handling in all programming languages.

PHP provides following specialized keywords for this purpose.


try: It represent block of code in which exception can arise.
 catch: It represent block of code that will be executed when a
particular exception has been thrown.
 throw: It is used to throw an exception. It is also used to list the
exceptions that a function throws, but doesn’t handle itself.
 finally: It is used in place of catch block or after catch block
basically it is put for cleanup activity in PHP code.
Why Exception Handling in PHP ?

Following are the main advantages of exception handling over error


handling
 Separation of error handling code from normal code: In
traditional error handling code there is always if else block to
handle errors. These conditions and code to handle errors got
mixed so that becomes unreadable. With try Catch block code
becomes readable.
 Grouping of error types: In PHP both basic types and objects can
be thrown as exception. It can create a hierarchy of exception
objects, group exceptions in namespaces or classes, categorize
them according to types.
Example 1
<?php

function demo($var) {
echo " Before try block";
try {
echo "\n Inside try block";
if($var == 0)
{

throw new Exception('Number is zero.');

echo "\n After throw (It will never be executed)";


}
}

catch(Exception $e) {
echo "\n Exception Caught", $e->getMessage();
}

echo "\n After catch (will be always executed)";


}

demo(5);
demo(0);
?>

Output:

Before try block


Inside try block
After catch (will be always executed)
Before try block
Inside try block
Exception CaughtNumber is zero.
After catch (will be always executed)

Example 2 :Following code explains the flow of normal try catch


and finally block in PHP
<?php

// PHP Program to illustrate normal


// try catch block code
function demo($var) {

echo " Before try block";


try {
echo "\n Inside try block";

// If var is zerothen only if will be executed


if($var == 0) {

// If var is zero then only exception is thrown


throw new Exception('Number is zero.');

// This line will never be executed


echo "\n After throw it will never be executed";
}
}

// Catch block will be executed only


// When Exception has been thrown by try block
catch(Exception $e) {
echo "\n Exception Caught" . $e->getMessage();
}
finally {
echo "\n Here cleanup activity will be done";
}

// This line will be executed whether


// Exception has been thrown or not
echo "\n After catch it will be always executed";
}

// Exception will not be rised


demo(5);

// Exception will be rised here


demo(0);
?>
OUTPUT:Before try block
Inside try block
Here cleanup activity will be done
After catch (will be always executed)
Before try block
Inside try block
Exception CaughtNumber is zero.
Here cleanup activity will be done
After catch (will be always executed)

4.5 State Management in PHP


HTTP is a stateless protocol which means every user request is
processed independently and it has nothing to do with the requests
processed before it. Hence there is no way to store or send any user
specific details using HTTP protocol.
But in modern applications, user accounts are created and user specific
information is shown to different users, for which we need to have
knowledge about who the user(or what he/she wants to see etc) is on
every webpage.
PHP provides for two different techniques for state management of your
web application, they are:

1. Server Side State Management


2. Client Side state Management

Server Side State Management


In server side state management we store user specific information
required to identify the user on the server. And this information is
available on every webpage.
In PHP we have Sessions for server side state management. PHP session
variable is used to store user session information like username, userid
etc and the same can be retrieved by accessing the session variable on
any webpage of the web application until the session variable is
destroyed.

Client Side State Management


In client side state management the user specific information is stored at
the client side i.e. in the bowser. Again, this information is available on
all the webpages of the web application.
In PHP we have Cookies for client side state management. Cookies are
saved in the browser with some data and expiry date(till when the cookie
is valid).
One drawback of using cookie for state management is the user can
easily access the cookie stored in their browser and can even delete it.

4.6 Cookies in PHP


Cookie is a small piece of information stored as a file in the user's
browser by the web server. Once created, cookie is sent to the web
server as header information with every HTTP request.
You can use cookie to save any data but it should not exceed 1K(1024
bytes) in size.
Before we move on to how to create, update and delete a cookies, let's
learn a few real world use of cookies.

Real world Use of Cookies


1. To store user information like when he/she visited, what pages
were visited on the website etc, so that next time the user visits
your website you can provide a better user experience.
2. To store basic website specific information to know this is not the
first visit of user.
3. You can use cookies to store number of visits or view counter.
I hope this gives you an idea about how you can utilize cookies in your
web application.
Types of Cookies
There are two types of cookies, they are:
1. Session Cookie: These types of cookies are temporary and are
expiring as soon as the session ends or the browser is closed.
2. Persistent Cookie: To make a cookie persistent we must provide it
with an expiration time. Then the cookie will only expire after the
given expiration time, until then it will be a valid cookie.
Creating a Cookie in PHP
In PHP we can create/set a cookie using the setcookie() function.
Below we have the syntax for the function,
setcookie(name, value, expire, path, domain, secure)
The first argument which defines the name of the cookie is mandatory,
rest all are optional arguments. Let's understand what are the available
arguments that we can supply to the setcookie() function to set a cookie.

Argument What is it for?

name Used to specify the name of the cookie. It is a mandatory


argument. Name of the cookie must be a string.

value Used to store any value in the cookie. It is generally saved


as a pair with name. For example, name is userid and value
is 7007, the userid for any user.

expire Used to set the expiration time for a cookie. if you do not
provide any value, the cookie will be treated as a session
cookie and will expire when the browser is closed.

path Used to set a web URL in the cookie. If set, the cookie will
be accessible only from that URL. To make a cookie
accessible through a domain, set '/' as cookie path.

domain The domain of your web application. It can be used to limit


access of cookie for sub-domains. For example, if you set
the domain value as wwww.studytonight.com, then the
cookie will be inaccessible from blog.studytonight.com

secure If you set this to 1, then the cookie will be available and sent
only over HTTPS connection.

So if we want to create a cookie to store the name of the user who


visited your website, and set an expiration time of a week, then we can
do it like this,
setcookie("username", "iamabhishek", time()+60*60*24*7);

To access a stored cookie we use the $_COOKIE global variable, and


can use the isset() methos to check whether the cookie is set or not.
Let's have a complete example where we will set a cookie and then
retrieve it to show its value in the HTML page.

<?php // check if the cookie exists

if(isset($_COOKIE["username"]))

{ echo "Cookie set with value: ".$_COOKIE["username"];

else {

echo "cookie not set!";

} ?>

</body>
</html>
<So by providing the name of the cookie inside the square brakets with
the globalcookie.
NOTE: setcookie() function should be placed before the starting HTML
tag(<html>).

Updating Cookie in PHP


To update/modify a cookie, simply set it again. For example, if we want
to update the username stored in the cookie created above, we can do it
using setcookie() method again,
We just update the value of username cookie
from iamabhishek to iamNOTabhishek.

Delete a Cookie in PHP


To delete/remove a cookie, we need to expire the cookie, which can be
done by updating the cookie using the setcookie() function with
expiration date in past.
Example for Cookies in PHP
Form.html
<html>
<body>
<form action="setcookie.php" method="POST">
Name: <input type="text" name="uname"/><br>
E-mail: <input type="text" name="email"/><br>
<input type="submit" name="submit"/>
</form>
</body>
</html>
OUPUT:

setcookie.php

<?php
if(isset($_POST['submit']))
{
$n=$_POST['uname'];
$e=$_POST['email'];
setCookie("name",$n);
setCookie("mail",$e,time()+86400,"/","",0);
echo "cookies are set";
echo "<a href='getcookie.php'><br>Click here to get
cookies</br></a>";
}
?>
OUTPUT:

getcookie.php
<?php
if(isset($_COOKIE["uname"]))
echo "welcome:".$_COOKIE["uname"]."<br/>";
else
echo "name not set";
if(isset($_COOKIE["email"]))
echo "Email is :".$_COOKIE["email"]."<br/>";
else
echo "email not set";
?>
OUTPUT:

Let's take a practical example, when you log into your facebook account,
by providing your email address and password, until and unless you
logout, the web application remembers who you are and display what
your friends are posting and liking on your News Feed, you can update
your profile, send someone message, join a group etc, this is
accomplished by Session.
When a user logs into their account on any web application, a session is
created for them, and in the session their username or userid or some
other unique identifier is stored, which is then used on the consecutive
webpages to show information specific to that user. On logout, the
session is destroyed.
Session is not limited by any size limit, you can store any information in
the session, irrespective of its size.
Before we move on to how to start, update and end a session in PHP,
let's learn a few realworld use of session.

Real world Use of Session

1. Web applications which require a user to login, use session to store


user information, so that on every webpage related information can
be displayed to the user.
2. In eCommerce websitees, shopping cart is generally saved as part
of session.

Start a Session in PHP


In PHP we can start a session by using the session_start() function. And
data is stored in the session using session variable, which can be
assigned different values using global variable $_SESSION
In simpler words, using the function session_start() we initialize the
session, in which we can store information using the session
variable $_SESSION.
Let's take an example, below we have a webpage with Php file
named first_page.php
<?php
// start the session
session_start();

// set the session variable


$_SESSION["username"] = "iamabhishek";
$_SESSION["userid"] = "1";
?>

<html>
<body>

NOTE: The function session_start() should be the first statement of the


page, before any HTML tag.

Getting PHP Session Variable Values


In the code above, we have started a session and set two session
variables. Above webpage will also have a link to navigate to Second
page second_page.php.
Below is the code for second_page.php, in which we fetch values from
the session variable which are set in the first_page.php.
<?php
// start the session
session_start();

// get the session variable values


$username = $_SESSION["username"];
$userid = $_SESSION["userid"];
?>

<html>
<body>

<?php
echo "Username is: ".$username."<br/>";
echo "User id is: ".$userid;
?>

</body>
</html>
You must be thinking, why we used session_start() here although we did
not set any new values in the session variable.
session_start() function is used to initialize a new session and to fetch
the ongoing session(if already started), and then, using
the $_SESSION global variable, we can either set new values into the
session or get the saved values.
If there are too many values stored in the session, and you don't know
which one do you want to get, you can use the below code to print all the
current session variable data.
<?php
// start the session
session_start();
?>

<html>
<body>

To update any value stored in the session variable, start the session by
calling session_start() function and then simply overwrite the vakue to
update session variable.
<<?phpme isiamabhishek
User id is: 1111

We just updated the value of userid in the session variable


from 1 to 1111.

Destroy a Session in PHP


To clean the session variable or to remove all the stored values from the
session variable we can use the function session_unset() and to detroy
the session, we use session_destroy() function.

Example for session


Session.php
<?php
if(isset($_POST['submit']))
{
session_start();
$_SESSION['user']=$_POST['uname'];
echo "session varaible set";
echo "<a href='checksession.php'><br>read session variable</b></a>";
exit();
}
?>
<html>
<body>
<form action="session.php" method="POST">
Name: <input type="text" name="uname"/><br>
E-mail: <input type="text" name="email"/><br>
<input type="submit" name="submit"/>
</form>
</body>
</html>
OUTPUT:

Checksesion.php
<?php
session_start();
echo "hello ".$_SESSION['user'];
?>
OUTPUT:

The PHP mail() Function


To send email using PHP, you use the mail() function. This accepts 5
parameters as follows (the last 2 are optional).

Mail(to,subject,message,headers,parameters)

Parameter Description

to Required. The recipient's email address.

subject Required. The email's subject line.


message Required. The actual email body.

headers Optional. Additional header fields such as "From", "Cc",


"Bcc" etc.

parameters Optional. Any additional parameters.

Configuring PHP Mail function


1. Open php.ini file which is available in C:\xampp\php.ini
2. In that file search for mail function
3. In mail function update
SMTP = SMTP.gmail.com
smtp_port = 587
4. Open another file sendmail which is available in
C:\xampp\sendmail
5. In sendmail update with
smtp_server=SMTP.gmail.com
smtp_port=587
error_logfile=error.log
debug_logfile=debug.log
default_domain=SMTP.gmail.com
auth_username=swapnabaduguna2010@gmail.com
auth_password=12345678
force_sender=swapnabaduguna2010@gmail.com
6. Restart your webserver

Then write the following PHP script to send mail

<?php
$to = "swapnadadigala@gmail.com";
$subject = "This is subject";
$message = "This is simple text message.";
$headers = "From: $from";
mail($to,$subject,$message,$headers);
echo "mail sent";
?>

Images with PHP

PHP provides multiple functions to create images from scratch and they
can be used to generate images of different extensions
(JPEG, GIF, PNG, etc...).

The imagecreatefromjpeg() function

An image can be created from a file or URL by a


function imagecreatefromjpeg(). which will create an image of an type
(extension) JPEG.

Example of creating a JPG (JPEG) image with PHP

<?php
function createJPEG($imagename)
{
$image = @imagecreatefromjpeg($imagename);
if(!$image)
{
$image = imagecreatetruecolor(150, 30);
$bgc = imagecolorallocate($image, 255, 255, 255);
$tc = imagecolorallocate($image, 0, 0, 0);
imagefilledrectangle($image, 0, 0, 150, 30, $bgc);
imagestring($image, 1, 5, 5, "Error loading image" .
$imagename, $tc);
}
return $image;
}
header("Content-Type: image/jpeg");
$image = createJPEG("fake_image.png");
imagejpeg($image);
imagedestroy($image);
?>

You might also like