SlideShare a Scribd company logo
Object Oriented PHP
By: Jalpesh Vasa
Class unitcounter
{
var $units;
var $weightperunit;
function add($n=1)
{
$this->units = $this->units+$n;
}
function toatalweight()
{
return $this->units * $this->weightperunit;
}
function _ _construct($unitweight=1.0)
{
$this->weightperunit = $unitweight;
$this->units=0;
}
}
$brick = new unitcounter(1.2);
$brick->add(3)
$w1 = $brick->totalweight();
print “total weight of {$brick->units} bricks = $w1”;
Cloning Objects
• A variable assigned with an objects is actually
a reference to the object.
• Copying a object variable in PHP simply
creates a second reference to the same object.
• Example:
$a = new unitcounter();
$a->add(5);
$b=$a;
$b->add(5);
Echo “number of units={$a->units}”;
Echo “number of units={$b->units}”;
//prints number of units = 10
• The _ _clone() method is available, if you want
to create an independent copy of an object.
$a = new unitcounter();
$a->add(5);
$b=$a->_ _clone();
$b->add(5);
Echo “number of units={$a->units}”; //prints 5
Echo “number of units={$b->units}”; //prints 10
Inheritance
• One of most powerful concept of OOP
• Allows a new class to be defined by extending
the capabilities of an existing base class or
parent class.
<?php
Require “a1.php”;
Class casecounter extends unitcounter
{
var $unitpercase;
function addcase()
{
$this->add($this->unitpercase);
}
function casecount()
{
return ceil($this->units/$this->unitpercase);
}
function casecounter($casecapacity)
{
$this->unitpercase = $casecapacity;
}
}
?>
$order = new casecounter(12);
$order->add(7);
$order->addcase();
Print $order->units; // prints 17
Print $order->casecount(); //prints 2
Calling a parent class constructor
<?php
Require “a1.php”;
Class casecounter extends unitcounter
{
var $unitpercase;
function addcase()
{
$this->add($this->unitpercase);
}
function casecount()
{
return ceil($this->units/$this->unitpercase);
}
function casecounter($casecapacity, $unitweight)
{
parent::_ _construct($unitweight);
$this->unitpercase = $casecapacity;
}
}
?>
Function overriding
Class shape
{
function info()
{
return “shape”;
}
}
Class polygon extends shape
{
function info()
{
return “polygon”;
}
}
$a = new shape();
$b = new polygon();
Print $a->info(); //prints shape
Print $b->info(); //prints polygon
Function overriding
Class polygon extends shape
{
function info()
{
return parent::info().“.polygon”;
}
}
$b = new polygon();
Print $b->info(); //prints shape.polygon
Function overriding
Class triangle extends polygon
{
function info()
{
return parent::info().“.triangle”;
}
}
$t = new triangle();
Print $t->info(); //prints shape.polygon.triangle
Protected member variables and functions
• Member variables and functions can be defined
using protected keyword.
• Offers a compromise between being public and
private.
• It allows access to member variables and functions
defined in a class from within descendant classes,
but it prevents access from outside of the class
hierarchy.
• A child class can access a parent class’s protected
function, but parent class protected function can’t
be accessed from an unrelated class or from within a
script that uses the class.
Final functions
• Descendant classes can be prevented from
redefining member functions in base class by
declaring them as final
• Final keyword prevents accidental redefinition
in a descendant class.
Error Handling
• Error handling is the process of catching errors
raised by your program and then taking
appropriate action.
• The default error handling in PHP is very simple.
• An error message with filename, line number and
a message describing the error is sent to the
browser.
• We will show different error handling methods:
– Simple "die()" statements
– Custom errors and error triggers
– Error reporting
Using the die() function
• While writing your PHP program you should check all
possible error condition before going ahead and take
appropriate action when required.
<?php
if(!file_exists("/tmp/test.txt"))
{
die("File not found");
}
else {
$file=fopen("/tmp/test.txt","r");
print "Opend file sucessfully"; }
// Test of the code here. ?>
Using the die() function
• Now if the file does not exist you get an error like
this:
File not found
• 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.
Defining Custom Error Handling Function
• You can write your own function to handling any
error. PHP provides you a framework to define
error handling function.
• 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):
• error_function(error_level,error_message,
error_file,error_line,error_context);
Defining Custom Error Handling Function
Parameter Description
error_level Required. Specifies the error report level for the user-
defined error. Must be a value number. See table
below for possible error report levels
error_message Required. Specifies the error message for the user-
defined error
error_file Optional. Specifies the filename in which the error
occurred
error_line Optional. Specifies the line number in which the
error occurred
error_context Optional. Specifies an array containing every variable,
and their values, in use when the error occurred
Error Report levels
Value Constant Description
2 E_WARNING Non-fatal run-time errors. Execution of the script is not
halted
8 E_NOTICE Run-time notices. The script found something that
might be an error, but could also happen when running
a script normally
256 E_USER_ERROR Fatal user-generated error. This is like an E_ERROR set by
the programmer using the PHP function trigger_error()
512 E_USER_WARNING Non-fatal user-generated warning. This is like an
E_WARNING set by the programmer using the PHP
function trigger_error()
1024 E_USER_NOTICE User-generated notice. This is like an E_NOTICE set by
the programmer using the PHP function trigger_error()
4096 E_RECOVERABLE_ERROR Catchable fatal error. This is like an E_ERROR but can be
caught by a user defined handle (see also
set_error_handler())
8191 E_ALL All errors and warnings (E_STRICT became a part of
E_ALL in PHP 5.4)
Defining Custom Error Handling Function
• Now lets create a function to handle errors:
function customError($errno, $errstr)
{
echo "<b>Error:</b> [$errno] $errstr<br>";
echo "Ending Script";
die();
}
OR
function handleError($errno, $errstr,$error_file,$error_line)
{
echo "<b>Error:</b> [$errno] $errstr - $error_file:$error_line";
echo "<br />";
echo "Terminating PHP Script";
die();
}
Set Error Handler
• 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.
<?php
//error handler function
function customError($errno, $errstr) {
echo "<b>Error:</b> [$errno] $errstr";
}
//set error handler
set_error_handler("customError");
//trigger error
echo($test);
?>
Error: [8] Undefined variable: test
PHP Exception Handling
• Exception handling is used to change the
normal flow of the code execution if a
specified error (exceptional) condition occurs.
This condition is called an exception.
• Exceptions give us much better handling of
errors an allow us to customize the behavior
of our scripts when an error (Exception) is
encountered.
• Exceptions are important and provides a
better control over error handling.
PHP Exception Handling
• This is what normally happens 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
PHP Exception Handling
• Exceptions are actually objects and you have the option to 'catch'
them and execute certain code. This is done by using 'try-catch'
blocks:
try {
// some code goes here
// which might throw an exception
}
catch (Exception $e) {
// the code here only gets executed
// if an exception happened in the try block above
}
PHP Exception Handling
• Lets explain three new keyword related to
exceptions.
• 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.
PHP Exception Handling
• Let's say you want to calculate the area of a
circle, by the given radius. This function will do
that:
function circle_area($radius)
{
return pi() * $radius * $radius;
}
PHP Exception Handling
• It is very simple, however it does not check if the radius is
a valid number. Now we are going to do that, and throw
an exception if the radius is a negative number:
function circle_area($radius) {
// radius can't be negative
if ($radius < 0) {
throw new Exception('Invalid Radius: ' . $radius);
}
else
{
return pi() * $radius * $radius;
}
}
PHP Exception Handling
• Let's see what happens when we call it with a
negative number:
$radius = -2;
echo "Circle Radius: $radius => Circle Area: ".
circle_area($radius) . "n";
echo "Another line";
PHP Exception Handling
• The script crashes with the following message:
<br />
<b>Fatal error</b>: Uncaught exception 'Exception'
with message 'Invalid Radius: -2' in
C:wampwwwtesttest.php:19
Stack trace:
#0 C:wampwwwtesttest.php(7): circle_area(-2)
#1 {main}
thrown in <b>C:wampwwwtesttest.php</b> on
line <b>19</b><br />
PHP Exception Handling
$radius_array = array(2,-2,5,-3);
foreach ($radius_array as $radius) {
try {
echo "Circle Radius: $radius => Circle Area: ".
circle_area($radius) . "n";
} catch (Exception $e) {
echo 'Caught Exception: ', $e->getMessage(), "n";
}
}
PHP Exception Handling
Now we get this output:
Circle Radius: 2 => Circle Area: 12.566370614359
Caught Exception: Invalid Radius: -2
Circle Radius: 5 => Circle Area: 78.539816339745
Caught Exception: Invalid Radius: -3
There are no more errors, and the script continues
to run. That is how you catch exceptions.
PHP Exception Handling
• When an exception is thrown from a function or
a class method, it goes to whoever called that
function or method. And it keeps on doing this
until it reaches the top of the stack OR is caught.
If it does reach the top of the stack and is never
called, you will get a fatal error.
PHP Exception Handling
function bar() {
throw new Exception('Message from bar().');
}
function foo() {
bar();
}
try {
foo();
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "n“;
PHP Exception Handling
• In the above example $e->getMessage function
is used to get error message. There are following
functions which can be used
from Exception class.
• getMessage()- message of exception
• getCode() - code of exception
• getFile() - source filename
• getLine() - source line
• getTrace() - n array of the backtrace()
• getTraceAsString() - formated string of trace
File upload in PHP
• How to upload file on server?
• How to limit size of file?
• How to check /limit file type?
• Where to store your file?
File upload in PHP
• First, ensure that PHP is configured to allow file
uploads.
• In your "php.ini" file, search for
the file_uploads directive, and set it to On:
• file_uploads = On
File upload in PHP(html file)
• <!DOCTYPE html>
<html>
<body>
<form action="upload.php" method="post" enctype="multipart
/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
File upload in PHP(html file)
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
?>
File upload in PHP(html file)
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
File upload in PHP(html file)
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" &&
$imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
File upload in PHP(html file)
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"],
$target_file)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). "
has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}

More Related Content

PPTX
Arrays &amp; functions in php
PDF
Object Oriented PHP - PART-1
PDF
4.2 PHP Function
PPT
php 2 Function creating, calling, PHP built-in function
PPT
Introduction To Lamp
PPSX
Javascript variables and datatypes
PDF
Functions in PHP
PPTX
PHP Basics
Arrays &amp; functions in php
Object Oriented PHP - PART-1
4.2 PHP Function
php 2 Function creating, calling, PHP built-in function
Introduction To Lamp
Javascript variables and datatypes
Functions in PHP
PHP Basics

What's hot (20)

PDF
JavaScript - Chapter 6 - Basic Functions
PDF
Creating native apps with WordPress
PPT
Javascript
PDF
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
PPTX
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
PDF
JavaScript Basics and Best Practices - CC FE & UX
PPT
PHP - Introduction to PHP Date and Time Functions
PPTX
PHP FUNCTIONS
PPTX
JavaScript Literacy
PDF
Basics of JavaScript
PDF
Advanced Interfaces and Repositories in Laravel
PDF
Design patterns in PHP
PDF
A Gentle Introduction To Object Oriented Php
PPT
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
PPT
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
PDF
jQuery - Chapter 5 - Ajax
PPT
Create a web-app with Cgi Appplication
PDF
3.1 javascript objects_DOM
ODP
Php variables (english)
PPT
JavaScript Basics
JavaScript - Chapter 6 - Basic Functions
Creating native apps with WordPress
Javascript
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
JavaScript Basics and Best Practices - CC FE & UX
PHP - Introduction to PHP Date and Time Functions
PHP FUNCTIONS
JavaScript Literacy
Basics of JavaScript
Advanced Interfaces and Repositories in Laravel
Design patterns in PHP
A Gentle Introduction To Object Oriented Php
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
jQuery - Chapter 5 - Ajax
Create a web-app with Cgi Appplication
3.1 javascript objects_DOM
Php variables (english)
JavaScript Basics
Ad

Similar to Object Oriented PHP - PART-2 (20)

PDF
Introduction to php exception and error management
PPTX
object oriented programming in PHP & Functions
PPTX
lecture 15.pptx
PDF
Elegant Ways of Handling PHP Errors and Exceptions
PPTX
Error and Exception Handling in PHP
PDF
Error Handling In PHP with all Try catch anf various runtime errors
PPT
PHP - Introduction to PHP Error Handling
PDF
Sending emails through PHP
PPTX
Error handling
PDF
Php exceptions
PPT
Error reporting in php
PDF
Module-4_WTA_PHP Class & Error Handling
PPT
Php Error Handling
PPTX
Handling error & exception in php
PPT
PHP - DataType,Variable,Constant,Operators,Array,Include and require
PDF
Preparing for the next PHP version (5.6)
ODP
PHP Basic
PDF
Errors, Exceptions & Logging (PHPNW13 Uncon)
PDF
Errors, Exceptions & Logging (PHP Hants Oct '13)
DOCX
Php advance
Introduction to php exception and error management
object oriented programming in PHP & Functions
lecture 15.pptx
Elegant Ways of Handling PHP Errors and Exceptions
Error and Exception Handling in PHP
Error Handling In PHP with all Try catch anf various runtime errors
PHP - Introduction to PHP Error Handling
Sending emails through PHP
Error handling
Php exceptions
Error reporting in php
Module-4_WTA_PHP Class & Error Handling
Php Error Handling
Handling error & exception in php
PHP - DataType,Variable,Constant,Operators,Array,Include and require
Preparing for the next PHP version (5.6)
PHP Basic
Errors, Exceptions & Logging (PHPNW13 Uncon)
Errors, Exceptions & Logging (PHP Hants Oct '13)
Php advance
Ad

More from Jalpesh Vasa (13)

PDF
5. HTML5
PDF
4.4 PHP Session
PDF
4.3 MySQL + PHP
PDF
4.1 PHP Arrays
PDF
4 Basic PHP
PDF
3.2.1 javascript regex example
PDF
3.2 javascript regex
PDF
3. Java Script
PDF
2 introduction css
PDF
1 web technologies
PDF
Remote Method Invocation in JAVA
PDF
Kotlin for android development
PDF
Security in php
5. HTML5
4.4 PHP Session
4.3 MySQL + PHP
4.1 PHP Arrays
4 Basic PHP
3.2.1 javascript regex example
3.2 javascript regex
3. Java Script
2 introduction css
1 web technologies
Remote Method Invocation in JAVA
Kotlin for android development
Security in php

Recently uploaded (20)

PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PPTX
Open Quiz Monsoon Mind Game Final Set.pptx
PDF
Pre independence Education in Inndia.pdf
PPTX
How to Manage Starshipit in Odoo 18 - Odoo Slides
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PPTX
Cell Structure & Organelles in detailed.
PDF
From loneliness to social connection charting
PPTX
Onica Farming 24rsclub profitable farm business
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
DOCX
UPPER GASTRO INTESTINAL DISORDER.docx
PDF
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
PPTX
Pharma ospi slides which help in ospi learning
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PPTX
COMPUTERS AS DATA ANALYSIS IN PRECLINICAL DEVELOPMENT.pptx
PDF
O7-L3 Supply Chain Operations - ICLT Program
PPTX
Revamp in MTO Odoo 18 Inventory - Odoo Slides
PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
Open Quiz Monsoon Mind Game Final Set.pptx
Pre independence Education in Inndia.pdf
How to Manage Starshipit in Odoo 18 - Odoo Slides
O5-L3 Freight Transport Ops (International) V1.pdf
Cell Structure & Organelles in detailed.
From loneliness to social connection charting
Onica Farming 24rsclub profitable farm business
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
UPPER GASTRO INTESTINAL DISORDER.docx
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
Pharma ospi slides which help in ospi learning
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
human mycosis Human fungal infections are called human mycosis..pptx
COMPUTERS AS DATA ANALYSIS IN PRECLINICAL DEVELOPMENT.pptx
O7-L3 Supply Chain Operations - ICLT Program
Revamp in MTO Odoo 18 Inventory - Odoo Slides
Renaissance Architecture: A Journey from Faith to Humanism
102 student loan defaulters named and shamed – Is someone you know on the list?

Object Oriented PHP - PART-2

  • 1. Object Oriented PHP By: Jalpesh Vasa
  • 2. Class unitcounter { var $units; var $weightperunit; function add($n=1) { $this->units = $this->units+$n; } function toatalweight() { return $this->units * $this->weightperunit; } function _ _construct($unitweight=1.0) { $this->weightperunit = $unitweight; $this->units=0; } } $brick = new unitcounter(1.2); $brick->add(3) $w1 = $brick->totalweight(); print “total weight of {$brick->units} bricks = $w1”;
  • 3. Cloning Objects • A variable assigned with an objects is actually a reference to the object. • Copying a object variable in PHP simply creates a second reference to the same object. • Example:
  • 4. $a = new unitcounter(); $a->add(5); $b=$a; $b->add(5); Echo “number of units={$a->units}”; Echo “number of units={$b->units}”; //prints number of units = 10
  • 5. • The _ _clone() method is available, if you want to create an independent copy of an object. $a = new unitcounter(); $a->add(5); $b=$a->_ _clone(); $b->add(5); Echo “number of units={$a->units}”; //prints 5 Echo “number of units={$b->units}”; //prints 10
  • 6. Inheritance • One of most powerful concept of OOP • Allows a new class to be defined by extending the capabilities of an existing base class or parent class.
  • 7. <?php Require “a1.php”; Class casecounter extends unitcounter { var $unitpercase; function addcase() { $this->add($this->unitpercase); } function casecount() { return ceil($this->units/$this->unitpercase); } function casecounter($casecapacity) { $this->unitpercase = $casecapacity; } } ?>
  • 8. $order = new casecounter(12); $order->add(7); $order->addcase(); Print $order->units; // prints 17 Print $order->casecount(); //prints 2
  • 9. Calling a parent class constructor <?php Require “a1.php”; Class casecounter extends unitcounter { var $unitpercase; function addcase() { $this->add($this->unitpercase); } function casecount() { return ceil($this->units/$this->unitpercase); } function casecounter($casecapacity, $unitweight) { parent::_ _construct($unitweight); $this->unitpercase = $casecapacity; } } ?>
  • 10. Function overriding Class shape { function info() { return “shape”; } } Class polygon extends shape { function info() { return “polygon”; } } $a = new shape(); $b = new polygon(); Print $a->info(); //prints shape Print $b->info(); //prints polygon
  • 11. Function overriding Class polygon extends shape { function info() { return parent::info().“.polygon”; } } $b = new polygon(); Print $b->info(); //prints shape.polygon
  • 12. Function overriding Class triangle extends polygon { function info() { return parent::info().“.triangle”; } } $t = new triangle(); Print $t->info(); //prints shape.polygon.triangle
  • 13. Protected member variables and functions • Member variables and functions can be defined using protected keyword. • Offers a compromise between being public and private. • It allows access to member variables and functions defined in a class from within descendant classes, but it prevents access from outside of the class hierarchy. • A child class can access a parent class’s protected function, but parent class protected function can’t be accessed from an unrelated class or from within a script that uses the class.
  • 14. Final functions • Descendant classes can be prevented from redefining member functions in base class by declaring them as final • Final keyword prevents accidental redefinition in a descendant class.
  • 15. Error Handling • Error handling is the process of catching errors raised by your program and then taking appropriate action. • The default error handling in PHP is very simple. • An error message with filename, line number and a message describing the error is sent to the browser. • We will show different error handling methods: – Simple "die()" statements – Custom errors and error triggers – Error reporting
  • 16. Using the die() function • While writing your PHP program you should check all possible error condition before going ahead and take appropriate action when required. <?php if(!file_exists("/tmp/test.txt")) { die("File not found"); } else { $file=fopen("/tmp/test.txt","r"); print "Opend file sucessfully"; } // Test of the code here. ?>
  • 17. Using the die() function • Now if the file does not exist you get an error like this: File not found • 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.
  • 18. Defining Custom Error Handling Function • You can write your own function to handling any error. PHP provides you a framework to define error handling function. • 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): • error_function(error_level,error_message, error_file,error_line,error_context);
  • 19. Defining Custom Error Handling Function Parameter Description error_level Required. Specifies the error report level for the user- defined error. Must be a value number. See table below for possible error report levels error_message Required. Specifies the error message for the user- defined error error_file Optional. Specifies the filename in which the error occurred error_line Optional. Specifies the line number in which the error occurred error_context Optional. Specifies an array containing every variable, and their values, in use when the error occurred
  • 20. Error Report levels Value Constant Description 2 E_WARNING Non-fatal run-time errors. Execution of the script is not halted 8 E_NOTICE Run-time notices. The script found something that might be an error, but could also happen when running a script normally 256 E_USER_ERROR Fatal user-generated error. This is like an E_ERROR set by the programmer using the PHP function trigger_error() 512 E_USER_WARNING Non-fatal user-generated warning. This is like an E_WARNING set by the programmer using the PHP function trigger_error() 1024 E_USER_NOTICE User-generated notice. This is like an E_NOTICE set by the programmer using the PHP function trigger_error() 4096 E_RECOVERABLE_ERROR Catchable fatal error. This is like an E_ERROR but can be caught by a user defined handle (see also set_error_handler()) 8191 E_ALL All errors and warnings (E_STRICT became a part of E_ALL in PHP 5.4)
  • 21. Defining Custom Error Handling Function • Now lets create a function to handle errors: function customError($errno, $errstr) { echo "<b>Error:</b> [$errno] $errstr<br>"; echo "Ending Script"; die(); } OR function handleError($errno, $errstr,$error_file,$error_line) { echo "<b>Error:</b> [$errno] $errstr - $error_file:$error_line"; echo "<br />"; echo "Terminating PHP Script"; die(); }
  • 22. Set Error Handler • 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. <?php //error handler function function customError($errno, $errstr) { echo "<b>Error:</b> [$errno] $errstr"; } //set error handler set_error_handler("customError"); //trigger error echo($test); ?> Error: [8] Undefined variable: test
  • 23. PHP Exception Handling • Exception handling is used to change the normal flow of the code execution if a specified error (exceptional) condition occurs. This condition is called an exception. • Exceptions give us much better handling of errors an allow us to customize the behavior of our scripts when an error (Exception) is encountered. • Exceptions are important and provides a better control over error handling.
  • 24. PHP Exception Handling • This is what normally happens 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
  • 25. PHP Exception Handling • Exceptions are actually objects and you have the option to 'catch' them and execute certain code. This is done by using 'try-catch' blocks: try { // some code goes here // which might throw an exception } catch (Exception $e) { // the code here only gets executed // if an exception happened in the try block above }
  • 26. PHP Exception Handling • Lets explain three new keyword related to exceptions. • 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.
  • 27. PHP Exception Handling • Let's say you want to calculate the area of a circle, by the given radius. This function will do that: function circle_area($radius) { return pi() * $radius * $radius; }
  • 28. PHP Exception Handling • It is very simple, however it does not check if the radius is a valid number. Now we are going to do that, and throw an exception if the radius is a negative number: function circle_area($radius) { // radius can't be negative if ($radius < 0) { throw new Exception('Invalid Radius: ' . $radius); } else { return pi() * $radius * $radius; } }
  • 29. PHP Exception Handling • Let's see what happens when we call it with a negative number: $radius = -2; echo "Circle Radius: $radius => Circle Area: ". circle_area($radius) . "n"; echo "Another line";
  • 30. PHP Exception Handling • The script crashes with the following message: <br /> <b>Fatal error</b>: Uncaught exception 'Exception' with message 'Invalid Radius: -2' in C:wampwwwtesttest.php:19 Stack trace: #0 C:wampwwwtesttest.php(7): circle_area(-2) #1 {main} thrown in <b>C:wampwwwtesttest.php</b> on line <b>19</b><br />
  • 31. PHP Exception Handling $radius_array = array(2,-2,5,-3); foreach ($radius_array as $radius) { try { echo "Circle Radius: $radius => Circle Area: ". circle_area($radius) . "n"; } catch (Exception $e) { echo 'Caught Exception: ', $e->getMessage(), "n"; } }
  • 32. PHP Exception Handling Now we get this output: Circle Radius: 2 => Circle Area: 12.566370614359 Caught Exception: Invalid Radius: -2 Circle Radius: 5 => Circle Area: 78.539816339745 Caught Exception: Invalid Radius: -3 There are no more errors, and the script continues to run. That is how you catch exceptions.
  • 33. PHP Exception Handling • When an exception is thrown from a function or a class method, it goes to whoever called that function or method. And it keeps on doing this until it reaches the top of the stack OR is caught. If it does reach the top of the stack and is never called, you will get a fatal error.
  • 34. PHP Exception Handling function bar() { throw new Exception('Message from bar().'); } function foo() { bar(); } try { foo(); } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), "n“;
  • 35. PHP Exception Handling • In the above example $e->getMessage function is used to get error message. There are following functions which can be used from Exception class. • getMessage()- message of exception • getCode() - code of exception • getFile() - source filename • getLine() - source line • getTrace() - n array of the backtrace() • getTraceAsString() - formated string of trace
  • 36. File upload in PHP • How to upload file on server? • How to limit size of file? • How to check /limit file type? • Where to store your file?
  • 37. File upload in PHP • First, ensure that PHP is configured to allow file uploads. • In your "php.ini" file, search for the file_uploads directive, and set it to On: • file_uploads = On
  • 38. File upload in PHP(html file) • <!DOCTYPE html> <html> <body> <form action="upload.php" method="post" enctype="multipart /form-data"> Select image to upload: <input type="file" name="fileToUpload" id="fileToUpload"> <input type="submit" value="Upload Image" name="submit"> </form> </body> </html>
  • 39. File upload in PHP(html file) <?php $target_dir = "uploads/"; $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]); $uploadOk = 1; $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION)); // Check if image file is a actual image or fake image if(isset($_POST["submit"])) { $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]); if($check !== false) { echo "File is an image - " . $check["mime"] . "."; $uploadOk = 1; } else { echo "File is not an image."; $uploadOk = 0; } } ?>
  • 40. File upload in PHP(html file) // Check if file already exists if (file_exists($target_file)) { echo "Sorry, file already exists."; $uploadOk = 0; } // Check file size if ($_FILES["fileToUpload"]["size"] > 500000) { echo "Sorry, your file is too large."; $uploadOk = 0; }
  • 41. File upload in PHP(html file) // Allow certain file formats if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) { echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed."; $uploadOk = 0; }
  • 42. File upload in PHP(html file) // Check if $uploadOk is set to 0 by an error if ($uploadOk == 0) { echo "Sorry, your file was not uploaded."; // if everything is ok, try to upload file } else { if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) { echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded."; } else { echo "Sorry, there was an error uploading your file."; } }