0% found this document useful (0 votes)
82 views27 pages

Unit-3 PHP

The document provides an overview of web application development using PHP, focusing on form elements such as text fields, buttons, and file uploads. It explains various input controls, methods for submitting data (GET and POST), and managing cookies and sessions. Additionally, it includes examples of HTML form syntax and PHP code for handling file uploads and form submissions.

Uploaded by

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

Unit-3 PHP

The document provides an overview of web application development using PHP, focusing on form elements such as text fields, buttons, and file uploads. It explains various input controls, methods for submitting data (GET and POST), and managing cookies and sessions. Additionally, it includes examples of HTML form syntax and PHP code for handling file uploads and form submissions.

Uploaded by

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

Shree Swaminarayan College Of Computer Science,Sardarnagar Bhavnagar

Unit-3
[Web Application Development Using PHP]

Topic:
1. Form elements- TextBox, TextArea,Password,RadioButton, Check Box, Combo Box, Image
2. Buttons – Submit and Reset
3. Uploading File to web server
4. POST & GET method
5. PHP include and require statement
6. Basic of Cookie-Setting Cookies, Accessing Cookies, Deleting Cookies.
7. Basic of Session- Starting a Session, Destroying a session

Created By :Professor Mr.Ravi Kukadiya Page 1


Shree Swaminarayan College Of Computer Science,Sardarnagar Bhavnagar
Unit-3
[Web Application Development Using PHP]

❖ Form and forms elements :

✓ An HTML form is a section of a document which contains controls such as text fields,
password fields, checkboxes, radio buttons, submit button, menus etc.
✓ An HTML form facilitates the user to enter data that is to be sent to the server for
processing such as name, email address, password, phone number, etc.
✓ HTML forms are required if you want to collect some data from of the site visitor.
✓ For example: If a user wants to purchase some items on internet, he/she must fill the form
such as shipping address and credit/debit card details so that item can be sent to the given
address.

➢ Form Syntax

<form action="server url" method="get|post">


//input controls e.g. textfield, textarea, radiobutton, button
</form>

➢ HTML <form> element


✓ The HTML <form> element provide a document section to take input from user. It
provides various interactive controls for submitting information to web server such as
text field, text area, password field, etc.

Note: The <form> element does not itself create a form but it is container to contain all
required form elements, such as <input>, <label>, etc.

➢ <input> element:
✓ The HTML <input> element is fundamental form element. It is used to create form fields,
to take input from user. We can apply different input filed to gather different information
form user. Following is the example to show the simple text input.

Example:
<body>
<form>
Enter your name <br>
<input type="text" name="username">
</form>
</body>

Output:
Created By :Professor Mr.Ravi Kukadiya Page 2
Shree Swaminarayan College Of Computer Science,Sardarnagar Bhavnagar
Unit-3
[Web Application Development Using PHP]

➢ TextField Control
✓ The type="text" attribute of input tag creates textfield control also known as single line
textfield control. The name attribute is optional, but it is required for the server side
component such as JSP, ASP, PHP etc.

Example:
<form>
First Name: <input type="text" name="firstname"/> <br/>
Last Name: <input type="text" name="lastname"/> <br/>
</form>

Output:

✓ Note: If you will omit 'name' attribute then the text filed input will not be submitted to
server.

➢ <textarea> tag in form

✓ The <textarea> tag in HTML is used to insert multiple-line text in a form. The size of
<textarea> can be specify either using "rows" or "cols" attribute or by CSS.

Created By :Professor Mr.Ravi Kukadiya Page 3


Shree Swaminarayan College Of Computer Science,Sardarnagar Bhavnagar
Unit-3
[Web Application Development Using PHP]

Example:
<!DOCTYPE html>
<html>
<head>
<title>Form in HTML</title>
</head>
<body>
<form>
Enter your address:<br>
<textarea rows="2" cols="20"></textarea>
</form>
</body>
</html>
Output:

➢ Password Field Control


✓ The password is not visible to the user in password field control.
<form>
<label for="password">Password: </label>
<input type="password" id="password" name="password"/> <br/>
</form>
Output:

Created By :Professor Mr.Ravi Kukadiya Page 4


Shree Swaminarayan College Of Computer Science,Sardarnagar Bhavnagar
Unit-3
[Web Application Development Using PHP]

➢ Radio Button Control


✓ The radio button is used to select one option from multiple options. It is used for
selection of gender, quiz questions etc.
✓ If you use one name for all the radio buttons, only one radio button can be selected at a
time.
✓ Using radio buttons for multiple options, you can only choose a single option at a time.

Example:

<form>
<label for="gender">Gender: </label>
<input type="radio" id="gender" name="gender" value="male"/>Male
<input type="radio" id="gender" name="gender" value="female"/>Female <br/>
</form>

Output:

➢ Checkbox Control
✓ The checkbox control is used to check multiple options from given checkboxes.
<form>
Hobby:<br>

Created By :Professor Mr.Ravi Kukadiya Page 5


Shree Swaminarayan College Of Computer Science,Sardarnagar Bhavnagar
Unit-3
[Web Application Development Using PHP]

<input type="checkbox" id="cricket" name="cricket" value="cricket"/>


<label for="cricket">Cricket</label> <br>
<input type="checkbox" id="football" name="football" value="football"/>
<label for="football">Football</label> <br>
<input type="checkbox" id="hockey" name="hockey" value="hockey"/>
<label for="hockey">Hockey</label>
</form>
Note: These are similar to radio button except it can choose multiple options at a time and radio
button can select one button at a time, and its display.

Output:

➢ Submit button control


✓ HTML <input type="submit"> are used to add a submit button on web page. When
user clicks on submit button, then form get submit to the server.
Syntax:
<input type="submit" value="submit">

✓ The type = submit , specifying that it is a submit button


✓ The value attribute can be anything which we write on button on web page.
✓ The name attribute can be omit here.
Example:
<form>

Created By :Professor Mr.Ravi Kukadiya Page 6


Shree Swaminarayan College Of Computer Science,Sardarnagar Bhavnagar
Unit-3
[Web Application Development Using PHP]

<label for="name">Enter name</label><br>


<input type="text" id="name" name="name"><br>
<label for="pass">Enter Password</label><br>
<input type="Password" id="pass" name="pass"><br>
<input type="submit" value="submit">
</form>
Output:

➢ Combobox Control:
✓ A select box, also called drop down box which provides option to list down various
options in the form of drop-down list, from where a user can select one or more options.
Example
✓ Here is example HTML code for a form with one drop down box
<!DOCTYPE html>
<html>
<head>
<title>Select Box Control</title>
</head>
<body>
<form>
<select name = "dropdown">
<option value = "Maths" selected>Maths</option>
<option value = "Physics">Physics</option>
</select>
</form>
</body>

Created By :Professor Mr.Ravi Kukadiya Page 7


Shree Swaminarayan College Of Computer Science,Sardarnagar Bhavnagar
Unit-3
[Web Application Development Using PHP]

</html>
Output:

➢ Image Button
✓ The image buttons in the HTML document can be created by using the type attribute of
an <input> element. Image buttons also perform the same function as submit buttons, but
the only difference between them is that you can keep the image of your choice as a
button.
Syntax
<input type="image" name="Name of image button" src="Path of the Image file? border
="Specfiy Image Border”>
Example:
<p>Sign in to your account:</p>
<div>
<label for="userId">User ID</label>
<input type="text" id="userId" name="userId" />
</div>
<input type="image" id="image" alt="Login" src="/media/examples/login-button.png"
/>

❖ Buttons – Submit and Reset


➢ Button:
✓ The <input type="submit"> defines a submit button which submits all form values to a form-
handler.

Created By :Professor Mr.Ravi Kukadiya Page 8


Shree Swaminarayan College Of Computer Science,Sardarnagar Bhavnagar
Unit-3
[Web Application Development Using PHP]

✓ The form-handler is typically a server page with a script for processing the input data.
✓ The form-handler is specified in the form's action attribute.
Syntax:
<input type="submit" name=”name of button” value=”value of button”>
Example
✓ An HTML form with two input fields; one text field and one submit button:
<form action="/action_page.php">
<label for="username">Username: </label>
<input type="text" id="username" name="username"><br>
<input type="submit" value="Submit">
</form>
Output:

Reset:
✓ The <input type="reset"> defines a reset button which resets all form values to its initial
values.
✓ Tip: Avoid reset buttons in your forms! It is frustrating for users if they click them by
mistake.
Syntax
<input type="reset" name=”Clear” value=”Rest”>
Output:

Created By :Professor Mr.Ravi Kukadiya Page 9


Shree Swaminarayan College Of Computer Science,Sardarnagar Bhavnagar
Unit-3
[Web Application Development Using PHP]

❖ Uploading File to web server


✓ PHP allows you to upload single and multiple files through few lines of code only.
✓ PHP file upload features allows you to upload binary and text files both. Moreover, you can
have the full control over the file to be uploaded through PHP authentication and file
operation functions.
➢ PHP $_FILES
✓ The PHP global $_FILES contains all the information of file. By the help of $_FILES global,
we can get file name, file type, file size, temp file name and errors associated with file.
✓ Here, we are assuming that file name is filename.
• $_FILES['filename']['name']
✓ returns file name.
• $_FILES['filename']['type']
✓ returns MIME type of the file.
• $_FILES['filename']['size']
✓ returns size of the file (in bytes).
• $_FILES['filename']['tmp_name']
✓ returns temporary file name of the file which was stored on the server.
• $_FILES['filename']['error']
✓ returns error code associated with this file.
➢ move_uploaded_file() function
✓ The move_uploaded_file() function moves the uploaded file to a new location. The
move_uploaded_file() function checks internally if the file is uploaded thorough the POST
request. It moves the file if it is uploaded through the POST request.
Syntax
✓ bool move_uploaded_file ( string $filename , string $destination )
➢ PHP File Upload Example
File: uploadform.html
<form action="uploader.php" method="post" enctype="multipart/form-data">
Select File:
<input type="file" name="fileToUpload"/>
<input type="submit" value="Upload Image" name="submit"/>
</form>
File: uploader.php
<?php

Created By :Professor Mr.Ravi Kukadiya Page 10


Shree Swaminarayan College Of Computer Science,Sardarnagar Bhavnagar
Unit-3
[Web Application Development Using PHP]

$target_path = "e:/";
$target_path = $target_path.basename( $_FILES['fileToUpload']['name']);
if(move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $target_path)) {
echo "File uploaded successfully!";
} else{
echo "Sorry, file not uploaded, please try again!";
}
?>
❖ Write a php file to upload following Restriction
✓ Allow file types only .jpg,.jpeg and .png
✓ File shoud not be larger than 25kb
✓ After successfully upload display upload image in web page.
Example:
<?Php
$file_upload="true";
$file_up_size=$_FILES['file_up'][size];
echo $_FILES[file_up][name];
if ($_FILES[file_up][size]>250000)
{
$msg=$msg."Your uploaded file size is more than 250KB so please reduce the file
size and then upload.<BR>";
$file_upload="false";
}

if (!($_FILES[file_up][type] =="image/jpeg" OR $_FILES[file_up][type]


=="image/gif"))
{
$msg=$msg."Your uploaded file must be of JPG or GIF. Other file types are not
allowed<BR>";
$file_upload="false";}

$file_name=$_FILES[file_up][name];
$add="upload/$file_name"; // the path with the file name where the file will be
stored

Created By :Professor Mr.Ravi Kukadiya Page 11


Shree Swaminarayan College Of Computer Science,Sardarnagar Bhavnagar
Unit-3
[Web Application Development Using PHP]

if($file_upload=="true"){
if(move_uploaded_file ($_FILES[file_up][tmp_name], $add)){
// do your coding here to give a thanks message or any other thing.
}else{echo "Failed to upload file Contact Site admin to fix the problem";}
}else{
echo $msg;
} ?>

❖ POST & GET method


✓ PHP provides two methods through which a client (browser) can send information to the
server. These methods are given below, and discussed in detail:

1. GET method
2. POST method

✓ Get and Post methods are the HTTP request methods used inside the <form> tag to send form
data to the server.
✓ HTTP protocol enables the communication between the client and the server where a browser
can be the client, and an application running on a computer system that hosts your website
can be the server.
➢ GET method
✓ The GET method is used to submit the HTML form data. This data is collected by the
predefined $_GET variable for processing.
✓ The information sent from an HTML form using the GET method is visible to everyone in
the browser's address bar, which means that all the variable names and their values will be
displayed in the URL. Therefore, the get method is not secured to send sensitive information.
For Example

localhost/gettest.php?username=Harry&bloodgroup=AB+

✓ The bold part in the above URL is the variables name and italic part contains the values for
their corresponding variable.
✓ Note that only a limited amount of information can be sent using the GET method.
✓ With the help of an example, let's understand how the GET method works-
Example
✓ The below code will display an HTML form containing two input fields and a submit button.
In this HTML form, we used the method = "get" to submit the form data.

Created By :Professor Mr.Ravi Kukadiya Page 12


Shree Swaminarayan College Of Computer Science,Sardarnagar Bhavnagar
Unit-3
[Web Application Development Using PHP]

file: test1.html
<html>
<body>
<form action = "gettest.php" method = "GET">
Username: <input type = "text" name = "username" /> <br>
Blood Group: <input type = "text" name = "bloodgroup" /> <br>
<input type = "submit" />
</form>
</body>
</html>

✓ Create gettest.php file, which will accept the data sent by HTML form.

file: gettest.php

<html>
<body>
Welcome <?php echo $_GET["username"]; ?> </br>
Your blood group is: <?php echo $_GET["bloodgroup"]; ?>
</body>
</html>
✓ When the user will click on Submit button after filling the form, the URL sent to the server
could look something like this:

localhost/gettest.php?username=Harry&bloodgroup=AB-

The output will look like the below output:


Welcome Harry
Your blood group is: AB-

➢ Advantages of GET method (method = "get")

Created By :Professor Mr.Ravi Kukadiya Page 13


Shree Swaminarayan College Of Computer Science,Sardarnagar Bhavnagar
Unit-3
[Web Application Development Using PHP]

✓ You can bookmark the page with the specific query string because the data sent by the GET
method is displayed in URL.
✓ GET requests can be cached.
✓ GET requests are always remained in the browser history.
➢ Disadvantages of GET Method
✓ The GET method should not be used while sending any sensitive information.
✓ A limited amount of data can be sent using method = "get". This limit should not exceed
2048 characters.
✓ For security reasons, never use the GET method to send highly sensitive information like
username and password, because it shows them in the URL.
✓ The GET method cannot be used to send binary data (such as images or word documents) to
the server.
➢ POST method
✓ Similar to the GET method, the POST method is also used to submit the HTML form data.
But the data submitted by this method is collected by the predefined superglobal
variable $_POST instead of $_GET.
✓ Unlike the GET method, it does not have a limit on the amount of information to be sent. The
information sent from an HTML form using the POST method is not visible to anyone.

For Example
localhost/posttest.php

✓ Note that the "post" method is more secure than the "get" method because the data sent using
the POST method is not visible to user.

With the help of an example, let's understand how the POST method works-

Example
✓ The below code will display an HTML form containing two input fields and a submit button.
In this HTML form, we used the method = "post" to submit the form data.

file: test2.html

<html>
<body>
<form action = "posttest.php" method = "post">
Username: <input type = "text" name = "username" /> <br>
Blood Group: <input type = "text" name = "bloodgroup" /> <br>
<input type = "submit" />

Created By :Professor Mr.Ravi Kukadiya Page 14


Shree Swaminarayan College Of Computer Science,Sardarnagar Bhavnagar
Unit-3
[Web Application Development Using PHP]

</form>
</body>
</html>

✓ Now create posttest.php file to accept the data sent by HTML form.

file: posttest.php

<html>
<body>

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


Your blood group is: <?php echo $_POST["bloodgroup"]; ?>
</body>
</html>
✓ When the user will click on Submit button after filling the form, the URL sent to the server
could look something like this:

localhost/posttest.php

✓ The output will look like the below output:


Welcome Harry
Your blood group is: O+
➢ Advantages of POST method (method = "post")
✓ The POST method is useful for sending any sensitive information because the information
sent using the POST method is not visible to anyone.
✓ There is no limitation on size of data to be sent using the POST Method. You can send a
large amount of information using this method.
✓ Binary and ASCII data can also be sent using the POST method.

Created By :Professor Mr.Ravi Kukadiya Page 15


Shree Swaminarayan College Of Computer Science,Sardarnagar Bhavnagar
Unit-3
[Web Application Development Using PHP]

✓ Data security depends on the HTTP protocol because the information sent using the POST
method goes through the HTTP header. By using secure HTTP, you can ensure that your data
is safe.
➢ Disadvantages of POST Method
✓ POST requests do not cache.
✓ POST requests never remain in the browser history.
✓ It is not possible to bookmark the page because the variables are not displayed in URL.

Created By :Professor Mr.Ravi Kukadiya Page 16


Shree Swaminarayan College Of Computer Science,Sardarnagar Bhavnagar
Unit-3
[Web Application Development Using PHP]

❖ PHP Include and Require


✓ PHP allows us to create various elements and functions, which are used several times in
many pages. It takes much time to script these functions in multiple pages. Therefore, use
the concept of file inclusion that helps to include files in various programs and saves the
effort of writing code multiple times.

✓ "PHP allows you to include file so that a page content can be reused many times. It is
very helpful to include files when you want to apply the same HTML or PHP code to
multiple pages of a website." There are two ways to include file in PHP.
1. include
2. require

➢ Both include and require are identical to each other, except failure.
✓ include only generates a warning, i.e., E_WARNING, and continue the execution of the
script.
✓ require generates a fatal error, i.e., E_COMPILE_ERROR, and stop the execution of the
script.
➢ Advantage
✓ Code Reusability: By the help of include and require construct, we can reuse HTML
code or PHP script in many PHP scripts.
✓ Easy editable: If we want to change anything in webpages, edit the source file included
in all webpage rather than editing in all the files separately.

➢ PHP include
✓ PHP include is used to include a file on the basis of given path. You may use a relative or
absolute path of the file.

Syntax

✓ There are two syntaxes available for include:


include 'filename ';
Or
include ('filename');

Examples
✓ Let's see a simple PHP include example.
File: menu.html

Created By :Professor Mr.Ravi Kukadiya Page 17


Shree Swaminarayan College Of Computer Science,Sardarnagar Bhavnagar
Unit-3
[Web Application Development Using PHP]

<a href="home.php">Home</a> |
<a href="php_std.php">PHP</a> |
<a href="java_std.php">Java</a> |
<a href="html_std.php">HTML</a>
File: include1.php
<?php include("menu.html"); ?>
<h1>This is Main Page</h1>

Output:
Home |
PHP |
Java |
HTML
This is Main Page
➢ PHP require
✓ PHP require is similar to include, which is also used to include files. The only difference
is that it stops the execution of script if the file is not found whereas include doesn't.

Syntax

✓ There are two syntaxes available for require:


require 'filename';
Or
require ('filename');

Examples
✓ Let's see a simple PHP require example.
File: menu.html

<a href="home.php">Home</a> |
<a href="php_std.php">PHP</a> |
<a href="java_std.php">Java</a> |
<a href="html_std.php">HTML</a>
File: require1.php

<?php require("menu.html"); ?>

Created By :Professor Mr.Ravi Kukadiya Page 18


Shree Swaminarayan College Of Computer Science,Sardarnagar Bhavnagar
Unit-3
[Web Application Development Using PHP]

<h1>This is Main Page</h1>

Output:
Home |
PHP |
Java |
HTML
This is Main Page

➢ PHP include vs PHP require


✓ Both include and require are same. But if the file is missing or inclusion
fails, include allows the script to continue but require halts the script producing a fatal
E_COMPILE_ERROR level error.

✓ Let's understand the difference with the help of example:

Example
include.php

<?php
//include welcome.php file
include("welcome.php");
echo "The welcome file is included.";
?>

Output:

✓ The welcome.php file is not available in the same directory, which we have included. So,
it will produce a warning about that missing file but also display the output.
Warning: include(welcome.php): failed to open stream: No such file or directory in
C:\xampp\htdocs\program\include.php on line 3

Warning: include(): Failed opening 'welcome.php' for inclusion


(include_path='C:\xampp\php\PEAR') in C:\xampp\htdocs\program\include.php on
line 3

Created By :Professor Mr.Ravi Kukadiya Page 19


Shree Swaminarayan College Of Computer Science,Sardarnagar Bhavnagar
Unit-3
[Web Application Development Using PHP]

The welcome file is included.


require.php
<?php
echo "HELLO";
//require welcome.php file
require("welcome.php");
echo "The welcome file is required.";
?>

Output:

✓ In case of require() if the file (welcome.php) is not found in the same directory. The
require() will generate a fatal error and stop the execution of the script, as you can see in
the below output.
HELLO
Warning: require(Welcome.php): failed to open stream: No such file or directory in
C:\xampp\htdocs\program\include.php on line 3
Fatal error: require(): Failed opening required 'Welcome.php' (include_path='C:\xampp

❖ Basic of Cookie-Setting Cookies, Accessing Cookies, Deleting 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 −

o Server script sends a set of cookies to the browser. For example name, age, or
identification number etc.
o Browser stores this information on local machine for future use.
o 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.
o This chapter will teach you how to set cookies, how to access them and how to delete
them.
o The Anatomy of a Cookie
o Cookies are usually set in an HTTP header (although JavaScript can also set a cookie
directly on a browser). A PHP script that sets a cookie might send headers that look
something like this –

HTTP/1.1 200 OK

Created By :Professor Mr.Ravi Kukadiya Page 20


Shree Swaminarayan College Of Computer Science,Sardarnagar Bhavnagar
Unit-3
[Web Application Development Using PHP]

Date: Fri, 04 Feb 2000 21:03:38 GMT


Server: Apache/1.3.9 (UNIX) PHP/4.0b3
Set-Cookie: name=xyz; expires=Friday, 04-Feb-07 22:03:38 GMT;
path=/; domain=tutorialspoint.com
Connection: close
Content-Type: text/html
✓ As you can see, the Set-Cookie header contains a name value pair, a GMT date, a path
and a domain. The name and value will be URL encoded. The expires field is an
instruction to the browser to "forget" the cookie after the given time and date.
✓ If the browser is configured to store cookies, it will then keep this information until the
expiry date. If the user points the browser at any page that matches the path and domain
of the cookie, it will resend the cookie to the server.The browser's headers might look
something like this −
GET / HTTP/1.0
Connection: Keep-Alive
User-Agent: Mozilla/4.6 (X11; I; Linux 2.2.6-15apmac ppc)
Host: zink.demon.co.uk:1126
Accept: image/gif, */*
Accept-Encoding: gzip
Accept-Language: en
Accept-Charset: iso-8859-1,*,utf-8
Cookie: name=xyz

✓ A PHP script will then have access to the cookie in the environmental variables
$_COOKIE or $HTTP_COOKIE_VARS[] which holds all cookie names and values.
Above cookie can be accessed using $HTTP_COOKIE_VARS["name"].

➢ 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 −

Created By :Professor Mr.Ravi Kukadiya Page 21


Shree Swaminarayan College Of Computer Science,Sardarnagar Bhavnagar
Unit-3
[Web Application Development Using PHP]

o 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.
o Value − This sets the value of the named variable and is the content that you actually
want to store.
o 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.
o 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.
o Domain − This can be used to specify the domain name in very large domains and must
contain at least two periods to be valid. All cookies are only valid for the host and domain
which created them.
o 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>

Created By :Professor Mr.Ravi Kukadiya Page 22


Shree Swaminarayan College Of Computer Science,Sardarnagar Bhavnagar
Unit-3
[Web Application Development Using PHP]

➢ 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>

✓ You can use isset() function to check if a cookie is set or not.


<html>
<head>
<title>Accessing Cookies with PHP</title>
</head>
<body>
<?php
if( isset($_COOKIE["name"]))
echo "Welcome " . $_COOKIE["name"] . "<br />";

else
echo "Sorry... Not recognized" . "<br />";
?>
</body>
</html>

Created By :Professor Mr.Ravi Kukadiya Page 23


Shree Swaminarayan College Of Computer Science,Sardarnagar Bhavnagar
Unit-3
[Web Application Development Using PHP]

➢ 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>

❖ Basic of Session- Starting a Session, Destroying a session


✓ An alternative way to make data accessible across the various pages of an entire website
is to use a PHP Session.
✓ A session creates a file in a temporary directory on the server where registered session
variables and their values are stored. This data will be available to all pages on the site
during that visit.
✓ The location of the temporary file is determined by a setting in the php.ini file
called session.save_path. Before using any session variable make sure you have setup this
path.

When a session is started following things happen −


o PHP first creates a unique identifier for that particular session which is a random string of
32 hexadecimal numbers such as 3c7foj34c3jj973hjkop2fc937e3443.
o A cookie called PHPSESSID is automatically sent to the user's computer to store unique
session identification string.
o A file is automatically created on the server in the designated temporary directory and
bears the name of the unique identifier prefixed by sess_ ie
sess_3c7foj34c3jj973hjkop2fc937e3443.

Created By :Professor Mr.Ravi Kukadiya Page 24


Shree Swaminarayan College Of Computer Science,Sardarnagar Bhavnagar
Unit-3
[Web Application Development Using PHP]

✓ When a PHP script wants to retrieve the value from a session variable, PHP automatically
gets the unique session identifier string from the PHPSESSID cookie and then looks in its
temporary directory for the file bearing that name and a validation can be done by
comparing both values.
✓ A session ends when the user loses the browser or after leaving the site, the server will
terminate the session after a predetermined period of time, commonly 30 minutes
duration.

➢ Starting a PHP Session


✓ A PHP session is easily started by making a call to the session_start() function.This
function first checks if a session is already started and if none is started then it starts one.
It is recommended to put the call to session_start() at the beginning of the page.
✓ Session variables are stored in associative array called $_SESSION[]. These variables
can be accessed during lifetime of a session.
✓ The following example starts a session then register a variable called counter that is
incremented each time the page is visited during the session.
✓ Make use of isset() function to check if session variable is already set or not.
✓ Put this code in a test.php file and load this file many times to see the result –

<?php
session_start();

if( isset( $_SESSION['counter'] ) ) {


$_SESSION['counter'] += 1;
}else {
$_SESSION['counter'] = 1;
}
$msg = "You have visited this page ". $_SESSION['counter'];
$msg .= "in this session.";
?>
<html>
<head>
<title>Setting up a PHP session</title>
</head>
<body>
<?php echo ( $msg ); ?>
</body>
</html>
✓ It will produce the following result −
You have visited this page 1in this session.

Created By :Professor Mr.Ravi Kukadiya Page 25


Shree Swaminarayan College Of Computer Science,Sardarnagar Bhavnagar
Unit-3
[Web Application Development Using PHP]

➢ Destroying a PHP Session


✓ A PHP session can be destroyed by session_destroy() function. This function does not
need any argument and a single call can destroy all the session variables. If you want to
destroy a single session variable then you can use unset() function to unset a session
variable.
Here is the example to unset a single variable −
<?php
unset($_SESSION['counter']);
?>
Here is the call which will destroy all the session variables −
<?php
session_destroy();
?>
➢ Turning on Auto Session
✓ You don't need to call start_session() function to start a session when a user visits your
site if you can set session.auto_start variable to 1 in php.ini file.
✓ Sessions without cookies
✓ There may be a case when a user does not allow to store cookies on their machine. So
there is another method to send session ID to the browser.
✓ Alternatively, you can use the constant SID which is defined if the session started. If the
client did not send an appropriate session cookie, it has the form
session_name=session_id. Otherwise, it expands to an empty string. Thus, you can
embed it unconditionally into URLs.
✓ The following example demonstrates how to register a variable, and how to link correctly
to another page using SID.
<?php
session_start();
if (isset($_SESSION['counter'])) {
$_SESSION['counter'] = 1;
}else {
$_SESSION['counter']++;
}
$msg = "You have visited this page ". $_SESSION['counter'];
$msg .= "in this session.";
echo ( $msg );
?>
<p>
To continue click following link <br />
<a href = "nextpage.php?<?php echo htmlspecialchars(SID); ?>">
</p>

Created By :Professor Mr.Ravi Kukadiya Page 26


Shree Swaminarayan College Of Computer Science,Sardarnagar Bhavnagar
Unit-3
[Web Application Development Using PHP]

It will produce the following result −


You have visited this page 1in this session.
To continue click following link

✓ The htmlspecialchars() may be used when printing the SID in order to prevent XSS
related attacks.

Created By :Professor Mr.Ravi Kukadiya Page 27

You might also like