Sita1502 Customer Interface Design and Development-165-219
Sita1502 Customer Interface Design and Development-165-219
Sita1502 Customer Interface Design and Development-165-219
Introduction To PHP – Data Types – Control Structures – Arrays - Function – HTML Form with
PHP – Form Handling and Validation - File Handling – Cookies – Sessions – Filters – Exception
Handling - Database Connectivity with MySQL.
Introduction to PHP
• Acronym for “PHP: Hypertext Preprocessor”.
• PHP is a widely-used, open-source server-side scripting language that is embedded in HTML.
It is used to manage dynamic content, databases, session tracking, even build entire e-
commerce sites.
• It is integrated with a number of popular databases, including MySQL, PostgreSQL, Oracle,
Sybase, Informix, and Microsoft SQL Server.
• PHP Syntax is C-Like.
• PHP scripts are executed on the server
• PHP is free to download and use
Common uses of PHP
• PHP performs system functions, i.e. from files on a system it can create, open, read, write,
and close them.
• PHP can handle forms, i.e. gather data from files, save data to a file, through email you can
send data, return data to the user.
• You add, delete, modify elements within your database through PHP.
• Access cookies variables and set cookies.
• Using PHP, you can restrict users to access some pages of your website.
• It can encrypt data.
• PHP files can contain text, HTML, CSS, JavaScript, and PHP code
• PHP code is executed on the server, and the result is returned to the browser as plain HTML
• PHP files have extension ".php"
Why PHP?
<html>
<head>
<title>Hello World</title>
</head>
<body>
<?php echo "Hello, World!";?>
</body>
</html>
Output:
Hello, World!
All PHP code must be included inside one of the three special markup tags which are recognised by
the PHP Parser.
PHP Variables
• All php variables are denoted with a leading dollar sign ($).
• The value of a variable is the value of its most recent assignment.
• Variables are assigned with the = operator, with the variable on the left-hand side and the
expression to be evaluated on the right.
• Variables can, but do not need, to be declared before assignment.
• Variables in PHP do not have intrinsic types - a variable does not know in advance whether
it will be used to store a number or a string of characters.
• Variables used before they are assigned have default values.
• PHP does a good job of automatically converting types from one to another when necessary.
PHP has a total of eight data types which we use to construct our variables −
• Integers − are whole numbers, without a decimal point, like 4195.
• Doubles − are floating-point numbers, like 3.14159 or 49.1.
• Booleans − have only two possible values either true or false.
• NULL − is a special type that only has one value: NULL.
• Strings − are sequences of characters, like 'PHP supports string operations.'
• Arrays − are named and indexed collections of other values.
• Objects − are instances of programmer-defined classes, which can package up both other
kinds of values and functions that are specific to the class.
• Resources − are special variables that hold references to resources external to PHP (such as
database connections).
The first five are simple types, and the next two (arrays and objects) are compound - the compound
types can package up other arbitrary values of arbitrary type, whereas the simple types cannot.
1. Integers
They are whole numbers, without a decimal point, like 4195. They are the simplest type .they
correspond to simple whole numbers, both positive and negative. Integers can be assigned to
variables, or they can be used in expressions as following,
$int_var = 12345;
$another_int = -12345 + 12345;
2. Doubles
They like 3.14159 or 49.1. By default, doubles print with the minimum number of decimal places
needed. For example, the code −
Example:
<?php
$a = 2.2888800;
$b = 2.2111200;
$c = $a + $b;
print("$a + $b = $c <br>");
?>
Output:
2.28888 + 2.21112 = 4.5
3. Boolean
They have only two possible values either true or false. PHP provides a couple of constants especially
for use as Booleans: TRUE and FALSE, which can be used like so −
if (TRUE)
print("This will always print<br>");
else
print("This will never print<br>");
Each of the following variables has the truth value embedded in its name when it is used in a
Boolean context.
$true_num = 3 + 0.14159;
$true_str = "Tried and true"
$true_array[49] = "An array element";
$false_array = array();
$false_null = NULL;
$false_num = 999 - 999;
$false_str = "";
4. NULL
NULL is a special type that only has one value: NULL. To give a variable the NULL value, simply assign
it like this –
$my_var = null;
Or
$my_var = NULL;
5. String
A string is a sequence of characters, like "Hello world!". A string can be any text inside
quotes. You can use single or double quotes:
Example:
<?php
$x= "Helloworld!";
$y= 'Helloworld!';
echo $x;
echo "<br>";
echo $y;
?>
Output:
Helloworld!
Helloworld!
6. Array
An array stores multiple values in one single variable. In the following example $cars is an array. The
PHP var_dump() function returns the data type and value:
Example:
<html>
<body>
<?php
$cars = array("Volvo","BMW","Toyota");
var_dump($cars);
?>
</body>
</html>
Output:
array(3) {
[0]=>
string(5) "Volvo"
[1]=>
string(3) "BMW"
[2]=>
string(6) "Toyota"
}
7. Object
•Classes and objects are the two main aspects of object-oriented programming.
•A class is a template for objects, and an object is an instance of a class.
•When the individual objects are created, they inherit all the properties and behaviors from the
class, but each object will have different values for the properties.
• Let's assume we have a class named Car. A Car can have properties like model, color, etc.
We can define variables like $model, $color, and so on, to hold the values of these properties.
• When the individual objects (Volvo, BMW, Toyota, etc.) are created, they inherit all the
properties and behaviors from the class, but each object will have different values for the
properties.
• If you create a __construct() function, PHP will automatically call this function when you
create an object from a class. Notice that the construct function starts with two underscores
(__)!
Example:-
<?php
class Car {
public $color;
public $model;
public function construct($color, $model) {
$this->color = $color;
$this->model = $model;
}
public function message() {
return "My car is a ". $this->color . " " . $this->model . "!";
}
}
Output:
My car is a black Volvo!
My car is a red Toyota!
8. Resource
The special resource type is not an actual data type. It is the storing of a reference to functions and
resources external to PHP. They are special variables that hold references to resources external to PHP (such
as database connections). A common example of using the resource data type is a database call.
PHP Control Structures and Loops: if, else, for, foreach, while
The control structure controls the flow of code execution in application. Generally, a program is
executed sequentially, line by line, and a control structure allows you to alter that flow, usually depending
on certain conditions.
Control structures are core features of the PHP language that allow script to respond differently to
different inputs or situations. This could allow script to give different responses based on user input, file
contents, or some other data.
• if
• else
• elseif
• switch
• while
• do-while
• for
• foreach
1. PHP If Statement
The ‘if’ construct allows you to execute a piece of code if the expression provided along with it evaluates
to true.
Example:
<?php
$age = 50;
if ($age > 30)
{
echo "Your age is greater than 30!";
}
?>
Output: Your age is greater than 30!
<?php
$age = 50;
if ($age < 30)
{
echo "Your age is less than 30!";
}
else
{
echo "Your age is greater than or equal to 30!";
}
?>
<?php
$age = 50;
if ($age < 30)
{
echo "Your age is less than 30!";
}
elseif ($age > 30 && $age < 40)
{
echo "Your age is between 30 and 40!";
}
elseif ($age > 40 && $age < 50)
{
echo "Your age is between 40 and 50!";
}
else
{
echo "Your age is greater than 50!";
}
?>
In the above example, check the value of the $favourite_site variable, and based on the value
of the $favourite_site variable, print a message.
For each value you want to check with the $favourite_site variable, you have to define the case block.
If the value is matched with a case, the code associated with that case block will be executed. After
that, you need to use the break statement to end code execution. If you don't use the break statement,
script execution will be continued up to the last block in the switch statement.
Finally, if you want to execute a piece of code if the variable's value doesn't match any case, you can
define it under the default block. Of course, it's not mandatory—it's just a way to provide a default
case.
Loops in PHP
<?php
$max = 0;
echo $i = 0;
echo ",";
echo $j = 1;
echo ",";
$result=0;
while ($max < 10 )
{
$result = $i + $j;
$i = $j;
$j = $result;
$max = $max + 1;
echo $result;
echo ",";
}
?>
The above program outputs the square of the first ten numbers. It initializes $i to 1, repeats as long
as $i is less than or equal to 10, and adds 1 to $i at each iteration.
Output:
The square of 1 is 1.
The square of 2 is 4.
The square of 3 is 9.
The square of 4 is 16.
The square of 5 is 25.
The square of 6 is 36.
The square of 7 is 49.
The square of 8 is 64.
The square of 9 is 81.
The square of 10 is 100.
$employee = array('name' => 'John Smith', 'age' => 30, 'profession' => 'Software Engineer');
foreach ($employee as $key => $value)
{
echo sprintf("%s: %s</br>", $key, $value);
echo "<br/>";
}
?>
Output:
apple
banana
orange
grapes
name: John Smith
age: 30
If you want to access array values, you can use the first version of the foreach loop, as shown
in the above example. On the other hand, if you want to access both a key and a value, you can do it
as shown in the $employee example above.
PHP Arrays
An array is a special variable, which can hold more than one value at a time. If you have a list of items
(a list of car names, for example), the array can be created as follows:
Example:
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
In PHP, the array() function is used to create an array. In PHP, there are three types of arrays:
The count() function is used to return the length (the number of elements) of an array:
Example:
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo count($cars);
?>
Output: 3
There are two ways to create indexed arrays. The index can be assigned automatically (index always
starts at 0), like this:
Example:
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
Output: I like Volvo,BMW and Toyota
To loop through and print all the values of an indexed array, you could use a for loop, like this:
Example:
<?php
$cars = array("Volvo", "BMW", "Toyota");
$arrlength = count($cars);
for($x = 0; $x < $arrlength; $x++) {
echo $cars[$x];
echo "<br>";
}
?>
Output:
Volvo
BMW
Toyota
Associative arrays are arrays that use named keys that you assign to them. There are two ways to
create an associative array:
To loop through and print all the values of an associative array, you could use a foreach loop, like
this:
Example:
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
foreach($age as $x => $x_value) {
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>
Output:
Key=Peter,Value=35
Key=Ben,Value=37
Key=Joe, Value=43
A multidimensional array is an array containing one or more arrays. PHP supports multidimensional
arrays that are two, three, four, five, or more levels deep. However, arrays more than three levels deep are
hard to manage for most people. The dimension of an array indicates the number of indices you need to
select an element.
For a two-dimensional array, two indices are needed to select an element. For a three-dimensional array,
three indices are needed to select an element.
We can store the data from the table above in a two-dimensional array, like this:
$cars = array (
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);
Now the two-dimensional $cars array contains four arrays, and it has two indices: row and column.
To get access to the elements of the $cars array we must point to the two indices (row and column):
Example:
<?php
echo $cars[0][0].": In stock: ".$cars[0][1].", sold: ".$cars[0][2].".<br>";
echo $cars[1][0].": In stock: ".$cars[1][1].", sold: ".$cars[1][2].".<br>";
echo $cars[2][0].": In stock: ".$cars[2][1].", sold: ".$cars[2][2].".<br>";
echo $cars[3][0].": In stock: ".$cars[3][1].", sold: ".$cars[3][2].".<br>";
?>
Output:
Volvo: In stock: 22, sold: 18.
BMW: In stock: 15, sold: 13.
Saab: In stock: 5, sold: 2.
Land Rover: In stock: 17, sold: 15.
We can also put a for loop inside another for loop to get the elements of the $cars array (we still have to
point to the two indices):
Example:
<?php
for ($row = 0; $row < 4; $row++) {
echo "<p><b>Row number $row</b></p>";
echo "<ul>";
for ($col = 0; $col < 3; $col++) {
echo "<li>".$cars[$row][$col]."</li>";
}
echo "</ul>";
}
?>
Output:
Row number 0
Volvo
22
18
Row number 1
BMW
15
13
Row number 2
Saab
5
2
Row number 3
Land Rover
17
15
1. sort()
The following example sorts the elements of the $cars array in ascending alphabetical order:
Example:-
<?php
$cars = array("Volvo", "BMW", "Toyota");
sort($cars);
$clength = count($cars);
for($x = 0; $x < $clength; $x++) {
echo $cars[$x];
echo "<br>";
}
?>
Result:
BMW
Toyota
Volvo
2. rsort()
Example:-
<?php
$cars = array("Volvo", "BMW", "Toyota");
rsort($cars);
$clength = count($cars);
for($x = 0; $x < $clength; $x++) {
echo $cars[$x];
echo "<br>";
}
?>
Result:
Volvo
Toyota
BMW
3. asort()
It sorts an associative array in ascending order, according to the value:
Example:-
<?php
$age = array("Peter"=>"37", "Ben"=>"35", "Joe"=>"29");
asort($age);
foreach($age as $x => $x_value) {
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>
Result:
Key=Joe,Value=29
Key=Ben,Value=35
Key=Peter, Value=37
4. ksort()
The following example sorts an associative array in ascending order, according to the key:
Example:-
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
ksort($age);
Result:
Key=Ben, Value=37
Key=Joe, Value=43
Key=Peter, Value=35
It sorts an associative array in descending order, according to the value: For the same example given
above, the result for arsort() is as follows,
Key=Joe, Value=43
Key=Ben, Value=37
Key=Peter, Value=35
It sorts an associative array in descending order, according to the key. For the above example, the result
for krsort() is as follows,
Key=Peter, Value=35
Key=Joe, Value=43
Key=Ben, Value=37
PHP Functions
PHP has more than 1000 built-in functions, and in addition we can create our own custom
functions.
PHP Built-in Functions
PHP has over 1000 built-in functions that can be called directly, from within a script, to perform a
specific task.
Besides the built-in PHP functions, it is possible to create your own functions.
Syntax:
function functionName() {
code to be executed;
}
Note: A function name must start with a letter or an underscore. Function names are NOT case-
sensitive.
Example:-
<?php
function writeMsg() {
echo "Hello world!";
}
writeMsg(); // call the function
?>
Output: Hello world!
Information can be passed to functions through arguments. An argument is just like a variable.
Arguments are specified after the function name, inside the parentheses. You can add as many arguments as
you want, just separate them with a comma.
The following example has a function with one argument ($fname). When the familyName() function
is called, we also pass along a name (e.g. Jani), and the name is used inside the function, which outputs several
different first names, but an equal last name:
Example:
<?php
function familyName($fname) {
echo "$fname <br>";
}
familyName("Jani");
familyName("Hege");
familyName("Stale");
familyName("Kai Jim");
familyName("Borge");
?>
Result:
Jani
Hege
Stale
Kai Jim
Borge
The following example has a function with two arguments ($fname and $year):
<?php
function familyName($fname, $year) {
echo "$fname Born in $year <br>";
}
familyName("Hege","1975");
familyName("Stale","1978");
familyName("Kai Jim","1983");
?>
Result:
Hege Born in 1975
Stale Born in 1978
Kai Jim Born in 1983
PHP is a Loosely Typed Language:
In the example above, notice that we did not have to tell PHP which data type the variable is. PHP
automatically associates a data type to the variable, depending on its value. Since the data types are not set
in a strict sense, you can do things like adding a string to an integer without causing an error.
In PHP 7, type declarations were added. This gives us an option to specify the expected data type when
declaring a function, and by adding the strict declaration, it will throw a "Fatal Error" if the data type
mismatches.
In the following example we try to send both a number and a string to the function without using strict:
Example:
<?php
function addNumbers(int $a, int $b) {
return $a + $b;
}
echo addNumbers(5, "5 days");
// since strict is NOT enabled "5 days" is changed to int(5), and it will return 10
?>
Result: 10
To specify strict we need to set declare(strict_types=1);. This must be on the very first line of the
PHP file. In the following example we try to send both a number and a string to the function, but here we
have added the strict declaration:
The following example shows how to use a default parameter. If we call the function setHeight()
without arguments it takes the default value as argument:
Example:
<?php
function setHeight(int $minheight = 50) {
echo "The height is : $minheight <br>";
}
setHeight(350);
setHeight();
setHeight(135);
setHeight(80);
?>
Result:
The height is : 350
The height is : 50
The height is : 135
The height is : 80
Example:
<?php
function sum(int $x, int $y) {
$z = $x + $y;
return $z;
}
PHP 7 also supports Type Declarations for the return statement. Like with the type declaration for
function arguments, by enabling the strict requirement, it will throw a "Fatal Error" on a type mismatch.
To declare a type for the function return, add a colon ( : ) and the type right before the opening curly
( { )bracket when declaring the function.
In the following example we specify the return type for the function:
Example:
<?php declare(strict_types=1); // strict requirement
function addNumbers(float $a, float $b) : float {
return $a + $b;
}
echo addNumbers(1.2, 5.2);
?>
Result: 6.4
Example
<?php
function add_five(&$value) {
$value += 5;
}
$num = 2;
add_five($num);
echo $num;
?>
Result: 7
</body>
</html>
Result:
When the user fills out the form above and clicks the submit button, the form data is sent for
processing to a PHP file named "welcome.php". The form data is sent with the HTTP POST method.
To display the submitted data you could simply echo all the variables. The "welcome.php" looks like
this:
<html>
<body>
</body>
</html>
Output:
Welcome John
Your email address is [email protected]
The code above is quite simple. However, the most important thing is missing. The form data
need to be validated to protect the script from malicious code. Think SECURITY when processing
PHP forms! This page does not contain any form validation, it just shows how to send and retrieve
form data. However, the next topic will show how to process PHP forms with security in mind!
Proper validation of form data is important to protect the form from hackers and spammers!
Both GET and POST create an array (e.g. array( key1 => value1, key2 => value2, key3 => value3, ...)).
This array holds key/value pairs, where keys are the names of the form controls and values are the input data
from the user.
Both GET and POST are treated as $_GET and $_POST. These are superglobals, which means that
they are always accessible, regardless of scope - and you can access them from any function, class or file
without having to do anything special.
$_GET is an array of variables passed to the current script via the URL parameters.
$_POST is an array of variables passed to the current script via the HTTP POST method.
Information sent from a form with the GET method is visible to everyone (all variable names and
values are displayed in the URL). GET also has limits on the amount of information to send. The limitation is
about 2000 characters. However, because the variables are displayed in the URL, it is possible to bookmark
the page. This can be useful in some cases. GET may be used for sending non-sensitive data.
Note: GET should NEVER be used for sending passwords or other sensitive information!
Information sent from a form with the POST method is invisible to others (all names/values are
embedded within the body of the HTTP request) and has no limits on the amount of information to send.
Moreover, POST supports advanced functionality such as support for multi-part binary input while uploading
files to server. However, because the variables are not displayed in the URL, it is not possible to bookmark
the page.
Text Fields
The name, email, and website fields are text input elements, and the comment field is a
textarea. The HTML code looks like this:
Radio Buttons
The gender fields are radio buttons and the HTML code looks like this:
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<input type="radio" name="gender" value="other">Other
When the form is submitted, the form data is sent with method="post".
$_SERVER["PHP_SELF"] variable
The $_SERVER["PHP_SELF"] is a super global variable that returns the filename of the
currently executing script.
So, the $_SERVER["PHP_SELF"] sends the submitted form data to the page itself, instead
of jumping to a different page. This way, the user will get error messages on the same page as the
form.
htmlspecialchars() function
The htmlspecialchars() function converts special characters to HTML entities. This means
that it will replace HTML characters like < and > with < and >. This prevents attackers from
exploiting the code by injecting HTML or Javascript code (Cross-site Scripting attacks) in forms.
<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
}
if (empty($_POST["website"])) {
$website = "";
} else {
$website = test_input($_POST["website"]);
}
if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}
if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
$gender = test_input($_POST["gender"]);
}
}
?>
Example:
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
E-mail:
<input type="text" name="email">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Website:
<input type="text" name="website">
<span class="error"><?php echo $websiteErr;?></span>
<br><br>
Comment: <textarea name="comment" rows="5" cols="40"></textarea>
<br><br>
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<input type="radio" name="gender" value="other">Other
<span class="error">* <?php echo $genderErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
The next step is to validate the input data, that is "Does the Name field contain only letters
and whitespace?", and "Does the E-mail field contain a valid e-mail address syntax?", and if filled
out, "Does the Website field contain a valid URL?".
$name = test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z-' ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
Here the preg_match() function searches for pattern, returns true if the pattern exists, and false
otherwise.
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
$website = test_input($_POST["website"]);
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-
9+&@#\/%=~_|]/i",$website)) {
$websiteErr = "Invalid URL";
}
Example:
<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z-' ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["website"])) {
$website = "";
} else {
$website = test_input($_POST["website"]);
// check if URL address syntax is valid (this regular expression also allows dashes in the
URL)
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-
9+&@#\/%=~_|]/i",$website)) {
$websiteErr = "Invalid URL";
}
}
if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}
if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
$gender = test_input($_POST["gender"]);
}
}
?>
Output:
To show the values in the input fields after the user hits the submit button, we add a little PHP script
inside the value attribute of the following input fields: name, email, and website. In the comment textarea
field, we put the script between the <textarea> and </textarea> tags. The little script outputs the value of
the $name, $email, $website, and $comment variables.
Then, we also need to show which radio button that was checked. For this, we must manipulate the
checked attribute (not the value attribute for radio buttons):
Assume we have a text file called "webdictionary.txt", stored on the server, that looks like this:
AJAX = Asynchronous JavaScript and XML
CSS = Cascading Style Sheets
HTML = Hyper Text Markup Language
PHP = PHP Hypertext Preprocessor
SQL = Structured Query Language
SVG = Scalable Vector Graphics
XML = EXtensible Markup Language
The PHP code to read the file and write it to the output buffer is as follows (the readfile() function
returns the number of bytes read on success):
Example
<?php
echo readfile("webdictionary.txt");
?>
Result:
AJAX = Asynchronous JavaScript and XML CSS = Cascading Style Sheets HTML = Hyper
Text Markup Language PHP = PHP Hypertext Preprocessor SQL = Structured Query Language
SVG = Scalable Vector Graphics XML = EXtensible Markup Language236
PHP File Open/Read/Close - To open, read, and close a file on the server
PHP Open File - fopen()
A better method to open files is with the fopen() function. This function gives you more
options than the readfile() function. The first parameter of fopen() contains the name of the file to be
opened and the second parameter specifies in which mode the file should be opened. The following
example also generates a message if the fopen() function is unable to open the specified file:
Modes Description
r Open a file for read only. File pointer starts at the beginning of the file
w Open a file for write only. Erases the contents of the file or creates a new file if it
doesn't exist. File pointer starts at the beginning of the file
a Open a file for write only. The existing data in file is preserved. File pointer starts at
the end of the file. Creates a new file if the file doesn't exist
x Creates a new file for write only. Returns FALSE and an error if file already exists
r+ Open a file for read/write. File pointer starts at the beginning of the file
w+ Open a file for read/write. Erases the contents of the file or creates a new file if it
doesn't exist. File pointer starts at the beginning of the file
a+ Open a file for read/write. The existing data in file is preserved. File pointer starts at
the end of the file. Creates a new file if the file doesn't exist
x+ Creates a new file for read/write. Returns FALSE and an error if file already exists
Note: After a call to the fgets() function, the file pointer has moved to the next line.
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. The example below reads the "webdictionary.txt" file line by line,
until end-of-file is reached:
Example:
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
// Output one line until end-of-file
while(!feof($myfile)) {
echo fgets($myfile) . "<br>";
}
fclose($myfile);
?>
Example (1) User sends a request for page at www.example.com for the first time. page
request
Example (2) Server sends back the page html to the browser AND stores some data in a
cookie on the user’s PC. html cookie data
Example (3) At the next page request for domain www.example.com, all cookie data
associated with this domain is sent too. page request cookie data
Destroying a Session
• The unset() function is used to free the specified session variable.
<?php
unset($_SESSION[views]);
?>
• You can also completely destroy the session by calling the session_destroy() function:
<?php
session_destroy();
?>
• session_destroy() will reset your session and you will lose all your stored session data.
Cookies vs. Sessions
Cookies Sessions
• Sanitization
Unlike validation, sanitization will sanitize data so as to ensure that no undesired characters
by removing or altering the data
Example passing in FILTER_SANITIZE_EMAIL will remove all the characters that are
inappropriate for an email address to contain. That said, it does not validate the data
Example PHP program to validate
Program to validate URL using FILTER_VALIDATE_URL filter
<?php
// PHP program to validate URL
// Error message
$errorMsg = 'Error on line '.$this->getLine().
' in '.$this->getFile()
.$this->getMessage().' is number zero';
return $errorMsg;
}
}
function demo($a) {
try {
// Check if
if($a == 0) {
throw new myException($a);
}
}
set_exception_handler('exception_handler');
• a PHP script can connect to a DBMS anywhere in the world, so long as it is connected to
the internet
Create a PHP page to save data from HTML form to your MySQL database
• The contact HTML form action is on “contact.php” page. On this page, we will write code
for inserting records into the database.
• For storing data in MySQL as records, you have to first connect with the DB. Connecting the
code is very simple. The mysql_connect in PHP is
mysqli_connect.
Example:
$con = mysqli_connect("localhost","your_localhost_database_user",
"your_localhost_database_password","your_localhost_database_db");
Local Host
You need to place value for your localhost username and password. Normally localhost MySQL
database username is root and password blank or root
Example
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Contact Form - PHP/MySQL Demo Code</title>
</head>
<body>
<fieldset>
<legend>Contact Form</legend>
<form name="frmContact" method="post" action="contact.php">
<p>
<label for="Name">Name </label>
<input type="text" name="txtName" id="txtName">
</p>
<p>
<label for="email">Email</label>
<input type="text" name="txtEmail" id="txtEmail">
</p>
<p>
<label for="phone">Phone</label>
<input type="text" name="txtPhone" id="txtPhone">
</p>
<p>
<label for="message">Message</label>
<textarea name="txtMessage" id="txtMessage"></textarea>
</p>
<p> </p>
<p>
<input type="submit" name="Submit" id="Submit" value="Submit">
</p>
</form>
</fieldset>
</body> </html>
QUESTION BANK
S.No Questions (2 Marks) Competence BT Level
How can we access the data sent through the URL Knowledge BTL1
7. with the GET method?