PHP Error Handling Section :I Source: www.w3schools.comwww.w3schools.com 1.

Slides:



Advertisements
Similar presentations
PHP Form and File Handling
Advertisements

Error HandlingPHPMay-2007 : [#] PHP Error Handling.
Error-handling using exceptions
Detecting Bugs Using Assertions Ben Scribner. Defining the Problem  Bugs exist  Unexpected errors happen Hardware failures Loss of data Data may exist.
Exception Handling Chapter 15 2 What You Will Learn Use try, throw, catch to watch for indicate exceptions handle How to process exceptions and failures.
Introduction to Exceptions in Java. 2 Runtime Errors What are syntax errors? What are runtime errors? Java differentiates between runtime errors and exceptions.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 15: Exception Handling.
Chapter 16: Exception Handling C++ Programming: From Problem Analysis to Program Design, Fifth Edition.
Objectives In this chapter you will: Learn what an exception is Learn how to handle exceptions within a program See how a try / catch block is used to.
Chapter 8Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 8 l Basic Exception Handling »the mechanics of exceptions l.
SE-1020 Dr. Mark L. Hornick 1 Exceptions and Exception Handling.
© The McGraw-Hill Companies, 2006 Chapter 15. © The McGraw-Hill Companies, 2006 Exceptions an exception is an event that occurs during the life of a program.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 16: Exception Handling.
Jerry Lebowitz. Topics  Provides a facility for a systematic object oriented approach to handling runtime errors ◦ Can also handle runtime errors.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
E XCEPTION H ANDLING Chapter 11 C S 442: A DVANCED J AVA P ROGRAMMING.
Exception Handling Introduction Exception handling is a mechanism to handle exceptions. Exceptions are error like situations. It is difficult to decide.
XAMPP: Cross – Apache, MySQL, Php, Perl + FileZilla, Tomcat NetBeans: IDE PHP Installation.
CSCI 215 Web Programming II Debugging & Error Handling.
Exceptions Objectives At the conclusion of this lesson, students should be able to Explain the need for exceptions Correctly write programs that use.
Exceptions. Many problems in code are handled when the code is compiled, but not all Some are impossible to catch before the program is run  Must run.
Lecture 8 : PHP Errors & Exceptions UFCFR Advanced Topics in Web Development II 2014/15 SHAPE Hong Kong.
Kyle MacLachlan.  Used To Format a Date/Time  Syntax: › date(format,timestamp)  format: Required, specifies format  timestamp:Optional, specifies.
PHP Tutorials 02 Olarik Surinta Management Information System Faculty of Informatics.
Open Source Server Side Scripting ECA 236 Open Source Server Side Scripting PHP Form Handling.
INTRODUCTION TO PHP Basic concept of PHP and Much More Prepared By: Farhan Nisar(7 th Semester) University of Peshawar.
Object Oriented Programming
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. Chapter 13 Files and Exception Handling 1.
Java Programming Exception Handling. The exception handling is one of the powerful mechanism provided in java. It provides the mechanism to handle the.
Understanding Events and Exceptions Lesson 3. Objective Domain Matrix Skills/ConceptsMTA Exam Objectives Understand events and event handling Understand.
PHP3. PHP File Upload With PHP, it is possible to upload files to the server. Create an Upload-File Form To allow users to upload files from a form can.
PHP Advance. Agenda Server side Includes File Handling Cookies Sessions Error/Exception handling Database handling with MySQL sending.
CMSC 202 Exceptions. Aug 7, Error Handling In the ideal world, all errors would occur when your code is compiled. That won’t happen. Errors which.
PHP meets MySQL.
PHP Workshop ‹#› PHP Error Handling. PHP Workshop ‹#› Types There are 12 unique error types, which can be grouped into 3 main categories: Informational.
Accessing MySQL with PHP IDIA 618 Fall 2014 Bridget M. Blodgett.
Creating Dynamic Web Pages Using PHP and MySQL CS 320.
Exceptions Handling Exceptionally Sticky Problems.
JSP Exception Handling 20-Oct-15. JSP - E XCEPTION H ANDLING When you are writing JSP code, a programmer may leave a coding errors which can occur at.
VB.Net - Exceptions Copyright © Martin Schray
PHP2. PHP Form Handling The PHP $_GET and $_POST variables are used to retrieve information from forms, like user input. Name: Age:
Introduction to Exception Handling and Defensive Programming.
Variables and ConstantstMyn1 Variables and Constants PHP stands for: ”PHP: Hypertext Preprocessor”, and it is a server-side programming language. Special.
Chapter 14: Exception Handling. Objectives In this chapter, you will: – Learn what an exception is – Learn how to handle exceptions within a program –
Topics Sending an Multipart message Storing images Getting confirmation Session tracking using PHP Graphics Input Validators Cookies.
8 th Semester, Batch 2008 Department Of Computer Science SSUET.
Computer Programming with JAVA Chapter 8. Exception Handling Basic Exception Handling the mechanics of exceptions Defining and Using Exceptions some "simple"
PHP Error Handling & Reporting. Error Handling Never allow a default error message or error number returned by the mysql_error() and mysql_errno() functions.
Chapter 15: Exception Handling C++ Programming: Program Design Including Data Structures, Fifth Edition.
Copyright © Curt Hill Error Handling in Java Throwing and catching exceptions.
8 th Semester, Batch 2008 Department Of Computer Science SSUET.
Creating FunctionstMyn1 Creating Functions Function can be divided into two groups: –Internal (built in) functions –User-defined functions.
Exceptions Lecture 11 COMP 401, Fall /25/2014.
IMS 3253: Validation and Errors 1 Dr. Lawrence West, MIS Dept., University of Central Florida Topics Validation and Error Handling Validation.
Exception Handling How to handle the runtime errors.
Unit-6 Handling Sessions and Cookies. Concept of Session Session values are store in server side not in user’s machine. A session is available as long.
PHP Exception Handling How to handle and create user-defined exceptions Mario Peshev Technical Trainer Software University
Martin Kruliš Who is General Failure and why is he reading my disk? by Martin Kruliš (v1.0)1.
ECE122 L23: Exceptions December 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 24 Exceptions.
Introduction to Exceptions in Java CS201, SW Development Methods.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Exceptions Exceptions are used to signal that an unexpected event has happened in a program C++ will generate exceptions for some errors in the program.
Exceptions.
Handling Exceptionally Sticky Problems
Chapter 14: Exception Handling
Part B – Structured Exception Handling
Exception Handling Imran Rashid CTO at ManiWeber Technologies.
Handling Exceptionally Sticky Problems
CMSC 202 Exceptions.
Exception Handling.
Presentation transcript:

PHP Error Handling Section :I Source: 1

PHP E XCEPTION H ANDLING Exceptions are used to change the normal flow of a script if a specified error occurs. It is used to change the normal flow of the code execution if a specified error (exceptional) condition occurs. This condition is called an exception. 2

U SE OF E XCEPTIONS when an exception is triggered: The current code state is saved. The code execution will switch to a predefined (custom) exception handler function. Depending on the situation, the handler may then resume the execution from the saved code state, terminate the script execution or continue the script from a different location in the code 3

K EYWORD USED IN EXCEPTION HANDLING Try - A function using an exception should be in a "try" block. If the exception does not trigger, the code will continue as normal. However if the exception triggers, an exception is "thrown". Throw - This is how you trigger an exception. Each "throw" must have at least one "catch". Catch - - A "catch" block retrieves an exception and creates an object containing the exception information. 4

S IMPLE EXCEPTION WITHOUT HANDLING 1) { throw new Exception("Value must be 1 or below"); } return true; } //trigger exception checkNum(2); ?> 5

C ONT : The code above will get an error like this: Fatal error : Uncaught exception 'Exception' with message 'Value must be 1 or below' in C:\webfolder\test.php:6 Stack trace: #0 C:\webfolder\test.php(12): checkNum(28) #1 {main} thrown in C:\webfolder\test.php on line 6 6

N OW LETS HANDLE THE EXCEPTION 7

1) { throw new Exception("Value must be 1 or below"); } return true; } //trigger exception in a "try" block try { checkNum(2); //If the exception is thrown, this text will not be shown echo 'If you see this, the number is 1 or below'; } //catch exception catch(Exception $e) { echo 'Message: '.$e->getMessage(); } ?> 8

The code above will get an error like this: Message: Value must be 1 or below 9

PHP E RROR H ANDLING When creating scripts and web applications, error handling is an important part. If your code lacks error checking code, your program may look very unprofessional and you may be open to security risks. Error handling methods: 1. Simple "die()" statements 2. Custom errors and error triggers 3. Error reporting 10

U SING THE DIE () FUNCTION <?php $file=fopen("welcome.txt","r"); ?> If the file does not exist you might get an error like this: Warning: fopen(welcome.txt) [function.fopen]: failed to open stream: No such file or directory in C:\webfolder\test.php on line 2 To avoid that the user gets an error message like the one above, we test if the file exist before we try to access it. 11

if(!file_exists("welcome.txt")) { die("File not found"); } else { $file=fopen("welcome.txt","r"); } ?> Now if the file does not exist you get: File not found 12

$con = mysql_connect("localhost","peter","abc123"); if (!$con) { die('Could not connect: '. mysql_error()); } // some code 13

The code above is more efficient than the earlier code, because it uses a simple error handling mechanism to stop the script after the error. However, simply stopping the script is not always the right way to go. Let's take a look at alternative PHP functions for handling errors. 14

C REATING A C USTOM E RROR H ANDLER Creating a custom error handler is quite simple. We simply create a special function that can be called when an error occurs in PHP. This function must be able to handle a minimum of two parameters (error level and error message) but can accept up to five parameters (optionally: file, line-number, and the error context): Syntax: error_function(error_level,error_message, error_file,error_line,error_context) 15

16

E RROR R EPORT LEVELS 17

EXMPLE function customError($errno, $errstr) { echo " Error: [$errno] $errstr "; echo "Ending Script"; die(); } The code above is a simple error handling function. When it is triggered, it gets the error level and an error message. It then outputs the error level and message and terminates the script. 18

S ET E RROR H ANDLER  The default error handler for PHP is the built in error handler.  We are going to make the function above the default error handler for the duration of the script.  It is possible to change the error handler to apply for only some errors.  that way the script can handle different errors in different ways. 19

SET _ ERROR _ HANDLER (); Let see how to trigger error via set_error_handler(); 20

<?php //error handler function function customError($errno, $errstr) { echo " Error: [$errno] $errstr"; } //set error handler set_error_handler("customError"); //trigger error echo($test); ?> 21

T RIGGER AN E RROR In a script where users can input data it is useful to trigger errors when an illegal input occurs. In PHP, this is done by the trigger_error() function. $test=2; if ($test>1) { trigger_error("Value must be 1 or below"); } ?> Notice: Value must be 1 or below in C:\webfolder\test.php on line 6 22

P OSSIBLE ERROR TYPES : E_USER_ERROR - Fatal user-generated run- time error. Errors that can not be recovered from. Execution of the script is halted E_USER_WARNING - Non-fatal user-generated run-time warning. Execution of the script is not halted E_USER_NOTICE - Default. User-generated run-time notice. The script found something that might be an error, but could also happen when running a script normally 23

<?php //error handler function function customError($errno, $errstr) { echo " Error: [$errno] $errstr "; echo "Ending Script"; die(); } //set error handler set_error_handler("customError",E_USER_WARNING); //trigger error $test=2; if ($test>1) { trigger_error("Value must be 1 or below",E_USER_WARNING); } 24

O UTPUT : Error: [512] Value must be 1 or below Ending Script 25

PHP F ILTER  A PHP filter is used to validate and filter data coming from insecure sources.  To test, validate and filter user input or custom data is an important part of any web application.  The PHP filter extension is designed to make data filtering easier and quicker. 26

 Almost all web applications depend on external input.  Data comes from a user or another application (like a web service).  By using filters you can be sure your application gets the correct input type.  Input data from a form  Cookies  Web services data  Server variables  Database query results 27

F UNCTIONS AND F ILTERS To filter a variable: filter_var() - Filters a single variable with a specified filter filter_var_array() - Filter several variables with the same or different filters filter_input - Get one input variable and filter it filter_input_array - Get several input variables and filter them with the same or different filters 28

E XAMPLE : 29

The code uses the "FILTER_VALIDATE_INT" filter to filter the variable. Since the integer is valid, the output of the code above will be: "Integer is valid". 30

K INDS O F FILTERS : There are two kinds of filters. 1. Validating filters: 2. Sanitizing filters: Validating filters: Are used to validate user input Strict format rules (like URL or validating) Sanitizing filters: Are used to allow or disallow specified characters in a string No data format rules Always return the string 31

O PTIONS AND F LAGS  Options and flags are used to add additional filtering options to the specified filters.  Different filters have different options and flags.  Let validate an integer using the filter_var() and the "min_range" and "max_range" options: 32

array ( "min_range"=>0, "max_range"=>256 ) ); if(!filter_var($var, FILTER_VALIDATE_INT, $int_options)) { echo("Integer is not valid"); } else { echo("Integer is valid"); } ?> 33

C ONT : Options must be put in an associative array with the name "options". If a flag is used it does not need to be in an array. Since the integer is "300" it is not in the specified range, and the output of the code above will be: "Integer is not valid". 34

PHP M AIL The PHP mail() Function is common to send input data from a web form to an address. mail( to,subject,message,headers,parameters ). 35

PHP S END M AIL E XAMPLE (NON-SECURE!) "> From: Subject: Message: 36

C ONT : 37