0% found this document useful (0 votes)
4 views

Experiment No 10 to 16

The document outlines a series of experiments focused on web form design using HTML and PHP, covering various form controls such as text boxes, radio buttons, check boxes, and buttons. It emphasizes the significance of HTML forms for data collection, explains the GET and POST methods for data submission, and includes practical coding examples. Additionally, it discusses data validation, session management, and cookie handling in PHP, providing exercises for hands-on practice.

Uploaded by

Sami Md
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)
4 views

Experiment No 10 to 16

The document outlines a series of experiments focused on web form design using HTML and PHP, covering various form controls such as text boxes, radio buttons, check boxes, and buttons. It emphasizes the significance of HTML forms for data collection, explains the GET and POST methods for data submission, and includes practical coding examples. Additionally, it discusses data validation, session management, and cookie handling in PHP, providing exercises for hands-on practice.

Uploaded by

Sami Md
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/ 19

Experiment No: 10

Design web page using following form controls.


a) Text box
b) Radio button
c) Check box
d) Button

Resources required:
Hardware Software
Computer System XAMPP

Knowledge required:

Students should know about the designing forms in HTML along with GET and POST
method.

Practical Significance:

HTML Forms are required, when you want to collect some data from the site visitor. For
example, during user registration you would like to collect information such as name,
email address, credit card, etc. A form will take input from the site visitor and then will
post it to a back-end application such as CGI, ASP Script or PHP script etc. The back-
end application will perform required processing on the passed data based on defined
business logic inside the application.

Theoretical Background:

GET Method
This is the built in PHP super global array variable that is used to get values submitted
via HTTP GET method. Data in GET method is sent as URL parameters that are usually
strings of name and value pairs separated by ampersands (&). URL with GET data look
like this:
http://www.abc.com/dataread.php?name=ram&age=20.
The name and age in the URL are the GET parameters; ram and 20 are the value of those
parameters. More than one parameter=value can be embedded in the URL by
concatenating with ampersands (&).

POST Method
This is the built in PHP super global array variable that is used to get values submitted
via HTTP POST method. Data in POST method is sent to the server in a form of a
package in a separate communication with the processing script. User entered
Information is never visible in the URL query string as it is visible in GET. The POST
method can be used to send the much larger amount of data and text data as well as
binary data (uploading a file).
Form Controls
The HTML <form> element defines a form which contains form controls that are used to
collect user input. Example text fields, text area, checkboxes, radio buttons, list, submit
buttons and more.

Text Field
Text Field is used to take a single line input from the user. Text Field will be included in
<form> element of a web page that will be used to take user input, which will be sent to
PHP script available on the server. Data on the server will be fetched by any one of the
super global variable $_GET and $_POST, after receiving it will be processed and the
result will be sent to the user in a form of response.

Text Area

Text Area is used to take multi line input from the user.
Text Area will be included in <form> element of a web page that will be used to take
multi line input like suggestions, address, feedback from users, which will be sent to
PHP script available on the server.Data on the server will be fetched by any one of the
super global variable $_GET and $_POST, after receiving it will be processed and the
result will be sent to user in a form of response.

Radio Button
Radio Button is used to make the user select single choice from a number of available
choices. Radio Button will be included in <form> element of a web page that will be
used single choice input from the user, which will be sent to PHP script available on the
server. Data on the server will be fetched by any of the super global variable $_GET and
$_POST, after receiving it will be processed and the result will be sent to the user in a
form of response.

Check Box
Check Box is used to select one or more options from available options displayed for
selection. Check Box will be displayed as square box which will be activated when
ticked (checked). Check Box will be included in <form> element of a web page that will
be used to take user input, which includes multiple options like hobbies, where user can
select one or more hobby form the multiple hobbies displayed on a web page, which will
be sent to PHP script available on the server.Data on the server will be fetched by any
one of the super global variable $_GET and $_POST, after receiving it will be processed
and the result will be sent to the user in a form of response.

Buttons
Button is created using <button> tag. Text and Image can be displayed on the button by
placing the text or image between the opening and closing tags of button. Buttons has to
be added with actions using JavaScript or by associating the button with a form. In we
are creating button in form <input> tag is used to create a button.
Program Code:
checkboxdemo.html
<html>
<head>
<title> Text Field Demo</title>
</head>
<body>
<form method="get" action="phpcheckboxdemo.php">
<label>Select your Hobbies:</label>
<input type="checkbox" name="cricket" value="Cricket" checked > Cricket
<input type="checkbox" name="football" value="Football"> Football
<input type="checkbox" name="basketball" value="Basket Ball" > Basket Ball
<input type="submit" value="Submit">
</form>
</body>
</html>

New file saved as phpcheckboxdemo.php

<?php
echo "<p>Your Hobbies are : " . $_GET["cricket "] .",". $_GET["football0"] ."," .
$_GET["basketball"] . " </p>";

?>

Output:

Practical related questions:

1.What is the difference between get and post methods?


2. What is the use of isset() function?
Exercise:

1. Write a PHP program that demonstrate form element Text box, Radio button, Check
box, Button.
2. Perform arithmetic operations using text filed and buttons and result should be
displayed on same page (Use PHP_SELF).
3. Perform arithmetic operations using text filed and buttons and result should be
displayed on another page.
Experiment No: 11
Design web page using following form controls.
a) List Box
b) Combo box
c) Hidden field

Resources required:
Hardware Software
Computer System XAMPP

Practical Significance:

HTML Forms are required, when you want to collect some data from the site visitor. For
example, during user registration you would like to collect information such as name,
email address, credit card, etc. A form will take input from the site visitor and then will
post it to a back-end application such as CGI, ASP Script or PHP script etc. The back-end
application will perform required processing on the passed data based on defined business
logic inside the application.

Theoretical Background:

List Box
List Box is used to create drop down list of options. HTML <select> tag will be include
in <form>element of a web page that will be used to display dropdown list where user
can select single or multiple options (when multiple attribute is set), which will be send to
PHP script available on server. The <option> tag will be used in <select> tag in order to
drop list of options. Data on the server will be fetched by any one of the super global
variable $_GET and $_POST, after receiving it will be processed and the result will be
sent to the user as a response.

Hidden Controls
Hidden Controls are used to store the data in a Web page that user can’t see. Hidden
Controls will be included in <form> element of a web page that will be used to store data
that will not be visible to the user, which will be sent to PHP script available on the
server. Data on the server will be fetched by any one of the superglobal variable $_GET
and $_POST, after receiving it will be processed and the result will be sent to the user in a
form of response.

Program Code:
hiddendemo.html
<html>
<head>
<title> Hidden Control Demo</title>
</head>
<body>
<form method="post" action="phphiddendemo.php">
<input type="hidden" name="user_id" id="user_id" value="101">
<input type="submit" value="Submit">
</form>
</body>
</html>

phphiddendemo.php

<?php
if(isset($_POST["user_id"])){
echo "<p>User ID : " . $_POST["user_id"] . "</p>";
}
?>

Output:

Practical related questions:


1. Explain the superglobals in PHP?
2. How does PHP handle forms with multiple selections?
3. How does the form information get from the browser to the server?

Exercise:

1. Write a PHP program that demonstrate form elements List Box, Combo Box.
2. Demonstrates Hidden Fields.
Experiment No: 12
Develop web page with data validation.

Resources required:
Hardware Software
Computer System XAMPP

Practical Significance:

User may by mistakenly submit the data through form with empty fields or in wrong
format. PHP script must ensure that required fields are complete and submitted data is in
valid format. PHP provides some inbuilt function using these functions that input data can
be validated.

Theoretical Background:

 empty() function will ensure that text field is not blank it is with some data, function
accepts a variable as an argument and returns TRUE when the text field is submitted
with empty string, zero, NULL or FALSE value.
 Is_numeric() function will ensure that data entered in a text field is a numeric value, the
function accepts a variable as an argument and returns TRUE when the text field is
submitted with numeric value.
 preg_match() function is specifically used to performed validation for entering text in the
text field, function accepts a “regular expression” argument and a variable as an
argument which has to be in a specific pattern. Typically it is for validating email, IP
address and pin code in a form.
For Example a PHP page formvalidation.php is having three text fields name, mobile number
and email from user, on clicking Submit button a data will be submitted to PHP script
validdata.php on the server, which will perform three different validation on these three text
fields, it will check that name should not be blank, mobile number should be in numeric form
and the email is validated with an email pattern.

Program Code:
formvalidation.php

<html>
<head>
<title> Validating Form Data</title>
</head>
<body>
<form method="post" action="validdata.php">
Name :<input type="text" name="name" id="name" /><br/>
Mobile Number :<input type="text" name="mobileno" id="mobileno" /><br/>
Email ID :<input type="text" name="email" id="email" /><br/>
<input type="submit" name="submit_btn" value="Submit" />
</form>
</body>
</html>

validdata.php

<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if(empty($_POST['name']))
{
echo "Name can't be blank<br/>";
}
if(!is_numeric($_POST['mobileno']))
{
echo "Enter valid Mobile Number<br/>";
}
$pattern ='/\b[\w.-]+@[\w.-]+\.[A-Za-z]{2,6}\b/';
if(!preg_match($pattern,$_POST['email']))
{
echo "Enter valid Email ID.<br/>";
}
}
?>
Output:
Practical related questions:
1. How to validate user input in PHP? Explain
2. Why is the need to validate user input?

Exercise:
1. Write a PHP script to check that emails are valid or not.
Experiment No: 13
Write simple PHP program to
1. Set cookies and read it
2. Demonstrate session management

Resources required:
Hardware Software
Computer System XAMPP

Practical Significance:

PHP cookie is a small piece of information which is stored at client browser. It is used to
recognize the user. PHP session is used to store and pass information from one page to
another temporarily (until user close the website). PHP session technique is widely used
in shopping websites where we need to store and pass cart information e.g. username,
product code, product name, product price etc from one page to another. PHP session
creates unique user id for each browser to recognize the user and avoid conflict between
multiple browsers.

Theoretical Background:
Cookies:
Cookie is created at server side and saved to client browser. Each time when client sends
request to the server, cookie is embedded with request. Such way, cookie can be received
at the server side. In short, cookie can be created, sent and received at server end.
A cookie is a small file with the maximum size of 4KB that the web server stores on the
client computer.
A cookie can only be read from the domain that it has been issued from. Cookies are
usually set in an HTTP header but JavaScript can also set a cookie directly on a browser.

Fig. Cookies
There are three steps involved in identifying returning users :
1. Server script sends a set of cookies to the browser. For example : name, age or
identification number etc.
2. Browser stores this information on local machine for future use.
3. 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.
There are two types of cookies :
1. Session Based which expire at the end of the session.
2. Persistent cookies which are written on hard disk.

PHP provides a inbuilt function setcookie(), that can send appropriate HTTP header to
create the cookie on the browser.
Only name argument is must but it is better to pass value, expires and path to avoid any
ambiguity.
Syntax : setcookie(name, value, expire, path, domain, secure, HttpOnly);

Attributes of Cookie:
Attribute of Description
cookies

Name The unique name is given to a particular cookie.

Value The value of the cookie.

Expires The time when a cookie will get expire. When it reaches to its expiration period cookies is
deleted from browser automatically. If value is set to zero, it will only last till the browser is
running its get deleted when the browser exits.

Path The path where browser to send the cookies back to the server. If the path is specified, it will
only send to specified URL else if it is stored with “/” the cookie will be available for all the
URL’s on the server.

Domain The browser will send the cookie only for URLs within this specified domain. By default is the
server host name.

Secure If this field is set, the cookie will only be sent over https connection. By default it is set to false,
means it is okay to send the cookie over an insecure connection.

HttpOnly This field, if present, tells the browser that it should only make the cookie assessable only to
scripts that run on the Web server (that is, via HTTP). Attempts to access the cookie through
JavaScript will be rejected.

Session:
Session are used to store important information such as the user id more securely on the
server where malicious users cannot temper with them.
To pass values from one page to another.
Sessions are the alternative to cookies on browsers that do not support cookies.
You want to store global variables in an efficient and more secure way compared to
passing them in the URL
You are developing an application such as a shopping cart that has to temporary store
information with a capacity larger than 4KB.
Set Session Variables
<?php
session_start();
$_SESSION["username"] = "abc";
?>
A PHP function session_unset() is used to remove all session variables and
session_destroy() is used to destroy session.

Practical related questions:

1. How to initiate a session in PHP ?


2. How to register a variable in PHP session ?
3. What is the difference between PHP session and Cookie ?
4. What is the difference between session_unregister () and session_unset()?
5. What is the default session time in PHPH?
6. Is it possible to destroy a cookie ()?

Exercise:
1. Write a program that demonstrate use of cookies.
2. Write a PHP program that demonstrate use of session.
Experiment No: 14
Write simple PHP program for sending and receiving plain text messages.

Resources required:
Hardware Software
Computer System XAMPP

Practical Significance:

PHP mail is an inbuilt PHP function which is used to send emails from PHP scripts.
It can also be used to send email, to your newsletter subscribers, password reset links to
users who forget their passwords, activation/confirmation links, registering users and
verifying their email addresses

Theoretical Background:
PHP uses Simple Mail Transmission Protocol (SMTP) to send mail.
Settings of the SMTP mail can be done through “php.ini” file present in the PHP
installation folder.
Any text editor will be used to open and edit “php.ini”file.
Locate [mail function] in the file.
After [mail function]in the file following things will be displayed :
Don’t remove the semi column if you want to work with an SMTP Server like Mercury
; SMTP = localhost;
; smtp_port = 25
Remove the semi colons before SMTP and smtp_port and set the SMTP to your smtp
server and the port to your smtp port. Your settings should look as follows :
SMTP = smtp.example.com
smtp_port = 587
We can get your SMTP settings from your web hosting providers.

PHP Mail
PHP mail is an inbuilt PHP function which is used to send emails from PHP scripts.
It is a cost-effective way of notifying users of important events.
User’s gets contact you via email by providing a contact us form on the website that
emails the provided content.
It can also be used to send email, to your newsletter subscribers, password reset links to
users who forget their passwords, activation/confirmation links, registering users and
verifying their email addresses
Syntax : mail( to, subject, message, headers, parameters );
Parameters Descriptions

To Required. Specifies the receiver or receivers email ids.

Required. Specifies the subject of the email. This parameter cannot contain any newline
Subject
characters.

Required. Defines the message to be sent. Each line should be separated with a (\n). Lines
message
should not exceed 70 characters.

Headers Optional. Specifies additional headers, like From, Cc, and Bcc.

parameters Optional. Additional parameter to the send mail can be mentioned in this section.

Practical related questions:


1. How to send mail in PHP?
2. Explain the different parameters of mail function?
3. Explain SMTP protocol?

Exercise:
1. Write simple PHP program for sending and receiving plain text messages through
mail ( ).
2. Write a steps to send and receive mail.
Experiment No: 15
Develop a simple application to
1. Enter data into database
2. Retrieve and present data from database.

Resources required:
Hardware Software
Computer System XAMPP

Practical Significance:

MySQL is used to manage stored data and is an open source Database Management
Software (DBMS) or Relational Database Management System (RDBMS). PHP and
MySQL are server side technologies, both are used on server side so the combination of
these is preferred to developed cloud based application.
Theoretical Background:
PHP 5 and later can work with a MySQL database using:

MySQLi extension (the "i" stands for improved)


PDO (PHP Data Objects)

The CREATE DATABASE statement is used to create a database in MySQL.


<?php
$servername = "localhost";
$username = "username";
$password = "password";

// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

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

$conn->close();
?>
Create Table SQL query Example
The CREATE TABLE statement is used to create a table in MySQL.
$sql = "CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE
CURRENT_TIMESTAMP
)";

Insert Data SQL query Example


The INSERT INTO statement is used to add new records to a MySQL table:

INSERT INTO table_name (column1, column2, column3,...)


VALUES (value1, value2, value3,...)
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', '[email protected]')";

Select Data from database


The SELECT statement is used to select data from one or more tables:

SELECT column_name(s) FROM table_name


or we can use the * character to select ALL columns from a table:

SELECT * FROM table_name


$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"].
"<br>";
}
} else {
echo "0 results";
}
Program Code:
<?php
$hn = 'localhost';
$db = 'college';
$un = 'root';
$pw = ' ‘;
$conn = new mysqli($hn, $un, $pw, $db);
if ($conn->connect_error) die($conn->connect_error);
$query = "SELECT * FROM student";
$result = $conn->query($query);
if (!$result) die($conn->error);
$rows = $result->num_rows;
for ($j = 0 ; $j < $rows ; ++$j)
{
$result->data_seek($j);
echo 'Roll No.: ' . $result->fetch_assoc()['rollno'] . '<br/>';
$result->data_seek($j);
echo 'Name: ' . $result->fetch_assoc()['name'] . '<br/>';
$result->data_seek($j);
echo 'Percentage: ' . $result->fetch_assoc()['percent'] . '<br/><br/>';
}
$result->close();
$conn->close();
?>

Practical related questions:


1. Which command would you use to view the available databases or tables?
2. How can you view the structure of a table?
3. How is it possible to know the number of rows returned in the result set?
4. Which function returns the number of affected entries by a query?

Exercise:
1. Write a PHP script to enter data in database.
2. Write a PHP script to retrieve and present the data from database.
Experiment No: 16
Develop a simple application to update, delete table data from database.

Resources required:
Hardware Software
Computer System XAMPP

Practical Significance:

MySQL is used to manage stored data and is an open source Database Management
Software (DBMS) or Relational Database Management System (RDBMS). PHP and
MySQL are server side technologies, both are used on server side so the combination of
these is preferred to developed cloud based application.

Theoretical Background:
PHP 5 and later can work with a MySQL database using:

MySQLi extension (the "i" stands for improved)


PDO (PHP Data Objects)

Update Data In a MySQL Table Using MySQLi.


The UPDATE statement is used to update existing records in a table:
UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value
Notice the WHERE clause in the UPDA
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2";


if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}

$conn->close();
?>

Delete Data From a MySQL Table Using MySQLi


The DELETE statement is used to delete records from a table:
$sql = "DELETE FROM MyGuests WHERE id=3";

Practical related questions:


1. Write use of mysql_fetch_row() and mysql_fetch_array().
2. How do you connect to a MySQL database using mysqli?

Exercise:

1. Write a PHP script to update data in database.


2. Write a PHP script to delete the data from database.

You might also like