Web Design Programming Chapter 5
Web Design Programming Chapter 5
Handling <html>
<body>
Form </html>
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.
PHP Validate E-
XML
CSS = Cascading Style Sheets
HTML = Hyper Text Markup Language
PHP- FILE
?>
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
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);
?>
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:
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
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
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
<?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
Variable
echo "Favorite animal is
" . $_SESSION["favanimal"] . ".";
?>
To change a session variable, just
</body> overwrite it:
</html>
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:
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
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:
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
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
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
PHP Create a
die("Database connection failed: "
. mysqli_connect_error());
}
// Create connection
$conn = mysqli_connect($servername,
$username, $password);
WEB DESIGN PROGRAMMING : CHAPTER 5
(PHP: Web Design) ----JITENDRA SINGH
// 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: " .