0% found this document useful (0 votes)
17 views

APHP NOTES

The document outlines the history and features of PHP, a server-side scripting language created by Rasmus Lerdorf in 1994. It covers PHP's syntax, variables, operators, control structures, arrays, and functions, emphasizing its open-source nature and compatibility with various platforms and databases. Additionally, it provides examples of basic PHP code and its functionalities.

Uploaded by

balujerry257
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

APHP NOTES

The document outlines the history and features of PHP, a server-side scripting language created by Rasmus Lerdorf in 1994. It covers PHP's syntax, variables, operators, control structures, arrays, and functions, emphasizing its open-source nature and compatibility with various platforms and databases. Additionally, it provides examples of basic PHP code and its functionalities.

Uploaded by

balujerry257
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 114

DISCOVERY OF PHP

 1994 - Written by Rasmus Lerdorf (PHP 1.0)


 1997 - Zeev Suraski and Andi Gutmans
 PHP 2
 ZEND company
 1998 - PHP 3
 ZEND engine
 2000 - PHP 4
 Version 4.4.7 - Oct. 2007
 2004 - PHP 5
PHP
 PHP stands for PHP: Hypertext Preprocessor
 PHP is a server-side scripting language, like
ASP
 PHP scripts are executed on the server
 PHP supports many databases (MySQL,
Informix, Oracle, Sybase, Solid,SQL Generic
ODBC, etc.)
 PHP is an open source software (OSS)
 PHP is free to download and use
WHY PHP?
 PHP runs on different platforms (Windows,
Linux, Unix, etc.)
 PHP is compatible with almost all servers used
today (Apache, IIS, etc.)
 PHP is FREE to download
 PHP is easy to learn and runs efficiently on the
server side
HOW TO SAVE & EXECUTE
 PHP files may contain text, HTML tags and
scripts
 PHP files are returned to the browser as plain
HTML
 PHP files have a file extension of ".php",
".php3", or ".phtml"
BASIC SYNTAX OF PHP
 A PHP scripting block always starts with <?
php and ends with ?>.
 A PHP scripting block can be placed anywhere
in the document.
 <?PHP
 ?>
 //This is a BASIC SYNTAX
 /*This is a multiline comment in php */
PHP VARIABLES
 Variables are used for storing a values, like
text strings, numbers or arrays.

 When a variable is set it can be used over and


over again in your script

 All variables in PHP start with a $ sign


symbol.
 A variable name must start with a letter or an
underscore "_"
 A variable name can only contain alpha-numeric
characters and underscores (a-Z, 0-9, and _ )
 A variable name should not contain spaces. If a
variable name is more than one word, it should be
separated with underscore ($my_string), or with
capitalization ($myString)
 VARIABLE DECLARATION
 $var_name = value;

 <?php
 $txt = "Hello World!";
 $number = 16;
 ?>
PHP Operators
 Assignment Operators
 Arithmetic Operators
 Comparison Operators
 String Operators
 Combination Arithmetic &
 Assignment Operators
Assignment Operators
Assignment operators are used to set a variable
equal to a value or set a variable to another
variable's value.

 $my_var = 4;
 $another_var = $my_var;
 Arithmetic Operators
Operator Meaning Example

+ Addition 2+4

- Subtraction 3-1

* Multiplication 5*2

Division 10/5
/

Modulus 23/10
%
Example
<?php
$add= 2 + 4;
$sub = 6 - 2; $multi = 5 * 3; $div = 15 / 3; $mod = 5 % 2;
echo " Addition: 2 + 4 = ".$add."<br />";
echo “ subtraction: 6 - 2 = ".$sub."<br />";
echo “multiplication: 5 * 3 = ".$multi."<br />";
echo “division: 15 / 3 = ".$div."<br />";
echo “ modulus: 5 % 2 = $mod;
?>
DISPLAY: Addition: 2 + 4 = 6
subtraction: 6 - 2 = 4
multiplication: 5 * 3 = 15
division: 15 / 3 = 5
modulus: 5 % 2 =1
Comparison Operators
Comparisons are used to check the relationship
between variables and/or values.
Example: $x = 4 and $y = 5;
Operator Meaning Example Result

== Equal To $x == $y False

!= Not Equal to $x != $y True

< Less than $x < $y True

> Greater than $x >$y False

<= Less than or Equal $x <= $y True


to
>= Greater than or $x >= $y False
Equal to
pre/post-increment & pre/post-decrement
operator

 $x++; Which is equivalent to $x += 1; or


$x = $x + 1;

 $x--; Which is equivalent to $x -= 1; or


$x = $x - 1;
Strings in PHP

 A string variable is used to store and


manipulate a piece of text
 String variables are used for values that
contains character strings.
 <?php
 $txt="Hello World";
 echo $txt;
 ?>
String functions
 chunk_split()  substr()
 strlen()
 Strpos()
 Ltrim()
 str_shuffle()
 Str_split()
 str_replace()
 strrev()
 join()
 Strstr()
 chr()
Chunk split()
 The chunk_split() function splits a string into a
series of smaller parts.
 <?php
$str = “Dream world!";
echo chunk_split($str,1,".");
?>
 Display : D.r.e.a.m. . W.o.r.l.d.!.
Strlen()
<?php
$str=“Dream world!”;
echo strlen(“Dream world!").”<br>”;
Echo strpos($str,”e”);
?>
Display : 12
2
Ltrim()
 <?php
$str = " Charmy World!";
echo "Without ltrim: " . $str;
echo "<br />";
echo "With ltrim: " . ltrim($str);
?>
 Display :Without ltrim: Charmy World!
With ltrim: Charmy World!
str_shuffle()
<?php
echo str_shuffle("Hello World");
?>
Display: Hlelo orwld
Str_split()
<?php
print_r(str_split(“Hii"));
?>
Display :Array
(
[0] => H
[1] => i
[2] => i )
Str_replace()
 <?php
 $str=“Hello world!”;
echo str_replace("world",“dreamy“,$str);
?>

 Display : Hello Dreamy!


strrev()
 <?php
echo strrev(“Teddy Bear!");
?>
 Display : !raeb yddeT
 Join()
 <?php
$arr = array('Hello',‘India!',‘nice',‘country!');
echo join(" ",$arr);
?>
 DISPLAY : Hello India! Nice country!
Strstr()
 <?php
echo strstr("Hello world!","world");
?>
 DISPLAY : world!
 Stristr()
 This function is incase-sensitive.
 It helps to search some words in given string.
chr()
The chr() function returns a character from the
specified ASCII value.
<?php
echo chr(52)."<br />";
?>
DISPLAY : 4
Substr()
<?php
echo substr(“dream world!",6);
?>
DISPLAY :world!
Strtolower() and strtoupper()
 <?php
 $str=“Hello WORLD.”;
 $str1=“dreamy india”;
echo strtolower($str);
 Echo strtoupper($str1)
 Echo ucwords($str1)
?>
 Display :hello world
 DREAMY INDIA
 Dreamy India
Concatenation Operator
 There is only one string operator in PHP.
 The concatenation operator (.) is used to put
two string values together.
 <?php
 $txt1="Hello World";
 $txt2="1234";
 echo $txt1 . " " . $txt2;
 ?>
 Combination of Arithmetic/Assignment
operator
Equivalent
Operators Meaning Example
Operation

+= Plus Equals $x += 2; $x = $x + 2;

-= Minus Equals $x -= 4; $x = $x - 4;

*= Multiply Equals $x *= 3; $x = $x * 3;

/= Divide Equals $x /= 2; $x = $x / 2;

%= Modulo Equals $x %= 5; $x = $x % 5;

Concatenate $my_str =
.= $str.="hello";
Equals $my_str . "hiii";
Constants
 A constant is a identifier for a simple value.
 Constants also follows the rules of naming
variables.
 <?php
 Define(“constant_var”, “value”);
 ?>
Constant Rules
 Constant do not have $ sign.
 It may only be defined using define() function.
 It can not be redefined or undefined once they
have been set.
 Constants may only evaluate to scalar values.
Example
<?php
define("MAXSIZE", 100);
echo "Declared Value:".MAXSIZE."<br>";
echo "Retrieve Constant
Value:".constant("MAXSIZE"); // same thing
as the previous line
?>
Display : Declared Value:100
Retrieve Constant Value:100
Expressions
 Expressions are the most important building
stone in PHP.
 The most basic forms of expressions are
Constant & Variables.
 The common expressions are COMPARISION
operator.
 This will give you either TRUE or FALSE
value.
 PHP supports >,<,<=,>=,==,!=,===,!==

, these are some mostly used


comparison operator to execute conditional
operators.
Control structures
 If Else
 Switch case
 For loop
 While loop
 Do .. While loop
Examples
IF..ELSE
<?php
$d=“tue”;
if ($d=="Tue")
echo "Have a nice weekend!";
else if ($d=="Sun")
echo "Have a nice Sunday!";
else
echo "Have a nice day!";
?>
 DISPLAY : Have a nice day!
Switch case
<?php
$x=2;
switch ($x)
{
case 1:
echo "Number 1"; break;
case 2:
echo "Number 2"; break;
case 3:
echo "Number 3"; break;
default:
echo "No number between 1 and 3";
}
?>
DISPLAY : Number 2
 FOR LOOP
 <?php
 For ($i=0;$i<=5;$i++)
 {
 Echo $i.”<br>”;
 }
 ?>
 DISPLAY:012345
 While
 <?php
 $a=1;
 While ($a<=5)
 {
 Echo $a;
 $a++;
 }
 ?>
 DISPLAY :12345
 DO…WHILE
 <?php
 $a=3;
 Do{
 Echo $a;
 $a++;
 }
 while ($a>0)
 ?>
PHP Arrays

 An array can store one or more values in a


single variable name.
 There are three different kind of arrays :
 Numeric array - An array with a numeric ID
key
 Associative array - An array where each ID
key is associated with a value
 Multidimensional array - An array
containing one or more arrays
NUMERIC ARRAY
 A numeric array stores each element with a
numeric ID key
 $names = array("Peter","Quagmire","Joe");
 $names[0] = "Peter";$names[1] = "Quagmire";
$names[2] = "Joe";
 <?php $names[0] = "Peter";$names[1] =
"Quagmire";$names[2] = "Joe";echo
$names[1] . " and " . $names[2] . " are ".
$names[0] . "'s neighbors";?>
ASSOCIATIVE ARRAY
 An associative array, each ID key is associated
with a value.
 $ages = array("Peter"=>32, "Quagmire"=>30,
"Joe"=>34);
 $ages['Peter'] = "32";$ages['Quagmire'] =
"30";$ages['Joe'] = "34";
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.
 $families = array( "Griffin"=>array
( "Peter", "Lois", "Megan" ),
"Quagmire"=>array ( "Glenn" ),
"Brown"=>array ( "Cleveland", "Loretta",
"Junior" ));
 Array([Griffin] => Array ( [0] => Peter [1]
=> Lois [2] => Megan )[Quagmire] => Array
( [0] => Glenn )[Brown] => Array ( [0] =>
Cleveland [1] => Loretta [2] => Junior ))
 echo "Is " . $families['Griffin'][2] . " a part of
the Griffin family?";
FOREACH STATEMENT
 The foreach statement is used to loop through
arrays.
 For every loop, the value of the current array
element is assigned to $value (and the array
pointer is moved by one) - so on the next loop,
you'll be looking at the next element.
 SYNTAX
 foreach (array as value)
 { code to be executed;}
 EXAMPLE:
 <?php
 $arr=array("one", "two", "three");
 foreach ($arr as $value)
 {
 echo "Value: " . $value . "<br />";}
 ?>
FUNCTIONS
 The real power of PHP comes from its
functions.
 In PHP - there are more than 700 built-in
functions available.
 A function is a block of code that can be
executed whenever we need it.
 Creating PHP functions:
 All functions start with the word "function()"
 Name the function - It should be possible to
understand what the function does by its name.
The name can start with a letter or underscore
(not a number)
 Add "{" - The function code starts after the
opening curly brace
 Insert the function code
 Add "}" - The function is finished by a
closing curly brace
 <?php
 function writeMyName()
 { echo "Kai Jim Refsnes"; }
 echo "Hello world!<br />";
 echo "My name is ";
 writeMyName();
 echo ".<br />That's right, ";
 writeMyName();
 echo " is my name.";?>
FUNCTION WITH PARAMETERS
 Our first function (writeMyName()) is a very
simple function. It only writes a static string.
 To add more functionality to a function, we
can add parameters. A parameter is just like a
variable.
 <?php
 function writeMyName($fname)
 { echo $fname; }
 echo "My name is ";
 writeMyName("Kai Jim");
 echo "My name is ";writeMyName("Hege");
 echo "My name is ";
 writeMyName("Stale");?>
 <?php
 function writeMyName($fname,$punctuation)
{ echo $fname . " Refsnes" . $punctuation ; }
 echo "My name is ";
 writeMyName("Kai Jim","..!!!!");
 echo "My name is ";
 writeMyName("Ståle","...");
 ?>
FORMS & USER INPUTS
 The PHP $_GET and $_POST variables are
used to retrieve information from forms, like
user input.
 The most important thing to notice when
dealing with HTML forms and PHP is that any
form element in an HTML page will
automatically be available to your PHP
scripts.
 <html>
 <body>
 <form action="welcome.php" method="post">
 Name: <input type="text" name="name" />
 Age: <input type="text" name="age" />
 <input type="submit" />
 </form>
 </body>
 </html>
 <html>
 <body>
 Welcome
 <?php echo $_POST["name"]; ?>,
 <br />
 You are
 <?php echo $_POST["age"]; ?>
 years old.
 </body>
 </html>
$_GET METHOD
 The $_GET variable is an array of variable
names and values sent by the HTTP GET
method.
 Information sent from a form with the GET
method is visible to everyone (it will be
displayed in the browser's address bar) and it
has limits on the amount of information to
send (max. 100 characters).
$_POST METHOD
 The $_POST variable is an array of variable
names and values sent by the HTTP POST
method.
 Information sent from a form with the POST
method is invisible to others and has no limits
on the amount of information to send.
REQUEST
 The PHP $_REQUEST variable contains the
contents of both $_GET, $_POST, and
$_COOKIE.
 The PHP $_REQUEST variable can be used to
get the result from form data sent with both the
GET and POST methods.
 <?
 php echo $_REQUEST["name"];
 ?>
INCLUDE FUNCTION
 The include() function takes all the text in a
specified file and copies it into the file that
uses the include function.
 EXAMPLE:
 <?php
 include("header.php");
 Echo “welcome you all”;
 ?>
REQUIRE FUNCTION
 The require() function is identical to include().
 The include() function generates a warning (but the
script will continue execution) while
 The require() function generates a fatal error (and the
script execution will stop after the error).
 <?php
 require("header.php");
 Echo “welcome you all”;
 ?>
FILE HANDLING
 The fopen() function is used to open files in
PHP.
 The first parameter of this function contains
the name of the file to be opened and the
second parameter specifies in which mode the
file should be opened:
 <?php
 $file=fopen("welcome.txt","r");
 ?>
Modes Description

r Read only. Starts at the beginning of the file

r+ Read/Write. Starts at the beginning of the file

w Write only. Opens and clears the contents of file; or creates a new file if it doesn't exist

w+ Read/Write. Opens and clears the contents of file; or creates a new file if it doesn't exist

a Append. Opens and writes to the end of the file or creates a new file if it doesn't exist

a+ Read/Append. Preserves file content by writing to the end of the file

x Write only. Creates a new file. Returns FALSE and an error if file already exists

x+ Read/Write. Creates a new file. Returns FALSE and an error if file already exists
fread() function
 This function is used to read the content in the
opened file
 fread(‘opened file name’,size);
 Ex:
 Fread($file,100);
 Find the full document size
 $size=Sizeof($filename);
 Fread($file,$size);
fwrite()
 This function is used to write the content in the
opened document.
 fwrite(‘openened file name’,content);
 Ex
 fwrite($file,‘cegonsoft’);
CLOSING A FILE
 The fclose() function is used to close an open
file:
 <?php
 $file = fopen("test.txt","r");
 //some code to be executed
 fclose($file);
 ?>
CHECK END-OF-FILE
 The feof() function checks if the "end-of-file"
(EOF) has been reached.
 The feof() function is useful for looping
through data of unknown length.
 Note: You cannot read from files opened in w,
a, and x mode!
 EXAMPLE:
 if (feof($file)) echo "End of file";
READING FILE LINE BY LINE
 The fgets() function is used to read a single
line from a file.
 <?php
 $file = fopen("welcome.txt", "r") or
exit("Unable to open file!");
 //Output a line of the file until the end is
reached
 while(!feof($file))
 { echo fgets($file). "<br />"; }
 fclose($file);?>
READING FILE BY CHARACTER
 The fgetc() function is used to read a single
character from a file.
 <?php
 $file=fopen("welcome.txt","r") or
exit("Unable to open file!");
 while (!feof($file))
 { echo fgetc($file); }
 fclose($file);?>
COOKIES
 A cookie is often used to identify a user.
 A cookie is a small file that the server embeds
on the user's computer.
 Each time the same computer requests a page
with a browser, it will send the cookie too.
 With PHP, you can both create and retrieve
cookie values.
CREATE COOKIE
 The setcookie() function is used to set a
cookie.
 setcookie(name, value, expire, path, domain);
 EXAMPLE:
 <?php setcookie(“cookie_name",
“cookie_value", time()+3600);?>
 The value of the cookie is automatically
URLencoded when sending the cookie, and
automatically decoded when received
RETRIVE COOKIE
 The PHP $_COOKIE variable is used to
retrieve a cookie value.
 <?php
// Print a cookie
echo $_COOKIE["user"];
 // A way to view all cookies
print_r($_COOKIE);
 ?>
DELETE COOKIE
 When deleting a cookie you should assure that
the expiration date is in the past.
 <?php
 // set the expiration date to one hour ago
setcookie("user", "", time()-3600);
 ?>
SESSIONS
 Before you can store user information in your
PHP session, you must first start up the
session.
 <?
 php session_start();
 ?>
 The code above will register the user's session
with the server, allow you to start saving user
information, and assign a UID for that user's
session.
STORE & RETRIVE
 <?php
 session_start();
 // store session data
 $_SESSION['views']=1;
 ?><html><body>
 <?php
 //retrieve session data
 echo "Pageviews=". $_SESSION['views'];
 ?></body></html>
 The isset() function checks if the "views" variable has
already been set. If "views" has been set, we can
increment our counter. If "views" doesn't exist, we
create a "views" variable, and set it to 1:
 <?php
session_start();
 if(isset($_SESSION['views']))
$_SESSION['views']=$_SESSION['views']+1;
else
$_SESSION['views']=1;
echo "Views=". $_SESSION['views'];
?>
DESTROY SESSION
 If you wish to delete some session data, you
can use the unset() or the session_destroy()
function.
 The unset() function is used to free the
specified session variable:
 <?php
unset($_SESSION['views']);?>
 <?php
session_destroy();?>
DATE FUNCTIONS
 The PHP date() function is used to format a
time or a date.
 SYNTAX:
 date(format,timestamp);
 Format:Required. Specifies the format of the
timestamp
 Timestamp: It is the number of seconds since
January 1, 1970 at 00:00:00 GMT. This is also
known as the Unix Timestamp.
 The first parameter in the date() function
specifies how to format the date/time.
 d - The day of the month (01-31)
 m - The current month, as a number (01-12)
 Y - The current year in four digits
 <?php
 echo date("Y/m/d");echo "<br />";
 echo date("Y.m.d");echo "<br />";
 echo date("Y-m-d");?>
 The mktime() function returns the Unix
timestamp for a specified date.
 SYNTAX:
 mktime(hour,minute,second,month,day,year)
 EXAMPLE:
 <?php
 $tomorrow =
mktime(0,0,0,date("m"),date("d")
+1,date("Y"));
echo "Tomorrow is ".date("Y/m/d/",
$tomorrow);?>
FILE UPLOADING
 With PHP, it is possible to upload files to the
server.
 <form action="uploadfile.php" method="post“
enctype="multipart/form-data">
 <label for="file">Filename:</label>
 OR Filename: <input type="file">
 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 input field

 Note: Allowing users to upload files is a big security


risk. Only permit trusted users to perform file uploads.
 <?php
 if ($_FILES["file"]["error"] > 0)
 { echo "Error: " . $_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 "Stored in: " . $_FILES["file"]
["tmp_name"]; }?>
 $_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
RESTRICTIONS ON UPLOAD
 <?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 "Error: " .
$_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 "Stored in: " . $_FILES["file"]["tmp_name"]; }
}else { echo "Invalid file"; }?>
SENDING E-MAILS
 The PHP mail() function is used to send emails from
inside a script.
 SYNTAX:
 Mail (to,subject,message,headers,parameters)
 To :Specifies the receiver / receivers of the email
 Subject: Specifies the subject of the email.
 Message: Defines the message to be sent. Lines
should not exceed 70 characters
 Headers: Optional. Specifies additional headers, like
From, Cc, and Bcc.
 Parameters: Optional. Specifies an additional
parameter to the send mail program
 NOTE: For the mail functions to be available, PHP
requires an installed and working email system.
 <?php
 $to = "[email protected]";
 $subject = "Test mail";
 $message = "Hello! This is a simple email message.";
 $from = "[email protected]";
 $headers = "From: $from";
 Mail ($to,$subject,$message,$headers);
 echo "Mail Sent.";?>
ERROR HANDLING
 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.
 Some of the most common error checking
methods in PHP.
 Simple "die()" statements
 Custom errors and error triggers
 Error reporting
Die( ) FUNCTION
 <?php$file=fopen("welcome.txt","r");?>
 Warning: fopen(welcome.txt)
[function.fopen]: failed to open stream: No
such file or directory in C:\webfolder\
test.php on line 2
 <?php
 if(!file_exists("welcome.txt"))
 { die("File not found"); }
 else { $file=fopen("welcome.txt","r"); }?>
CUSTOM ERROR HANDLER
 Creating a custom error handler is quite
simple. We simply create a special function
that can be called when an error occurs in
PHP.
 SYNTAX:
 error_function(error_level,error_message,e
rror_file,error_line,error_context)
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, except level E_STRICT
(E_STRICT will be part of E_ALL as of PHP 6.0)
 function customError($errno, $errstr)
 { echo "<b>Error:</b> [$errno] $errstr<br
/>"; 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.
 we have created an error handling function we
need to decide when it should be triggered.
SET ERROR HANDLER
 The default error handler for PHP is the built
in error handler.
 <?php
 function customError($errno, $errstr)
 { echo "<b>Error:</b> [$errno] $errstr"; }
set_error_handler("customError");
echo($test);?>
 Custom error: [8] Undefined variable: test
ERROR TRIGGER
 The 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.
 <?php
 $test=2;
 if ($test>1)
 {
 trigger_error("Value must be 1 or below");}?>
 Notice: Value must be 1 or belowin C:\webfolder\
test.php on line 6
 An error can be triggered anywhere you wish
in a script, and by adding a second parameter,
you can specify what error level is triggered.
 POSSIBLE ERROR TYPES:
 E_USER_ERROR
 E_USER_WARNING
 E_USER_NOTICE
 Output for following user trigger program.
 Error: [512] Value must be 1 or below
 Ending Script
 <?php
 function customError($errno, $errstr)
 { echo "<b>Error:</b> [$errno] $errstr";
 echo "Ending Script"; die(); }
 set_error_handler("customError",E_USER_W
ARNING);
 $test=2;
 if ($test>1)
 { trigger_error("Value must be 1 or
below",E_USER_WARNING); }?>
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.
 Note: Exceptions should only be used with
error conditions, and should not be used to
jump to another place in the code at a specified
point.
ERROR HANDLING METHODS
 Basic use of Exceptions
 Creating a custom exception handler
 Multiple exceptions
 Re-throwing an exception
 Setting a top level exception handler
TRY,THROW & CATCH
 TRY - A function using an exception should be in a
"try" block. If the exception does not trigger, the
code will continue as normal.
 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
 function checkNum($number)
{ if($number>1) { throw new
Exception("Value must be 1 or below"); }
return true; }
 try { checkNum(2);
 echo 'If you see this, the number is 1 or
below'; }
 catch(Exception $e) { echo 'Message: ' .$e-
>getMessage(); }?>
BASIC USE OF EXCEPTION
 When an exception is thrown, the code
following it will not be executed, and PHP will
try to find the matching "catch" block.
 If an exception is not caught, a fatal error will
be issued with an "Uncaught Exception"
message.
 <?php
 function checkNum($number)
 { if($number>1)
 { throw new Exception("Value must be 1 or
below"); } return true; }
 checkNum(2);?>
 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
CUSTOM EXCEPTION CLASS
 We simply create a special class with
functions that can be called when an exception
occurs in PHP.
 The class must be an extension of the
exception class.
 The custom exception class inherits the
properties from PHP's exception class and you
can add custom functions to it.
MULTIPLE EXCEPTION
 It is possible to use several if..else blocks, a
switch, or nest multiple exceptions.

 These exceptions can use different exception


classes and return different error messages:
RE-THROW EXCEPTION
 Sometimes, when an exception is thrown, you
may wish to handle it differently than the
standard way. It is possible to throw an
exception a second time within a "catch"
block.
 System errors may be important for the coder.
But it is complicated sometimes.
 To make things easier for the user you can re-
throw the exception with a user friendly
message:
TOP LEVEL EXCEPTION
 The set_exception_handler() function sets a user-
defined function to handle all uncaught exceptions.
 <?php
 function myException($exception)
 {echo "<b>Exception:</b> " , $exception-
>getMessage();}
 set_exception_handler('myException');
 throw new Exception('Uncaught Exception
occurred');
 ?>
RULES FOR EXCEPTION
 Code may be surrounded in a try block, to help
catch potential exceptions
 Each try block or "throw" must have at least
one corresponding catch block
 Multiple catch blocks can be used to catch
different classes of exceptions
 Exceptions can be thrown (or re-thrown) in a
catch block within a try block
FILTERS
 PHP filters is used to validate and filter data
coming from insecure sources, like user input.
 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.
FUNCTIONS IN FILTERS
 To filter a variable, use one of the following
filter functions:
 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
VALIDATING & SANITIZING
 There are two kinds of filters:
 Validating filters:
 Are used to validate user input
 Strict format rules (like URL or E-Mail validating)
 Returns the expected type on success or FALSE on
failure
 Sanitizing filters:
 Are used to allow or disallow specified characters in
a string
 No data format rules
 Always return the string
VALIDATE
 Filter the input data using the filter_input()
function.
 <?php
 if(!filter_has_var(INPUT_GET, "email"))
 { echo("Input type does not exist"); }
 else { if (!filter_input(INPUT_GET, "email",
FILTER_VALIDATE_EMAIL))
 { echo "E-Mail is not valid"; }
 else { echo "E-Mail is valid"; } }?>
SANITIZE
 To sanitize the input data using the
filter_input() function.
 <?php
 if(!filter_has_var(INPUT_POST, "url"))
 { echo("Input type does not exist"); }
 else { $url = filter_input(INPUT_POST, "url",
FILTER_SANITIZE_URL); }?>
MULTIPLE FILTERS
 A form almost always consist of more than
one input field.
 To avoid calling the filter_var or filter_input
functions over and over.
 we can use the filter_var_array or the
filter_input_array functions.
FILTER CALLBACK
 It is possible to call a user defined function
and use it as a filter using the
FILTER_CALLBACK filter. This way, we
have full control of the data filtering.
 You can create your own user defined function
or use an existing PHP function
 The function you wish to use to filter is
specified the same way as an option is
specified. In an associative array with the
name "options"
THANK YOU………

You might also like