0% found this document useful (0 votes)
53 views22 pages

Web Design Programming Chapter 5

This document discusses handling PHP forms. It explains that the PHP superglobals $_GET and $_POST collect form data and can be used to echo the submitted values. A simple HTML form is provided as an example that submits to a PHP file using the POST method. Both GET and POST methods are discussed, noting that GET values are visible in the URL while POST values are embedded in the request. Validation of form data is emphasized for security. The document also covers opening files in PHP using fopen() and specifying the file mode.

Uploaded by

Hiziki Tare
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
53 views22 pages

Web Design Programming Chapter 5

This document discusses handling PHP forms. It explains that the PHP superglobals $_GET and $_POST collect form data and can be used to echo the submitted values. A simple HTML form is provided as an example that submits to a PHP file using the POST method. Both GET and POST methods are discussed, noting that GET values are visible in the URL while POST values are embedded in the request. Validation of form data is emphasized for security. The document also covers opening files in PHP using fopen() and specifying the file mode.

Uploaded by

Hiziki Tare
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 22

WEB DESIGN PROGRAMMING : CHAPTER 5

(PHP: Web Design) ----JITENDRA SINGH

To display the submitted data you


PHP  Form could simply echo all the variables.
The "welcome.php" looks like this:

Handling <html>
<body>

The PHP superglobals $_GET and Welcome <?php echo


$_POST are used to collect form- $_POST["name"]; ?><br>
data. Your email address is: <?php echo
$_POST["email"]; ?>

PHP - A Simple HTML </body>

Form </html>

The output could be something like


The example below displays a simple this:
HTML form with two input fields and
a submit button: Welcome John
Your email address is
Example john.doe@example.com

<html> The same result could also be


<body> achieved using the HTTP GET
method:
<form action="welcome.php" method="
post"> Example
Name: <input type="text" name="name
"><br> <html>
E-mail: <input type="text" name="em <body>
ail"><br>
<input type="submit"> <form action="welcome_get.php" meth
</form> od="get">
Name: <input type="text" name="name
</body> "><br>
</html> E-mail: <input type="text" name="em
ail"><br>
Run example » <input type="submit">
</form>
When the user fills out the form
above and clicks the submit button, </body>
the form data is sent for processing
</html>
to a PHP file named "welcome.php".
The form data is sent with the HTTP Run example »
POST method.
WEB DESIGN PROGRAMMING : CHAPTER 5
(PHP: Web Design) ----JITENDRA SINGH

and "welcome_get.php" looks like Both GET and POST are treated as
this: $_GET and $_POST. These are
superglobals, which means that they
<html> are always accessible, regardless of
<body> scope - and you can access them
from any function, class or file
Welcome <?php echo $_GET["name"]; ? without having to do anything
><br> special.
Your email address is: <?php echo
$_GET["email"]; ?> $_GET is an array of variables
passed to the current script via the
</body> URL parameters.
</html>
$_POST is an array of variables
passed to the current script via the
The code above is quite simple.
HTTP POST method.
However, the most important thing
is missing. You need to validate form
data to protect your script from
malicious code.
When to use GET?
Information sent from a form with
Think SECURITY when
the GET method is visible to
processing PHP forms!
everyone (all variable names and
values are displayed in the URL).
This page does not contain any form
GET also has limits on the amount of
validation, it just shows how you can
information to send. The limitation is
send and retrieve form data.
about 2000 characters. However,
because the variables are displayed
However, the next pages will show
in the URL, it is possible to
how to process PHP forms with
bookmark the page. This can be
security in mind! Proper validation of
useful in some cases.
form data is important to protect
your form from hackers and
GET may be used for sending non-
spammers!
sensitive data.

Note: GET should NEVER be used


for sending passwords or other

GET vs. POST sensitive information!

Both GET and POST create an array


(e.g. array( key => value, key2 =>
value2, key3 => value3, ...)). This When to use POST?
array holds key/value pairs, where
keys are the names of the form
Information sent from a form with
controls and values are the input
the POST method is invisible to
data from the user.
others (all names/values are
embedded within the body of the
WEB DESIGN PROGRAMMING : CHAPTER 5
(PHP: Web Design) ----JITENDRA SINGH

HTTP request) and has no limits on


the amount of information to send. PHP Open File -
Moreover POST supports advanced fopen()
functionality such as support for
multi-part binary input while A better method to open files is with
uploading files to server. the fopen() function. This function
gives you more options than the
However, because the variables are readfile() function.
not displayed in the URL, it is not
possible to bookmark the page. We will use the text file,
"webdictionary.txt", during the
Developers prefer POST for lessons:
sending form data.
AJAX = Asynchronous JavaScript and

PHP Validate E-
XML
CSS = Cascading Style Sheets
HTML = Hyper Text Markup Language

mail PHP = PHP Hypertext Preprocessor


SQL = Structured Query Language
SVG = Scalable Vector Graphics
The easiest and safest way to check XML = EXtensible Markup Language
whether an email address is well-
formed is to use PHP's filter_var() The first parameter of fopen()
function. contains the name of the file to be
opened and the second parameter
In the code below, if the e-mail specifies in which mode the file
address is not well-formed, then should be opened. The following
store an error message: example also generates a message if
the fopen() function is unable to
$email = open the specified file:
test_input($_POST["email"]);
if (!filter_var($email,
FILTER_VALIDATE_EMAIL)) {
Example
  $emailErr = "Invalid email <?php
format";  $myfile =
} fopen("webdictionary.txt", "r") or 
die("Unable to open file!");
echo fread($myfile,filesize("webdic
tionary.txt"));
fclose($myfile);

PHP- FILE
?>

Tip: The fread() and the fclose()

HANDLING functions will be explained below.


WEB DESIGN PROGRAMMING : CHAPTER 5
(PHP: Web Design) ----JITENDRA SINGH

The file may be opened in one of the


following modes:
read/write. File pointer
starts at the beginning of
the file
Mode Description
s

w+ Open a file for


read/write. Erases the
r Open a file for read contents of the file or
only. File pointer starts creates a new file if it
at the beginning of the doesn't exist. File pointer
file starts at the beginning of
the file

w Open a file for write


only. Erases the a+ Open a file for
contents of the file or read/write. The existing
creates a new file if it data in file is preserved.
doesn't exist. File pointer File pointer starts at the
starts at the beginning of end of the file. Creates a
the file new file if the file doesn't
exist

a Open a file for write


only. The existing data x+ Creates a new file for
in file is preserved. File read/write. Returns
pointer starts at the end FALSE and an error if file
of the file. Creates a new already exists
file if the file doesn't
exist

x Creates a new file for


write only. Returns PHP Read File -
FALSE and an error if file
already exists fread()
The fread() function reads from an
open file.
r+ Open a file for
WEB DESIGN PROGRAMMING : CHAPTER 5
(PHP: Web Design) ----JITENDRA SINGH

The first parameter of fread() The fgets() function is used to read a


contains the name of the file to read single line from a file.
from and the second parameter
specifies the maximum number of The example below outputs the first
bytes to read. line of the "webdictionary.txt" file:

The following PHP code reads the


"webdictionary.txt" file to the end:
Example
<?php
fread($myfile,filesize("webdictiona
$myfile =
ry.txt"));
fopen("webdictionary.txt", "r") or 
die("Unable to open file!");
echo fgets($myfile);
fclose($myfile);

PHP Close File - ?>

fclose() Note: After a call to the fgets()


function, the file pointer has moved
to the next line.
The fclose() function is used to close
an open file.

It's a good programming practice to


close all files after you have finished
with them. You don't want an open
PHP Check End-Of-
file running around on your server
taking up resources!
File - feof()
The fclose() requires the name of The feof() function checks if the
the file (or a variable that holds the "end-of-file" (EOF) has been
filename) we want to close: reached.

<?php The feof() function is useful for


$myfile = looping through data of unknown
fopen("webdictionary.txt", "r"); length.
// some code to be executed....
fclose($myfile); The example below reads the
?> "webdictionary.txt" file line by line,
until end-of-file is reached:

Example
PHP Read Single Line <?php
$myfile =
- fgets() fopen("webdictionary.txt", "r") or 
die("Unable to open file!");
// Output one line until end-of-
WEB DESIGN PROGRAMMING : CHAPTER 5
(PHP: Web Design) ----JITENDRA SINGH

file The fopen() function is also used to


while(!feof($myfile)) { create a file. Maybe a little
  echo fgets($myfile) . "<br>"; confusing, but in PHP, a file is
} created using the same function
fclose($myfile); used to open files.
?>
If you use fopen() on a file that does
not exist, it will create it, given that
the file is opened for writing (w) or
appending (a).
PHP Read Single The example below creates a new

Character - fgetc() file called "testfile.txt". The file will


be created in the same directory
where the PHP code resides:
The fgetc() function is used to read a
single character from a file.
Example
The example below reads the $myfile = fopen("testfile.txt",
"webdictionary.txt" file character by
"w")
character, until end-of-file is
reached:

Example
<?php
$myfile =
fopen("webdictionary.txt", "r") or 
PHP File Permissions
die("Unable to open file!");
If you are having errors when trying
// Output one character until end- to get this code to run, check that
of-file you have granted your PHP file
while(!feof($myfile)) { access to write information to the
  echo fgetc($myfile); hard drive.
}
fclose($myfile);
?>

Note: After a call to the fgetc()


function, the file pointer moves to
PHP Write to File -
the next character. fwrite()
PHP Create File - The fwrite() function is used to write
to a file.
fopen() The first parameter of fwrite()
contains the name of the file to write
WEB DESIGN PROGRAMMING : CHAPTER 5
(PHP: Web Design) ----JITENDRA SINGH

to and the second parameter is the In the example below we open our
string to be written. existing file "newfile.txt", and write
some new data into it:
The example below writes a couple
of names into a new file called
"newfile.txt":
Example
<?php
Example $myfile =
fopen("newfile.txt", "w") or die("U
<?php nable to open file!");
$myfile = $txt = "Mickey Mouse\n";
fopen("newfile.txt", "w") or die("U fwrite($myfile, $txt);
nable to open file!"); $txt = "Minnie Mouse\n";
$txt = "John Doe\n"; fwrite($myfile, $txt);
fwrite($myfile, $txt); fclose($myfile);
$txt = "Jane Doe\n"; ?>
fwrite($myfile, $txt);
fclose($myfile); If we now open the "newfile.txt" file,
?> both John and Jane have vanished,
and only the data we just wrote is
present:

Notice that we wrote to the file Mickey Mouse


"newfile.txt" twice. Each time we Minnie Mouse
wrote to the file we sent the string

PHP  File Upload


$txt that first contained "John Doe"
and second contained "Jane Doe".
After we finished writing, we closed
the file using the fclose() function.
With PHP, it is easy to upload files
If we open the "newfile.txt" file it to the server.
would look like this:
However, with ease comes danger,
John Doe so always be careful when allowing
Jane Doe file uploads!

PHP Overwriting
Now that "newfile.txt" contains some Configure The
"php.ini" File
data we can show what happens
when we open an existing file for
writing. All the existing data will be
ERASED and we start with an empty First, ensure that PHP is configured
file. to allow file uploads.
WEB DESIGN PROGRAMMING : CHAPTER 5
(PHP: Web Design) ----JITENDRA SINGH

In your "php.ini" file, search for the Other things to notice:


file_uploads directive, and set it to
On:  The type="file" attribute of the
<input> tag shows the input
file_uploads = On field as a file-select control,
with a "Browse" button next to
the input control

The form above sends data to a file


Create The HTML called "upload.php", which we will
create next.
Form
Next, create an HTML form that
allow users to choose the image file
they want to upload: Create The Upload
<!DOCTYPE html> File PHP Script
<html>
<body> The "upload.php" file contains the
code for uploading a file:
<form action="upload.php" method
="post" enctype="multipart/form- <?php
data"> $target_dir = "uploads/";
    Select image to upload: $target_file = $target_dir .
    <input type="file" name="fil basename($_FILES["fileToUpload"]
eToUpload" id="fileToUpload"> ["name"]);
    <input type="submit" value=" $uploadOk = 1;
Upload Image" name="submit"> $imageFileType =
</form> pathinfo($target_file,PATHINFO_E
XTENSION);
</body> // Check if image file is a
</html> actual image or fake image
if(isset($_POST["submit"])) {
Some rules to follow for the HTML     $check =
form above: getimagesize($_FILES["fileToUplo
ad"]["tmp_name"]);
 Make sure that the form uses     if($check !== false) {
method="post"         echo "File is an image -
 The form also needs the " . $check["mime"] . ".";
following attribute:         $uploadOk = 1;
enctype="multipart/form-     } else {
data". It specifies which         echo "File is not an
content-type to use when image.";
submitting the form         $uploadOk = 0;
    }
Without the requirements above, the }
file upload will not work. ?>
WEB DESIGN PROGRAMMING : CHAPTER 5
(PHP: Web Design) ----JITENDRA SINGH

PHP script explained: The file input field in our HTML form
above is named "fileToUpload".
 $target_dir = "uploads/" -
specifies the directory where Now, we want to check the size of
the file is going to be placed the file. If the file is larger than
 $target_file specifies the path 500KB, an error message is
of the file to be uploaded displayed, and $uploadOk is set to
 $uploadOk=1 is not used yet 0:
(will be used later)
 $imageFileType holds the file  // Check file size
extension of the file if ($_FILES["fileToUpload"]
 Next, check if the image file is ["size"] > 500000) {
an actual image or a fake     echo "Sorry, your file is
image too large.";
    $uploadOk = 0;
Note: You will need to create a new }
directory called "uploads" in the
directory where "upload.php" file
resides. The uploaded files will be
saved there.
Limit File Type
The code below only allows users to

Check if File Already upload JPG, JPEG, PNG, and GIF


files. All other file types gives an
error message before setting
Exists $uploadOk to 0:

Now we can add some restrictions. // Allow certain file formats


if($imageFileType != "jpg" &&
First, we will check if the file already $imageFileType != "png" &&
exists in the "uploads" folder. If it $imageFileType != "jpeg"
does, an error message is displayed, && $imageFileType != "gif" ) {
and $uploadOk is set to 0:     echo "Sorry, only JPG, JPEG,
PNG & GIF files are allowed.";
// Check if file already exists     $uploadOk = 0;
if (file_exists($target_file)) { }
    echo "Sorry, file already
exists.";
    $uploadOk = 0;

Complete Upload File


}

PHP Script
Limit File Size The complete "upload.php" file now
looks like this:
WEB DESIGN PROGRAMMING : CHAPTER 5
(PHP: Web Design) ----JITENDRA SINGH

<?php 0 by an error
$target_dir = "uploads/"; if ($uploadOk == 0) {
$target_file = $target_dir .     echo "Sorry, your file was
basename($_FILES["fileToUpload"] not uploaded.";
["name"]); // if everything is ok, try to
$uploadOk = 1; upload file
$imageFileType = } else {
pathinfo($target_file,PATHINFO_E     if (move_uploaded_file($_FIL
XTENSION); ES["fileToUpload"]["tmp_name"],
// Check if image file is a $target_file)) {
actual image or fake image         echo "The file ".
if(isset($_POST["submit"])) { basename( $_FILES["fileToUpload"
    $check = ]["name"]). " has been
getimagesize($_FILES["fileToUplo uploaded.";
ad"]["tmp_name"]);     } else {
    if($check !== false) {         echo "Sorry, there was
        echo "File is an image - an error uploading your file.";
" . $check["mime"] . ".";     }
        $uploadOk = 1; }
    } else { ?>
        echo "File is not an

PHP  Sessions
image.";
        $uploadOk = 0;
    }
}
// Check if file already exists A session is a way to store
if (file_exists($target_file)) { information (in variables) to be
    echo "Sorry, file already used across multiple pages.
exists.";
    $uploadOk = 0; Unlike a cookie, the information is
} not stored on the users computer.
// Check file size
if ($_FILES["fileToUpload"]
["size"] > 500000) { What is a PHP
Session?
    echo "Sorry, your file is
too large.";
    $uploadOk = 0;
} When you work with an application,
// Allow certain file formats you open it, do some changes, and
if($imageFileType != "jpg" && then you close it. This is much like a
$imageFileType != "png" && Session. The computer knows who
$imageFileType != "jpeg" you are. It knows when you start the
&& $imageFileType != "gif" ) { application and when you end. But
    echo "Sorry, only JPG, JPEG, on the internet there is one problem:
PNG & GIF files are allowed."; the web server does not know who
    $uploadOk = 0; you are or what you do, because the
} HTTP address doesn't maintain
// Check if $uploadOk is set to state.
WEB DESIGN PROGRAMMING : CHAPTER 5
(PHP: Web Design) ----JITENDRA SINGH

Session variables solve this problem ?>


by storing user information to be
used across multiple pages (e.g. </body>
username, favorite color, etc). By </html>
default, session variables last until
the user closes the browser. Note: The session_start() function
must be the very first thing in your
So; Session variables hold document. Before any HTML tags.
information about one single user,
and are available to all pages in one
application.

Tip: If you need a permanent


storage, you may want to store the
Get PHP Session
data in a database.
Variable Values
Next, we create another page called
"demo_session2.php". From this
Start a PHP Session page, we will access the session
information we set on the first page
("demo_session1.php").
A session is started with the
session_start() function. Notice that session variables are not
passed individually to each new
Session variables are set with the page, instead they are retrieved
PHP global variable: $_SESSION. from the session we open at the
beginning of each page
Now, let's create a new page called (session_start()).
"demo_session1.php". In this page,
we start a new PHP session and set Also notice that all session variable
some session variables: values are stored in the global
$_SESSION variable:
Example
<?php
Example
// Start the session <?php
session_start(); session_start();
?> ?>
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
<body> <body>

<?php <?php
// Set session variables // Echo session variables that were
$_SESSION["favcolor"] = "green"; set on previous page
$_SESSION["favanimal"] = "cat"; echo "Favorite color is
echo "Session variables are set.";
WEB DESIGN PROGRAMMING : CHAPTER 5
(PHP: Web Design) ----JITENDRA SINGH

Modify a PHP Session


" . $_SESSION["favcolor"] . ".<br>"
;

Variable
echo "Favorite animal is
" . $_SESSION["favanimal"] . ".";
?>
To change a session variable, just
</body> overwrite it:
</html>

Another way to show all the session


Example
variable values for a user session is <?php
to run the following code: session_start();
?>
Example <!DOCTYPE html>
<html>
<?php <body>
session_start();
?> <?php
<!DOCTYPE html> // to change a session variable,
<html> just overwrite it 
<body> $_SESSION["favcolor"] = "yellow";
print_r($_SESSION);
<?php ?>
print_r($_SESSION);
?> </body>
</html>
</body>
</html>

How does it work? How does it


know it's me? Destroy a PHP
Most sessions set a user-key on the
user's computer that looks
Session
something like this:
765487cf34ert8dede5a562e4f3a7e1 To remove all global session
2. Then, when a session is opened variables and destroy the session,
on another page, it scans the use session_unset() and
computer for a user-key. If there is session_destroy():
a match, it accesses that session, if
not, it starts a new session. Example
<?php
session_start();
?>
<!DOCTYPE html>
WEB DESIGN PROGRAMMING : CHAPTER 5
(PHP: Web Design) ----JITENDRA SINGH

Basic Error Handling:


<html>
<body>

<?php Using the die()


function
// remove all session variables
session_unset(); 

// destroy the session  The first example shows a simple


session_destroy();  script that opens a text file:
?>
<?php
</body> $file=fopen("welcome.txt","r");
</html> ?>

If the file does not exist you might


PHP Error get an error like this:

Handling
Warning: fopen(welcome.txt)
[function.fopen]: failed to open
stream:
No such file or directory
When creating scripts and web in C:\webfolder\test.php on
applications, error handling is an line 2
important part. If your code lacks
error checking code, your program To prevent the user from getting an
may look very unprofessional and error message like the one above,
you may be open to security risks. we test whether the file exist before
we try to access it:
This tutorial contains some of the
most common error checking <?php
methods in PHP. if(!file_exists("welcome.txt")) 
{
We will show different error handling   die("File not found");
methods: } else {
  $file=fopen("welcome.txt","r")
 Simple "die()" statements ;
 Custom errors and error }
triggers ?>
 Error reporting
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
WEB DESIGN PROGRAMMING : CHAPTER 5
(PHP: Web Design) ----JITENDRA SINGH

mechanism to stop the script after


the error.
for possible error
report levels
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.
error_messa Required.
ge Specifies the error
message for the
user-defined error
Creating a Custom
Error Handler error_file Optional.
Specifies the
Creating a custom error handler is filename in which
quite simple. We simply create a the error occurred
special function that can be called
when an error occurs in PHP.

This function must be able to handle error_line Optional.


a minimum of two parameters (error Specifies the line
level and error message) but can number in which
accept up to five parameters the error occurred
(optionally: file, line-number, and
the error context):

error_contex Optional.
Syntax t Specifies an array
containing every
error_function(error_level,error variable, and their
_message, values, in use
error_file,error_line,error_cont when the error
ext) occurred

Parameter Description
Error Report levels
These error report levels are the
error_level Required. different types of error the user-
Specifies the error defined error handler can be used
report level for for:
the user-defined
error. Must be a
value number.
See table below
WEB DESIGN PROGRAMMING : CHAPTER 5
(PHP: Web Design) ----JITENDRA SINGH

Val Constant Description This is like


ue an
E_WARNIN
G set by the
programmer
2 E_WARNING Non-fatal using the
run-time PHP
errors. function
Execution of trigger_error
the script is ()
not halted

102 E_USER_NOTICE User-


8 E_NOTICE Run-time 4 generated
notices. The notice. This
script found is like an
something E_NOTICE
that might be set by the
an error, but programmer
could also using the
happen when PHP
running a function
script trigger_error
normally ()

256 E_USER_ERROR Fatal user- 409 E_RECOVERABL Catchable


generated 6 E_ERROR fatal error.
error. This is This is like
like an an
E_ERROR E_ERROR
set by the but can be
programmer caught by a
using the user defined
PHP handle (see
function also
trigger_error set_error_ha
() ndler())

512 E_USER_WARNI Non-fatal 819 E_ALL All errors


NG user- 1 and
generated warnings
warning. (E_STRICT
WEB DESIGN PROGRAMMING : CHAPTER 5
(PHP: Web Design) ----JITENDRA SINGH

set_error_handler("customError")
;
became a
part of
Since we want our custom function
E_ALL in
to handle all errors, the
PHP 5.4)
set_error_handler() only needed one
parameter, a second parameter
could be added to specify an error
Now lets create a function to handle level.
errors:

function customError($errno, Example


$errstr) {
  echo "<b>Error:</b> [$errno] Testing the error handler by trying
$errstr<br>"; to output variable that does not
  echo "Ending Script"; exist:
  die();
} <?php
//error handler function
The code above is a simple error function customError($errno,
handling function. When it is $errstr) {
triggered, it gets the error level and   echo "<b>Error:</b> [$errno]
an error message. It then outputs $errstr";
the error level and message and }
terminates the script.
//set error handler
Now that we have created an error set_error_handler("customError")
handling function we need to decide ;
when it should be triggered.
//trigger error
echo($test);
?>

Set Error Handler The output of the code above should


be something like this:
The default error handler for PHP is
the built in error handler. We are Error: [8] Undefined variable:
going to make the function above test
the default error handler for the
duration of the script.

It is possible to change the error


handler to apply for only some Trigger an Error
errors, that way the script can
handle different errors in different In a script where users can input
ways. However, in this example we data it is useful to trigger errors
are going to use our custom error when an illegal input occurs. In PHP,
handler for all errors:
WEB DESIGN PROGRAMMING : CHAPTER 5
(PHP: Web Design) ----JITENDRA SINGH

this is done by the trigger_error()


function. Example
Example In this example an
E_USER_WARNING occurs if the
"test" variable is bigger than "1". If
In this example an error occurs if an E_USER_WARNING occurs we will
the "test" variable is bigger than "1": use our custom error handler and
end the script:
<?php
$test=2; <?php
if ($test>=1) { //error handler function
  trigger_error("Value must be 1 function customError($errno,
or below"); $errstr) {
}   echo "<b>Error:</b> [$errno]
?> $errstr<br>";
  echo "Ending Script";
The output of the code above should   die();
be something like this: }

Notice: Value must be 1 or below //set error handler


in C:\webfolder\test.php on set_error_handler("customError",
line 6 E_USER_WARNING);

An error can be triggered anywhere //trigger error


you wish in a script, and by adding a $test=2;
second parameter, you can specify if ($test>=1) {
what error level is triggered.   trigger_error("Value must be 1
or below",E_USER_WARNING);
Possible error types: }
?>
 E_USER_ERROR - Fatal user-
generated run-time error. The output of the code above should
Errors that can not be be something like this:
recovered from. Execution of
the script is halted Error: [512] Value must be 1 or
 E_USER_WARNING - Non-fatal below
user-generated run-time Ending Script
warning. Execution of the
script is not halted Now that we have learned to create
 E_USER_NOTICE - Default. our own errors and how to trigger
User-generated run-time them, lets take a look at error
notice. The script found logging.
something that might be an
error, but could also happen
when running a script
normally
Error Logging
WEB DESIGN PROGRAMMING : CHAPTER 5
(PHP: Web Design) ----JITENDRA SINGH

By default, PHP sends an error log to The output of the code above should
the server's logging system or a file, be something like this:
depending on how the error_log
configuration is set in the php.ini Error: [512] Value must be 1 or
file. By using the error_log() function below
you can send error logs to a Webmaster has been notified
specified file or a remote destination.
And the mail received from the code
Sending error messages to yourself above looks like this:
by e-mail can be a good way of
getting notified of specific errors. Error: [512] Value must be 1 or
below

Send an Error This should not be used with all


errors. Regular errors should be
Message by E-Mail logged on the server using the
default PHP logging system.
In the example below we will send

PHP Exception
an e-mail with an error message and
end the script, if a specific error
occurs:

<?php Handling
//error handler function
function customError($errno,
$errstr) { Exceptions are used to change the
  echo "<b>Error:</b> [$errno] normal flow of a script if a specified
$errstr<br>"; error occurs.
  echo "Webmaster has been
notified";
  error_log("Error: [$errno]

What is an Exception
$errstr",1,
  "someone@example.com","From:
webmaster@example.com");
} With PHP 5 came a new object
oriented way of dealing with errors.
//set error handler
set_error_handler("customError", Exception handling is used to change
E_USER_WARNING); the normal flow of the code
execution if a specified error
//trigger error (exceptional) condition occurs. This
$test=2; condition is called an exception.
if ($test>=1) {
  trigger_error("Value must be 1 This is what normally happens when
or below",E_USER_WARNING); an exception is triggered:
}
?>  The current code state is
saved
WEB DESIGN PROGRAMMING : CHAPTER 5
(PHP: Web Design) ----JITENDRA SINGH

 The code execution will switch <?php


to a predefined (custom) //create function with an
exception handler function exception
 Depending on the situation, function checkNum($number) {
the handler may then resume   if($number>1) {
the execution from the saved     throw new Exception("Value
code state, terminate the must be 1 or below");
script execution or continue   }
the script from a different   return true;
location in the code }

We will show different error handling //trigger exception


methods: checkNum(2);
?>
 Basic use of Exceptions
 Creating a custom exception The code above will get an error like
handler this:
 Multiple exceptions
 Re-throwing an exception Fatal error: Uncaught exception
 Setting a top level exception 'Exception'
handler with message 'Value must be 1 or
below' in
Note: Exceptions should only be C:\webfolder\test.php:6
used with error conditions, and Stack trace: #0
should not be used to jump to C:\webfolder\test.php(12):
another place in the code at a checkNum(28) #1 {main} thrown
specified point. in C:\webfolder\test.php on
line 6

Try, throw and catch


Basic Use of To avoid the error from the example
Exceptions above, we need to create the proper
code to handle an exception.
When an exception is thrown, the Proper exception code should
code following it will not be include:
executed, and PHP will try to find the
matching "catch" block. 1. Try - A function using an
exception should be in a "try"
If an exception is not caught, a fatal block. If the exception does
error will be issued with an not trigger, the code will
"Uncaught Exception" message. continue as normal. However
if the exception triggers, an
Lets try to throw an exception exception is "thrown"
without catching it: 2. Throw - This is how you
trigger an exception. Each
WEB DESIGN PROGRAMMING : CHAPTER 5
(PHP: Web Design) ----JITENDRA SINGH

"throw" must have at least The code above throws an exception


one "catch" and catches it:
3. Catch - A "catch" block
retrieves an exception and 1. The checkNum() function is
creates an object containing created. It checks if a number
the exception information is greater than 1. If it is, an
exception is thrown
Lets try to trigger an exception with 2. The checkNum() function is
valid code: called in a "try" block
3. The exception within the
<?php checkNum() function is thrown
//create function with an 4. The "catch" block retrieves the
exception exception and creates an
function checkNum($number) { object ($e) containing the
  if($number>1) { exception information
    throw new Exception("Value 5. The error message from the
must be 1 or below"); exception is echoed by calling
  } $e->getMessage() from the
  return true; exception object
}
However, one way to get around the
//trigger exception in a "try" "every throw must have a catch"
block rule is to set a top level exception
try { handler to handle errors that slip
  checkNum(2); through.
  //If the exception is thrown,

PHP Connect to
this text will not be shown
  echo 'If you see this, the
number is 1 or below';

MySQL
}

//catch exception
catch(Exception $e) {
  echo 'Message: ' .$e-
>getMessage();
Open a Connection
}
?>
to MySQL
The code above will get an error like Before we can access data in the
this: MySQL database, we need to be able
to connect to the server:
Message: Value must be 1 or
below Example (MySQLi Object-
Example explained: Oriented)
<?php
$servername = "localhost";
WEB DESIGN PROGRAMMING : CHAPTER 5
(PHP: Web Design) ----JITENDRA SINGH

$username = "username"; // Check connection


$password = "password"; if (!$conn) {
    die("Connection failed: " .
// Create connection mysqli_connect_error());
$conn = new mysqli($servername, }
$username, $password); echo "Connected successfully";
?>
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . Close the Connection
$conn->connect_error);
}  The connection will be closed
echo "Connected successfully"; automatically when the script ends.
?> To close the connection before, use
the following:

Example (MySQLi Object-


PHP is an amazing and popular
language! Oriented)
Note on the object-oriented example $conn->close();
above: $connect_error was broken
until PHP 5.2.9 and 5.3.0. If you
need to ensure compatibility with
PHP versions prior to 5.2.9 and Example (MySQLi
5.3.0, use the following code
instead: Procedural)
// Check connection mysqli_close($conn);
if (mysqli_connect_error()) {

PHP Create a
    die("Database connection failed: "
. mysqli_connect_error());
}

Example (MySQLi MySQL Database


Procedural) The CREATE DATABASE statement is
used to create a database in MySQL.
<?php
$servername = "localhost";
The following examples create a
$username = "username"; database named "myDB":
$password = "password";

// Create connection
$conn = mysqli_connect($servername,
$username, $password);
WEB DESIGN PROGRAMMING : CHAPTER 5
(PHP: Web Design) ----JITENDRA SINGH

Example (MySQLi Object-


mysqli_connect_error());
}

oriented) // Create database


<?php $sql = "CREATE DATABASE myDB";
$servername = "localhost"; if (mysqli_query($conn, $sql)) {
$username = "username";     echo "Database created
$password = "password"; successfully";
} else {
// Create connection     echo "Error creating database:
$conn = new mysqli($servername, " . mysqli_error($conn);
$username, $password); }
// Check connection
if ($conn->connect_error) { mysqli_close($conn);
    die("Connection failed: " . ?>
$conn->connect_error);

// Create database
$sql = "CREATE DATABASE myDB";
if ($conn->query($sql) === TRUE) {
    echo "Database created
successfully";
} else {
    echo "Error creating database:
" . $conn->error;
}

$conn->close();
?>

Example (MySQLi
Procedural)
<?php
$servername = "localhost";
$username = "username";
$password = "password";

// Create connection
$conn = mysqli_connect($servername,
$username, $password);
// Check connection
if (!$conn) {
    die("Connection failed: " .

You might also like