Unit Iv Error Handling
Unit Iv Error Handling
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:
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:
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:
function demo($var) {
echo " Before try block";
try {
echo "\n Inside try block";
if($var == 0)
{
catch(Exception $e) {
echo "\n Exception Caught", $e->getMessage();
}
demo(5);
demo(0);
?>
Output:
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.
secure If you set this to 1, then the cookie will be available and sent
only over HTTPS connection.
if(isset($_COOKIE["username"]))
else {
} ?>
</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>).
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.
<html>
<body>
<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
Checksesion.php
<?php
session_start();
echo "hello ".$_SESSION['user'];
?>
OUTPUT:
Mail(to,subject,message,headers,parameters)
Parameter Description
<?php
$to = "[email protected]";
$subject = "This is subject";
$message = "This is simple text message.";
$headers = "From: $from";
mail($to,$subject,$message,$headers);
echo "mail sent";
?>
PHP provides multiple functions to create images from scratch and they
can be used to generate images of different extensions
(JPEG, GIF, PNG, etc...).
<?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);
?>