WP Module 3

Download as pdf or txt
Download as pdf or txt
You are on page 1of 107

IIIrd module

• SERVER SIDE SCRIPTING- PHP


Server-side scripting
• A script is a set of instructions. Server-side scripting is a
technique of programming for producing the code which can
run software on the server side, in simple words any scripting or
programming that can run on the web server is known as server-
side scripting. The operations like customization of a website,
dynamic change in the website content, response generation to
the user’s queries, accessing the database, and so on are
performed at the server end.
Server-side scripting languages
• PHP, Python, Ruby, ColdFusion, C#, Java, C++ are Server-side
scripting languages.
Advantages of PHP
• Freely available
• The PHP group provides complete source code free of charge
• Similar syntax to C, Pearl
• Works with many operating systems
• Can be deployed on many web servers
• Interacts with lots of databases
• It is supported by many providers of webhosting
PHP(Hypertext Preprocessor )
PHP is a server scripting language, and a powerful tool for making
dynamic and interactive Web pages.
Characteristics of PHP
Five important characteristics make PHP's practical nature possible −
• Simplicity
• Efficiency
• Security
• Flexibility
• Familiarity
What is PHP?
• PHP is an acronym for "PHP: Hypertext Preprocessor"
• PHP is a widely-used, open source scripting language
• PHP scripts are executed on the server
• PHP is free to download and use
What is a PHP File?
• PHP files can contain text, HTML, CSS, JavaScript, and PHP
code
• PHP code are executed on the server, and the result is returned
to the browser as plain HTML
• PHP files have extension ".php"
What Can PHP Do?
• PHP can generate dynamic page content
• PHP can create, open, read, write, delete, and close files on the
server
• PHP can collect form data
• PHP can send and receive cookies
• PHP can add, delete, modify data in your database
• PHP can be used to control user-access
• PHP can encrypt data
Why PHP?
• PHP runs on various platforms (Windows, Linux, Unix, Mac OS X,
etc.)
• PHP is compatible with almost all servers used today (Apache,
IIS, etc.)
• PHP supports a wide range of databases
• PHP is free. Download it from the official PHP resource: www.
php.net
• PHP is easy to learn and runs efficiently on the server side
PHP 5 Installation
• To start using PHP, you can:
• Find a web host with PHP and MySQL support.
• Install a web server on your own PC, and then install PHP and
MySQL.
Set Up PHP on Your Own PC
• However, if your server does not support PHP, you must:
• install a web server
• install PHP
• install a database, such as MySQL
• The official PHP website (PHP.net) has installation instructions
for PHP: http://php.net/manual/en/install.php
LAMP
• Lamp is an archetypal model of web service solution stacks, named as
an acronym of the names of its original four open source components:
The Linux operating system, the Apache HTTP server, the MySQL
relational database management system(RDBMS) , and the PHP
programming language .
• The Lamb components are mostly interchangeable and not limited to
the original selection .Since its creation the lamb model has been
adapted to the componentry though typically consisting of free and
open source software.
• Originally popularized from the phrase "Linux, Apache, MySQL, and PHP",
the acronym "LAMP" now refers to a generic software stack model.
Apache
• Apache is the most widely used web server software.
Developed and maintained by Apache Software Foundation,
Apache is an open source software available for free. It runs on
67% of all webservers in the world. It is fast, reliable, and secure.
It can be highly customized to meet the needs of many different
environments by using extensions and modules.
MySQL
• MySQL is an open source relational database management
system. It runs as a server and allows multiple users to manage
and create numerous databases. It is a central component in the
LAMP stack of open source web application software that is
used to create websites. LAMP stands for Linux, Apache,
MySQL, and PHP.
How To Install Linux, Apache, MySQL, PHP (LAMP) stack on
Ubuntu
Step One: Install Apache
• Apache is a free open source software which runs over 50% of the world’s web
servers.
• To install apache, open terminal and type in these commands:
• sudo apt-get update
• sudo apt-get install apache2
Step Two: Install MySQL
• MySQL is a powerful database management system used for organizing and
retrieving data
• To install MySQL, open terminal and type in these commands:
• sudo apt-get install mysql-server libapache2-mod-auth-mysql php5-mysql
Step Three: Install PHP
• PHP is an open source web scripting language that is widely use to build dynamic
webpages.
• To install PHP, open terminal and type in this command.
• sudo apt-get install php5 libapache2-mod-php5 php5-mcrypt
• sudo = permits users to execute command as super user
apt-get = Get a package from the Advance Packing Tool (
something like extract a package from a library kind of I believe)
PHP language elements

PHP 5 Syntax
• A PHP script is executed on the server, and the plain HTML result is sent
back to the browser.
• A PHP script can be placed anywhere in the document.
• A PHP script starts with <?php and ends with ?>:
<?php
// PHP code goes here
?>
• The default file extension for PHP files is ".php".
• A PHP file normally contains HTML tags, and some PHP scripting code.
example
<html>
<body>

<h1>My first PHP page</h1>

<?php
echo "Hello World!";
?>

</body>
</html>

• we have an example of a simple PHP file, with a PHP script that uses a built-in PHP function "
echo" to output the text "Hello World!" on a web page:
• PHP statements end with a semicolon (;).
Comments in PHP

• A comment in PHP code is a line that is not read/executed as


part of the program. Its only purpose is to be read by someone
who is looking at the code.
• // This is a single-line comment.
# This is also a single-line comment.
/*
This is a multiple-lines comment block
that spans over multiple
lines.
*/
PHP Data Types
• PHP data types are used to hold different types of data or values. PHP supports 8 primitive
data types that can be categorized further in 3 types:
1. Scalar Types
2. Compound Types
3. Special Types
Scalar Types
• There are 4 scalar data types in PHP.
1) String 2) integer 3)float 4) Boolean
Compound Types
• There are 2 compound data types in PHP.
2) Array 2) object
Special Types
• There are 2 special data types in PHP.
1) Resource 2) NULL
1) PHP 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 = "Hello world!";
$y = 'Hello world!';

echo $x;
echo "<br>";
echo $y;
?>
2) PHP Integer
• Integers are whole numbers, without a decimal point, like 4195.Rules for
integers:
• An integer must have at least one digit
• An integer must not have a decimal point
• An integer can be either positive or negative
• Integers can be specified in three formats: decimal (10-based),
hexadecimal (16-based) or octal (8-based).
In the following example $x is an integer. The PHP var_dump() function
returns the data type and value:
• Example
• <?php
$x = 5985;
var_dump($x);
?>
3)PHP Float
• A float (floating point number) is a number with a decimal point
or a number in exponential form. In the following example $x is
a float. The PHP var_dump() function returns the data type and
value:
• Example
• <?php
$x = 10.365;
var_dump($x);
?>
4)PHP Boolean
• A Boolean represents two possible states: TRUE or FALSE.
• $x = true;
$y = false;
• Booleans are often used in conditional testing.
Compound data types-
1)PHP 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
• <?php
$cars = array("Volvo","BMW","Toyota");
var_dump($cars);
?>
2)PHP Object
An object is a data type which stores data and information on how to process that data. In PHP,
an object must be explicitly declared. First we must declare a class of object.
For this, we use the class keyword. A class is a structure that can contain properties and
methods:
• Example
• <?php
class Car {
function Car() {
$this->model = "VW";
}
}

// create an object
$herbie = new Car();

// show object properties


echo $herbie->model;
?>
Special data types
1. PHP NULL Value: Null is a special data type which can have only
one value: NULL.
2. A variable of data type NULL is a variable that has no value
assigned to it. If a variable is created without a value, it is
automatically assigned a value of NULL.
3. Variables can also be emptied by setting the value to NULL:
• Example
• <?php
$x = "Hello world!";
$x = null;
var_dump($x);
?>
2)PHP Resource
• Resources are special variables that hold references to
resources external to PHP (such as database connections).
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. The correct way
of setting a variable in PHP:
• $var_name = value;
• New PHP programmers often forget the $ sign at the beginning of the
variable. In that case it will not work. Let's try creating a variable with a
string, and a variable with a number:
• <?php
• $txt = "Hello World!";
• $number = 16;
• ?>
PHP is a Loosely Typed Language
• In PHP a variable does not need to be declared before being set.
In the example above, you see that you do not have to tell PHP
which data type the variable.
• PHP automatically converts the variable to the correct data
type, depending on how they are set.
• In a strongly typed programming language, you have to declare
(define) the type and name of the variable before using it .
• In PHP the variable is declared automatically when you use it.
Rules for PHP variables:

• A variable starts with the $ sign, followed by the name of the


variable
• A variable name must start with a letter or the underscore
character
• A variable name cannot start with a number
• A variable name can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _ )
• Variable names are case-sensitive ($age and $AGE are two
different variables)
PHP Variables Scope
• In PHP, variables can be declared anywhere in the script. The
scope of a variable is the part of the script where the variable can
be referenced /used. PHP has three different variable scopes:
• local
• global
• Static
Global and Local Scope
• A variable declared outside a function has a GLOBAL SCOPE and
can only be accessed outside a function:A variable
declared within a function has a LOCAL SCOPE and can only be
accessed within that function:
• PHP The static Keyword
• Normally, when a function is completed/executed, all of its
variables are deleted. However, sometimes we want a local
variable NOT to be deleted. We need it for a further job.
• To do this, use the static keyword when you first declare the
variable: Then, each time the function is called, that variable will
still have the information it contained from the last time the
function was called.
PHP Constants

• Constants are like variables except that once they are defined
they cannot be changed or undefined.
• A constant is an identifier (name) for a simple value. The value
cannot be changed during the script.
• A valid constant name starts with a letter or underscore (no $
sign before the constant name). Unlike variables, constants are
automatically global across the entire script.
• Create a PHP Constant : To create a constant, use the define()
function.
• Syntax
• define(name, value, case-insensitive)
• Parameters:
• name: Specifies the name of the constant
• value: Specifies the value of the constant
• case-insensitive: Specifies whether the constant name should
be case-insensitive. Default is false
PHP Operators
• Operators are used to operate on values. There are four
classifications of operators:
1. Arithmetic
2. Assignment
3. Comparison
4. Logical
Arithmetic Operators
Assignment Operators
Comparison operators
Logical Operators
Control Structures
• PHP Conditional Statements:
• Very often when you write code, you want to perform different actions
for different conditions. You can use conditional statements in your
code to do this.
• In PHP we have the following conditional statements:
• if statement - use this statement to execute some code only if a
specified condition is true.
• if...else statement - use this statement to execute some code if a
condition is true and another code if the condition is false.
• if...elseif....else statement - use this statement to select one of several
blocks of code to be executed.
• switch statement - use this statement to select one of many blocks of
code to be executed.
PHP - The if Statement
The if statement executes some code if one condition is true.
• Syntax
if (condition) {
code to be executed if condition is true;
}
The example below will output "Have a good day!" if the current time (HOUR) is less
than 20:
• Example
<?php
$t = date("H");
if ($t < "20") {
echo "Have a good day!";
}
?>
PHP - The if...else Statement
The if....else statement executes some code if a condition is true and another code if that
condition is false.
• Syntax
if (condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}
The example below will output "Have a good day!" if the current time is less than 20, and "Have a
good night!" otherwise:
• Example
<?php
$t = date("H");

if ($t < "20") {


echo "Have a good day!";
} else {
echo "Have a good night!";
}
?>
PHP - The if...elseif....else Statement
• The if....elseif...else statement executes different codes for more
than two conditions.
• Syntax
• if (condition) {
code to be executed if this condition is true;
} elseif (condition) {
code to be executed if this condition is true;
} else {
code to be executed if all conditions are false;
}
• The example below will output "Have a good morning!" if the current
time is less than 10, and "Have a good day!" if the current time is less
than 20. Otherwise it will output "Have a good night!":
The if...elseif....else Statement
• Example
• <?php
$t = date("H");

if ($t < "10") {


echo "Have a good morning!";
} elseif ($t < "20") {
echo "Have a good day!";
} else {
echo "Have a good night!";
}
?>
PHP - The switch Statement
• Use the switch statement to select one of many blocks of code to be executed.
• switch (expression){
• case label1:
• code to be executed if expression = label1;
• break;
• case label2:
• code to be executed if expression = label2;
• break;
• default:
• code to be executed
• if expression is different
• from both label1 and label2;
•}
• The switch statement works in an unusual way.
• First it evaluates given expression then seeks a lable to match
the resulting value.
• If a matching value is found then the code associated with the
matching label will be executed or if none of the lable matches
then statement will execute any specified default code.
• <html> • case "Fri":
• <body> • echo "Today is Friday";
• <?php • break;
• $d = date("D"); • case "Sat":
• switch ($d){
• echo "Today is Saturday";
• case "Mon":
• break;
• echo "Today is Monday";
• break;
• case "Sun":
• case "Tue": • echo "Today is Sunday";
• echo "Today is Tuesday"; • break;
• break; • default:
• case "Wed": • echo "Wonder which day is
• echo "Today is Wednesday"; this ?";
• break; • }
• case "Thu": • ?>
• echo "Today is Thursday"; • </body>
• break; • </html>
PHP - Loop
• Loops in PHP are used to execute the same block of code a
specified number of times. PHP supports following four loop
types.
• In PHP, we have the following looping statements:
• while - loops through a block of code as long as the specified
condition is true
• do...while - loops through a block of code once, and then repeats
the loop as long as the specified condition is true
• for - loops through a block of code a specified number of times
• foreach - loops through a block of code for each element in an
array
The while loop statement
• The while statement will
execute a block of code if and
as long as a test expression is
true.
• If the test expression is true
then the code block will be
executed. After the code has
executed the test expression
will again be evaluated and the
loop will continue until the test
expression is found to be false.
Syntax- while loop
while (condition) {
code to be executed; }

• Example
This example decrements a variable value on each iteration of
the loop and the counter increments until it reaches 10 when the
evaluation is false and the loop ends.
Example- while loop
• <html>
• <body>
• <?php
• $i = 0;
• $num = 50;
• while( $i < 10) {
• $num--;
• $i++;
• }
• echo ("Loop stopped at i = $i and num = $num" );
• ?>
• </body>
• </html>
output
• This will produce the following result −
• Loop stopped at i = 10 and num = 40
The do...while loop statement
• The do...while statement will execute a block of code at least
once - it then will repeat the loop as long as a condition is true.
• Syntax
• do {
• code to be executed;
•}
• while (condition);
example • <html>
• <body>
• The following example will • <?php
increment the value of i at • $i = 0;
least once, and it will continue
• $num = 0;
incrementing the variable i as
long as it has a value of less • do {
than 10 . • $i++;
• This will produce the •}
following result − • while( $i < 10 );
• Loop stopped at i = 10 • echo ("Loop stopped at i = $i" );
• ?>
• </body>
• </html>
The for loop statement
The for statement is used when you know how many times you
want to execute a statement or a block of statements.
• Syntax
for (initialization; condition; increment){
code to be executed; }
• Parameters:
init counter: Initialize the loop counter value
test counter: Evaluated for each loop iteration. If it evaluates to
TRUE, the loop continues. If it evaluates to FALSE, the loop ends.
increment counter: Increases the loop counter value
The example below displays the numbers from 0 to 10:

• <html> • The number is: 0


<body> The number is: 1
The number is: 2
<?php The number is: 3
for ($x = 0; $x <= 10; $x++) { The number is: 4
echo "The number is: $x <br>"; The number is: 5
} The number is: 6
?> The number is: 7
The number is: 8
</body> The number is: 9
</html> The number is: 10
The PHP foreach Loop
• The foreach loop works only on arrays, and is used to loop
through each key/value pair in an array.
• Syntax
• foreach ($array as $value) {
code to be executed;
}
• For every loop iteration, the value of the current array element is
assigned to $value and the array pointer is moved by one, until it
reaches the last array element.
• The following example demonstrates a loop that will output the
values of the given array ($colors):
example
• <?php
$colors = array("red", "green", "blue", "yellow");

foreach ($colors as $value) {


echo "$value <br>";
}
?>
• output
red
green
blue
yellow
PHP Arrays
• An array stores multiple values in one single variable:
• Example
• <?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
OUTPUT
I like Volvo, BMW and Toyota.
• 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), storing the cars
in single variables could look like this:
• $cars1 = "Volvo";
$cars2 = "BMW";
$cars3 = "Toyota";
PHP- ARRAY
• An array can hold many values under a single name, and you can
access the values by referring to an index number.
Create an Array in PHP
• In PHP, the array() function is used to create an array:
• array();
• In PHP, there are three types of arrays:
• Indexed arrays - Arrays with a numeric index
• Associative arrays - Arrays with named keys
• Multidimensional arrays - Arrays containing one or more arrays
1)PHP Indexed Arrays
• There are two ways to create indexed arrays:
• The index can be assigned automatically (index always starts at
0), like this:
• $cars = array("Volvo", "BMW", "Toyota");
• or the index can be assigned manually:
• $cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";
• The following example creates an indexed array named $cars,
assigns three elements to it, and then prints a text containing
the array values:
Example
• <?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
• Get The Length of an Array - The count() Function
• 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
PHP Associative Arrays
• Associative arrays are arrays that use named keys that you assign to them.
• There are two ways to create an associative array:
• $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
• or:
• $age['Peter'] = "35";
$age['Ben'] = "37";
$age['Joe'] = "43";
• The named keys can then be used in a script:
• Example
• <?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";
?>
Output
Peter is 35 years old.
Loop Through 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
PHP - Multidimensional Arrays
• A multidimensional array is an array containing one or more
arrays.
• PHP understands 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.
PHP Functions
• The real power of PHP comes from its functions; it has more than 1000
built-in functions.
• PHP User Defined Functions
• Besides the built-in PHP functions, we can create our own functions. A
function is a block of statements that can be used repeatedly in a
program. A function will not execute immediately when a page loads. A
function will be executed by a call to the function.
• Create a User Defined Function in PHP
A user defined function declaration starts with the word "function":
• Syntax
function functionName() {
code to be executed;
}
PHP Functions
• A function name can start with a letter or underscore (not a number).
• Function names are NOT case-sensitive.
• In the example below, we create a function named "writeMsg()".
• The opening curly brace ( { ) indicates the beginning of the function code and the
closing curly brace ( } ) indicates the end of the function. The function outputs "
Hello world!". To call the function, just write its name:
• Example
• <?php
function writeMsg() {
echo "Hello world!";
}
writeMsg(); // call the function
?>
PHP Function Arguments
• 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:
PHP Function Arguments
• Example
• <?php
function familyName($fname) {
echo "$fname Refsnes.<br>";
}

familyName("Jani");
familyName("Hege");
familyName("Stale");
familyName("Kai Jim");
familyName("Borge");
?>
• The following example has a function with two arguments ($fname and $year):
• Example
• <?php
function familyName($fname, $year) {
echo "$fname Refsnes. Born in $year <br>";
}

familyName("Hege", "1975");
familyName("Stale", "1978");
familyName("Kai Jim", "1983");
?>
PHP Default Argument Value

• 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($minheight = 50) {
echo "The height is : $minheight <br>";
}
setHeight(350);
setHeight(); // will use the default value of 50
setHeight(135);
setHeight(80);
?>
PHP Functions - Returning values
• To let a function return a value, use the return statement:
• Example
• <?php
function sum($x, $y) {
$z = $x + $y;
return $z;
}

echo "5 + 10 = " . sum(5, 10) . "<br>";


echo "7 + 13 = " . sum(7, 13) . "<br>";
echo "2 + 4 = " . sum(2, 4);
?>
Form Handling
• The PHP superglobals $_GET and $_POST are used to collect form-data.
PHP - A Simple HTML Form
The example below displays a simple HTML form with two input fields and a
submit button:
<html>
<body>

<form action="welcome.php" method="post">


Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>

</body>
</html>
Form Handling
• 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>

Welcome <?php echo $_POST["name"]; ?><br>


Your email address is: <?php echo $_POST["email"]; ?>

</body>
</html>
• The output could be something like this:
Welcome John
Your email address is [email protected]
The same result could also be achieved using the HTTP GET
method:
• <html>
<body>

<form action="welcome_get.php" method="get">


Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>

</body>
</html>
• and "welcome_get.php" looks like this:
• <html>
<body>

Welcome <?php echo $_GET["name"]; ?><br>


Your email address is: <?php echo $_GET["email"]; ?>

</body>
</html>
PHP 5 Form Validation
The validation rules for the form above
are as follows:
• 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:
• Name: <input type="text" name="name">
E-mail: <input type="text" name="email">
Website: <input type="text" name="website">
Comment: <textarea name="comment" rows="5" cols="40"></
textarea>
• 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
PHP 5 Sessions
• What is a PHP Session?
• A session is a way to store information (in variables) to be used
across multiple pages.
• When you work with an application, you open it, do some
changes, and then you close it. This is much like a Session. The
computer knows who you are. It knows when you start the
application and when you end. But on the internet there is one
problem: the web server does not know who you are or what you
do, because the HTTP address doesn't maintain state.
• Session variables solve this problem by storing user information
to be used across multiple pages (e.g. username, favorite color,
etc). By default, Sessions end when the user closes the browser,
or when the web server deletes the session information.
Start a PHP Session
• A session is started with the session_start() function.
• Session variables are set with the PHP global variable: $_SESSION.
• Now, let's create a new page called "demo_session1.php". In this page, we start a new PHP
session and set some session variables:
• <?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>

</body>
</html>
PHP - Cookies
• Cookies are text files stored on the client computer and they are
kept of use tracking purpose. PHP transparently supports HTTP
cookies.
• There are three steps involved in identifying returning users −
• Server script sends a set of cookies to the browser. For example
name, age, or identification number etc.
• Browser stores this information on local machine for future use.
• When next time browser sends any request to web server then it
sends those cookies information to the server and server uses
that information to identify the user.
Setting Cookies with PHP
• PHP provided setcookie() function to set a cookie. This function
requires upto six arguments and should be called before <html>
tag. For each cookie this function has to be called separately.
setcookie(name, value, expire, path, domain, security);
Here is the detail of all the arguments :
• Name − This sets the name of the cookie and is stored in an
environment variable called HTTP_COOKIE_VARS. This variable is
used while accessing cookies.
• Value − This sets the value of the named variable and is the
content that you actually want to store.
• Expiry − This specify a future time in seconds since 00:00:00
GMT on 1st Jan 1970. After this time cookie will become
inaccessible. If this parameter is not set then cookie will
automatically expire when the Web Browser is closed.
• Path − This specifies the directories for which the cookie is
valid. A single forward slash character permits the cookie to be
valid for all directories.
• Domain − This can be used to specify the domain name in very
large domains and must contain at least two periods to be valid.
• Security − This can be set to 1 to specify that the cookie should
only be sent by secure transmission using HTTPS otherwise set
to 0 which mean cookie can be sent by regular HTTP.
Following example will create two cookies name and age these cookies will
be expired after one hour.

• <?php
• setcookie("name", "John Watkin", time()+3600, "/","", 0);
• setcookie("age", "36", time()+3600, "/", "", 0);
• ?>
• <html>
• <head>
• <title>Setting Cookies with PHP</title>
• </head>
• <body>
• <?php echo "Set Cookies"?>
• </body>
• </html>
Accessing Cookies with PHP
• PHP provides many ways to access cookies. Simplest way is to use either $_COOKIE or
$HTTP_COOKIE_VARS variables. Following example will access all the cookies set in above example.
• <html>
• <head>
• <title>Accessing Cookies with PHP</title>
• </head>
• <body>
• <?php
• echo $_COOKIE["name"]. "<br />";
• /* is equivalent to */
• echo $HTTP_COOKIE_VARS["name"]. "<br />";
• echo $_COOKIE["age"] . "<br />";
• /* is equivalent to */
• echo $HTTP_COOKIE_VARS["age"] . "<br />";
• ?>
• </body>
• </html>
Deleting Cookie with PHP
• Officially, to delete a cookie you should call setcookie() with the name argument
only but this does not always work well, however, and should not be relied on.
• It is safest to set the cookie with a date that has already expired −
• <?php
• setcookie( "name", "", time()- 60, "/","", 0);
• setcookie( "age", "", time()- 60, "/","", 0);
• ?>
• <html>
• <head>
• <title>Deleting Cookies with PHP</title>
• </head>
• <body>
• <?php echo "Deleted Cookies" ?>
• </body>
• </html>
PHP 5 File Handling
The PHP code to read the file and write it to the
output buffer is as follows
• <!DOCTYPE html> • AJAX = Asynchronous
<html> JavaScript and XML CSS =
<body> Cascading Style Sheets HTML
= Hyper Text Markup
<?php Language PHP = PHP
echo readfile("webdictionary. Hypertext Preprocessor SQL =
txt"); Structured Query Language
?> SVG = Scalable Vector
Graphics XML = EXtensible
</body> Markup Language
</html>
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.
• We will use the text file, "webdictionary.txt",
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 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:
Example AJAX = Asynchronous JavaScript and XML
CSS = Cascading Style Sheets HTML =
Hyper Text Markup Language PHP = PHP
Hypertext Preprocessor SQL = Structured
• <!DOCTYPE html> Query Language SVG = Scalable Vector
Graphics XML = EXtensible Markup
<html> Language
<body>

<?php
$myfile = fopen("webdictionary.txt", "r")
or die("Unable to open file!");
echo fread($myfile,filesize("
webdictionary.txt"));
fclose($myfile);
?>

</body>
</html>
The file may be opened in one of the following modes:
PHP Read File - fread()
• The fread() function reads from an open file.
• The first parameter of fread() contains the name of the file to
read from and the second parameter specifies the maximum
number of bytes to read.
• The following PHP code reads the "webdictionary.txt" file to the
end:
• fread($myfile,filesize("webdictionary.txt"));
PHP Close File - fclose()
• The fclose() function is used to close an open file. The fclose()
requires the name of the file (or a variable that holds the
filename) we want to close:
• <?php
$myfile = fopen("webdictionary.txt", "r");
// some code to be executed....
fclose($myfile);
?>
PHP Read Single Line - fgets()
• The fgets() function is used to read a single line from a file.
• The example below outputs the first line of the "webdictionary.
txt" file:
• <?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open
file!");
echo fgets($myfile);
fclose($myfile);
?>
PHP Check End-Of-File - feof()
• 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.
• PHP Read Single Character - fgetc():
• The fgetc() function is used to read a single character from a file.
• PHP Create File - fopen():
• The fopen() function is also used to create a file. Maybe a little
confusing, but in PHP, a file is created using the same function used
to open files.
PHP Write to File - fwrite()
• The fwrite() function is used to write to a file. The first parameter
of fwrite() contains the name of the file to write to and the second
parameter is the string to be written.
• <?php
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$txt = "John Doe\n";
fwrite($myfile, $txt);
$txt = "Jane Doe\n";
fwrite($myfile, $txt);
fclose($myfile);
?>
• Notice that we wrote to the file "newfile.txt" twice. Each time we
wrote to the file we sent the string $txt that first contained "John
Doe" and second contained "Jane Doe". After we finished writing,
we closed the file using the fclose() function.
• If we open the "newfile.txt" file it would look like this:
• John Doe
Jane Doe
PHP 5 File Upload
• A PHP script can be used with a HTML form to allow users to
upload files to the server. Initially files are uploaded into a
temporary directory and then relocated to a target destination by
a PHP script.
• Information in the phpinfo.php page describes the temporary
directory that is used for file uploads as upload_tmp_dir and the
maximum permitted size of files that can be uploaded is stated
as upload_max_filesize. These parameters are set into PHP
configuration file php.ini
The process of uploading a file follows these steps −
• The user opens the page containing a HTML form featuring a text
files, a browse button and a submit button.
• The user clicks the browse button and selects a file to upload from
the local PC.
• The full path to the selected file appears in the text filed then the user
clicks the submit button.
• The selected file is sent to the temporary directory on the server.
• The PHP script that was specified as the form handler in the form's
action attribute checks that the file has arrived and then copies the
file into an intended directory.
• The PHP script confirms the success to the user.
• An uploaded file could be a text file or image file or any document.
Create The HTML Form
• <!DOCTYPE html>
<html>
<body>

<form action="upload.php" method="post" enctype="multipart/form-data">


Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>

</body>
</html>
• Some rules to follow for the HTML form above:
• Make sure that the form uses method="post"
• The form also needs the following attribute: enctype="multipart/form-
data". It specifies which content-type to use when submitting the form
• Without the requirements above, the file upload will not work.
• Other things to notice:
• The type="file" attribute of the <input> tag shows the input field as a file-
select control, with a "Browse" button next to the input control
• The form above sends data to a file called "upload.php", which we will
create next.
Create The Upload File PHP Script
• The "upload.php" file contains the code for uploading a file:
• <?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
?>
PHP script explained:
• $target_dir = "uploads/" - specifies the directory where the file is
going to be placed
• $target_file specifies the path of the file to be uploaded
• $uploadOk=1 is not used yet (will be used later)
• $imageFileType holds the file extension of the file (in lower case)
• Next, check if the image file is an actual image or a fake image
END

You might also like