IWD Lab Manual
IWD Lab Manual
Laboratory Manual
Introduction to Web Development
(DI04007011)
[Computer Engineering ,Semester IV]
Enrolment No
Name
Branch
Academic Term
Institute
Certificate
Place:…………………..
Date:…………………..
Institute’s Mission:
Department’s Vision:
Department’s Mission:
PROGRAMME OUTCOMES (POs)
Following programme outcomes are expected to be achieved through the practical of the course:
CONo CourseOutcomes
CO1 Apply basic PHP syntax and structures to create simple web pages.
CO2 Use PHP functions, arrays, and strings to write efficient code.
CO3 Handle and validate user inputs using forms in PHP.
CO4 Manage user data across multiple pages using sessions and cookies in PHP.
CO5 Connect PHP with the MySQLi Database and perform common database operations.
ASSESSMENT RUBRICS
% of
Criteria Rubrics
point
Excellent (10-8 marks): Completed programs/scripts correctly as per
the requirements.
10
11
12
13
Procedure:
Below steps describes installation of XAMPP on Windows operating system. Steps are
similar for Linux and Mac
ac operating systems.
i. Install XAMPP
1. Open the XAMPP website. Go to [Link] in
your computer's web browser.
4. Because User Account Control (UAC) restricts writing access to the C: drive and
can interfere with the XAMPP installation, it is recommended that this be disabled
for the duration of the installation.
5. After that the start screen of the XAMPP setup wizard should appear
automatically. Click on ‘Next’ to configure the installation settings.
7. In this next step, you have the chance to choose where you’d like the XAMPP
software packet to be installed. If you opt for the standard setup, then a folder with
the name xampp will be created under C:\ for you. After you’ve chosen a location,
click ‘Next’.
10. Once all the preferences have been decided, click to start the installation. The
setup wizard will unpack and install the selected components and save them to the
designated directory. This process may take few minutes.
Introduction to Web Development (DI04007011) [Link](617)
11. Your Firewall may interrupt the installation process to block the some components
of the XAMPP. Use the corresponding check box to enable communication
between the Apache server and your private network or work network. Remember
that making your XAMPP server available for public network networks isn’t
recommended.
12. Once all the components are unpacked and installed, you can close the setup
wizard by clicking on ‘Finish’. Click to tick the corresponding check box and
open the XAMPP Control Panel once the installation process is finished.
13. XAMPP Control Panel provides controls for the individual components of your
xampp test server. The control panel user interface allows you to start or stop
individual modules: Apache, MySQL, FileZilla, Mercury and Tomcat. The
XAMPP Control Panel also offers you various other buttons, including:
Config: allows you to configure the XAMPP as well as the individual components
Netstat: shows all running processes on the local computer
Shell: opens a UNIX shell
Explorer: opens the XAMPP folder in Windows Explorer
Services: shows all services currently running in the background
Help: offers links to user forums
Quit: closes the XAMPP Control Panel
Introduction to Web Development (DI04007011) [Link](617)
14. Individual modules can be started or stopped on the XAMPP Control Panel
through the corresponding buttons under ‘Actions’. You can see which modules
have been started because their names are highlighted green under the ‘Module’
title.
17. You can use the Admin button of your database module to open phpMyAdmin.
Here, you can manage the databases of your web proj
projects
ects that you’re testing on
your XAMPP. Alternatively, you can reach the administration section of your
MySQL database via localhost/phpmyadmin/
20. Now open a web browser and load your PHP page via localhost/test/[Link]. If
your browser
owser window displays the words ‘Hello World’, then you’ve successfully
installed and configured your XAMPP.
ii. Create a web page using PHP that displays a welcome message.
Source Code:
Output:
SIGN OF FACULTY:
8
Introduction to Web Development (DI04007011) G. P., Ahmedabad (617)
Unlike variables, constants are automatically [Link] can be made using the
define() function or const keyword.
9
Introduction to Web Development (DI04007011) G. P., Ahmedabad (617)
Operators:
Operator is a symbol used to perform operations on operands (variables or values).For
example:
$a = $b + 10;
Above code uses arithmetic operator (+) to add 10 to variable $b and assign it to $a.
PHP operators can be categorized into following types:
Arithmetic Operators:
Operator Name Example Description
+ Addition $a + $b Sum of two operands
- Subtraction $a - $b Difference of two operands
* Multiplication $a * $b Multiply tow operands
/ Division $a / $b Quotient of operands
% Modulo $a % $b Reminder of operands
++ Increment $a++ Same as $a = $a + 1
-- Decrement $a-- Same as $a = $a - 1
Assignment Operators:
Operator Name Example Description
$a = $b Value of right operand is assigned to
= Assign
left operand
+= Add then assign $a += $b Same as $a = $a + $b
-= Subtract then assign $a -= $b Same as $a = $a - $b
*= Multiply then assign $a *= $b Same as $a = $a * $b
Divide then assign $a /= $b
/= Same as $a = $a / $b
(Quotient)
Divide then assign $a %= $b
%= Same as $a = $a % $b
(Reminder)
Bitwise Operators:
Operator Name Example Description
$a & $b Bitwise AND operation between $a
& Bitwise AND
and $b
$a | $b Bitwise OR operation between $a and
| Bitwise OR
$b
$a ^ $b Bitwise XOR operation between $a
^ Bitwise XOR
and $b
~ Bitwise NOT ~ $a Bitwise NOT operation on $a
<< Left shift $a << $b Left shift bits of $a by $b steps
>> Right shift $a >> $b Right shift bits of $a by $b steps
10
Introduction to Web Development (DI04007011) G. P., Ahmedabad (617)
Comparison Operators:
Operator Name Example Description
== Equal $a == $b Returns TRUE if $a is equal to $b
!= Not equal $a != $b Returns TRUE if $a is not equal to $b
<> Not equal $a <> $b Returns TRUE if $a is not equal to $b
$a === $b Returns TRUE if $a and $b are equal
=== Identical
and of same data type
$a !== $b Returns TRUE if $a and $b are not
!== Not identical
equal or of different data type
< Less than $a < $b Returns TRUE if $a is less than $b
> Greater than $a > $b Returns TRUE if $a is greater than $b
$a <= $b Returns TRUE if $a is less than or
<= Less than or equal to
equal to $b
Greater than or equal $a >= $b Returns TRUE if $a is greater than or
>=
to equal to $b
$a <=> $b Return -1 if $a is less than $b
<=> Spaceship Return 0 if $a is equal $b
Return 1 if $a is greater than $b
Logical Operators:
Operator Name Example Description
$a and $b Returns TRUE if both $a and $b are
and Logical AND
true
$a or $b Returns TRUE if either $a or $b is
or Logical OR
true
$a xor $b Returns TRUE if either $a or $b is
xor Logical XOR
true, but not both are TRUE
! Logical NOT !$a Returns TRUE if $a is FALSE
$a && $b Returns TRUE if both $a and $b are
&& Logical AND
true
$a || $b Returns TRUE if either $a or $b is
|| Logical OR
true
String Operators:
Operator Name Example Description
. Concatenation $a . $b Concatenate both $a and $b
Concatenation and $a .= $b
.= Same as $a = $a . $b
assign
Expressions
11
Introduction to Web Development (DI04007011) G. P., Ahmedabad (617)
In PHP, anything that has a value is an expression, so most of the statements you write
in PHP scrips are expression. For Example:
$a = $b; // $b is an expression
$a = $b * $c; // $b * $c is an expression
$a = sum($b, $c); // sum($b, $c) is an expression
$b++; // $b++ is an expression
12
Introduction to Web Development (DI04007011) G. P., Ahmedabad (617)
Output:
13
Introduction to Web Development (DI04007011) G. P., Ahmedabad (617)
Output:
14
Introduction to Web Development (DI04007011) G. P., Ahmedabad (617)
Output:
15
Introduction to Web Development (DI04007011) G. P., Ahmedabad (617)
16
Introduction to Web Development (DI04007011) G. P., Ahmedabad (617)
Output:
SIGN OF FACULTY:
17
Practical No. 3:Control & Looping Structures
Prerequisite Theory:
Control Structures (Decision Making Statements):
Controls statements are used to control are used to control the flow of execution of
program based on certain conditions. In PHP, there are following decision making
statements:
if statement
if...else statement
if...elseif...else statement
switch statement
if statement:
if statement allow us to run a block of code if certain condition is true. If condition is
false it will not execute block of code.
if(condition) {
Block of code // statements to execute if condition is
// true
}
if...elsestatement:
if...else executes a block of code if certain condition is true and another block of code if
condition is false.
if(condition) {
Block of code // statements to execute if
// condition is true
}
else {
Block of code // statements to execute if
// condition is false
}
if...elseif...else statement:
It is similar to multiple if...else statements. It executes different blocks of code
based on different conditions.
18
if(condition) {
Block of code // statements to execute if this
// condition is true
}
elseif(condition) {
Block of code // statements to execute if this
// condition is true
} elseif(condition) {
Block of code // statements to execute if this
// condition is true
} else {
Block of code // statements to execute if all
// conditions are false
}
switch statement:
The switch statement is used to perform different actions based on different conditions.
Use the switch statement to select one of many blocks of code to be executed.
switch(n) {
case value1:
code to be executed if n== value1;
break;
case value2:
code to be executed if n== value2;
break;
case value3:
code to be executed if n== value3;
break;
case value4:
code to be executed if n== value4;
break;
......
default:
code to be executed if n != any case;
}
Looping Structures:
Loops in PHP are used to execute the same block of code a specified number of times.
PHP supports below loop statements:
while loop
do...while loop
for loop
foreach loop
while loop:
19
while loop executes a block of code as long as the specified condition is true.
while(condition) {
Block of code // statements to execute
// till condition is true
}
do...while loop:
do...while loop executes a block of code once, and then repeats the loop as long as the
specified condition is true
do {
Block of code // statements to execute till
// condition is true. Executed once
// before checking condition.
} while(condition);
for loop:
for loop executes a block of code a specified number of times.
foreach loop:
foreach loop executes a block of code for each element in an array.
break statement:
break statement is used to terminate the execution of a loop prematurely.
while(condition1) {
Block of code // statements to execute
// till condition1 is true
if(condition2) {
break; // exit while loop is condition2
// is true
}
}
continue statement:
20
continue statement is used to halt the current iteration of a loop and start next iteration
of loop. It does not terminate the loop.
while(condition1) {
if(condition2) {
continue; // if condition2 is true then
// remaining part of the loop will
// not be executed in this
// iteration
}
Block of code // statements to execute
// till condition1 is true
}
Source Code:
21
Output:
2. Write a script to read the marks of 4 subjects and display the result as per the below
instructions:
22
GTU Mark-
GRADE Range
AA 85 - 100
AB 75 - 84
BB 65 - 74
BC 55 - 64
CC 45 - 54
CD 40 - 44
DD 35 - 39
FF < 35 (FAIL)
Each of the four subjects is worth 100 marks.
If a student gets less than 35 marks in any subject, then he/she will be marked as FAIL,
otherwise he/she will be marked as PASS.
The result contains the grades of each individual subject in tabular format as per the
above table.
Source Code:
23
Output:
24
Source Code:
Output:
25
Output:
SIGN OF FACULTY:
26
Practical No. 4: Functions
Prerequisite Theory:
A function is a block of code written in a program to perform some specific task.
Functions take inputs as parameters, executes a block of statements or perform
operations on these parameters and returns the result. There are two types of functions
in PHP:
Built-in functions: PHP provides large collection of built-in library functions
(more than 1000 functions). Whenever we need, we can just call these built-in
functions as per our requirements.
User defined functions: PHP allows us to create our own customised functions
called user defined functions. We can create our own packages of code and use
them whenever required.
User defined functions:
User defined functions are defined as below:
function functionname() {
Block of code;
}
Note: A function name must start with a letter or an underscore. Function names are
NOT case-sensitive.
Below code is example of PHP function which prints a message on the browser.
<?php
function writeMessage() {
echo "Welcome to the PHP course..!!";
}
27
<?php
function printSubjects($code, $subject) {
echo "Subject name for code $code is $subject <br>";
}
Arguments are by default passed by value, which means that a copy of the value is
passed to the function, so the original variable that was passed into the function is not
changed when we modify argument in the function. We can pass argument by
reference, where changes made to the argument also change the original variable that
was passed in. The & operator is used to pass variable by reference in argument. Below
example show how to pass argument by reference:
<?php
function incrementVar(&$var) {
$var += 1;
return $var;
}
$a = 5;
$res = incrementVar($a);
echo "Value after increment is $res <br>";
?>
<?php
function areaofCircle($radius = 10) {
$area = 2 * 3.14 * $radius;
echo "Area of Circle is : $area <br>";
}
areaofCircle();
areaofCircle(20);
?>
28
<?php
function sumArray($arr) {
$sum = 0;
for ($i = 0; $i < count($arr); $i++) {
$sum += $arr[$i];
}
return $sum;
}
$a = array(4, 9, 11, 25, 17);
$s = sumArray($a);
29
Output:
30
Output:
3. Write a script to display the current date and time in different formats.
Source Code:
31
Output:
SIGN OF FACULTY:
32
Practical No. 5: Arrays
Prerequisite Theory:
PHP array is a collection of similar data times stored in a single variable. It is basically
an ordered map, which contains values on the basis of keys/indexes. PHP arrays allows
traversing and processing of data items using a single loop. There are three types of
arrays in PHP.
1. Indexed arrays
2. Associative arrays
3. Multi-dimensional arrays
Indexed/Numeric arrays
This type of arrays can store data of any type. They have integer indexes that start at
zero by default. The Indexed array can be created as follow:
$subject_codes[0] = 4330701;
$subject_codes[1] =4330702;
$subject_codes[2] =4330703;
$subject_codes[3] =4330704;
Another way to access all elements in the array using for loops is as below:
33
$subject_codes = array(4330701, 4330702, 4330703, 4330704);
echo "Subject codes: <br>";
foreach ($subject_codes as $code) {
echo $code . "<br>";
}
Associative arrays
Associative arrays are similar to indexed arrays but instead of integer indexes values
are assigned to user-defined keys of string type. Below example shows how to assign
associative array:
$subjects = array("4330701" => "SLP",
"4330702" => "RDBMS",
"4330703" => "BOS",
"4330704" => "DSA");
Or it can be assigned manually as below:
$subjects["4330701"] = "SLP";
$subjects["4330702"] = "RDBMS";
$subjects["4330703"] = "BOS";
$subjects["4330704"] = "DSA";
Below example shows accessing data stored in the associative array:
$subjects = array("4330701" => "SLP",
"4330702" => "RDBMS",
"4330703" => "BOS",
"4330704" => "DSA");
echo "Subjects: <br>";
echo $subjects["4330701"] . "<br>";
echo $subjects["4330702"] . "<br>";
echo $subjects["4330703"] . "<br>";
echo $subjects["4330704"] . "<br>";
Multidimensional arrays
34
A multidimensional array is an array containing one or more arrays. PHP supports
multidimensional array that are two or more levels deep. However, arrays more than
three levels are hard to manage. Below is example of two-dimensional array:
$subjects = array (
array("4330701","SLP",150),
array("4330702","RDBMS",150),
array("4330703","BOS",150),
array("4330704","DSA",150)
);
Below example shows a way to access all elements in the multidimensional array using
for loops is as below:
$subjects = array (
array("4330701","SLP",150),
array("4330702","RDBMS",150),
array("4330703","BOS",150),
array("4330704","DSA",150)
);
35
Output:
36
Output:
37
3. Write a script to perform addition of 3 x 3 matrix.
Source Code:
38
Output:
39
Output:
40
iii. Develop PHP web applications to demonstrate array functions.
5. Write PHP script to make use of array-related library functions like count, list, in_array,
current,next, previous, end, each, sort, array_merge, array_reverse
Source Code:
41
Output:
SIGN OF FACULTY:
42
1. Single Quoted (' ')
The simplest way to specify a string. It does not interpret variables or most escape
sequences (except \' and \\).
$name = 'World'; echo 'Hello $name'; // Outputs: Hello $name
2. Double Quoted (" ")
The most common syntax. It interpolates variables (replaces variable names with their
values) and supports various escape sequences like \n (newline) or \t (tab).
$name = 'World'; echo "Hello $name"; // Outputs: Hello World
3. Heredoc (<<<Label)
Acts like a double-quoted string but is ideal for multi-line text. It preserves formatting
and interpolates variables.
$text = <<<EOD
This is a multi-line
string for $name.
EOD;
4. Nowdoc (<<<'Label')
The "single-quoted" version of Heredoc. It does not interpolate variables. It’s useful for
embedding code or large blocks of raw text.
$text = <<<'EOD'
Variables like $name won't expand here.
EOD;
43
Function Description Example
chr($n) Returns a character from an ASCII chr(65) // "A"
value.
ord($s) Returns the ASCII value of the first ord("A") // 65
character.
strtolower() Converts string to lowercase. strtolower("HEY") // "hey"
strtoupper() Converts string to uppercase. strtoupper("hey") // "HEY"
strlen() Returns the length of the string. strlen("abc") // 3
ltrim() / rtrim() Strips whitespace from the left or ltrim(" x") // "x"
right.
trim() Strips whitespace from both ends. trim(" x ") // "x"
substr() Returns a portion of a string. substr("Hello", 1, 2) // "el"
strcmp() Case-sensitive string comparison. strcmp("a", "A") // Non-zero
strcasecmp() Case-insensitive string comparison. strcasecmp("a", "A") // 0
strpos() Finds the position of the first strpos("abc", "b") // 1
occurrence.
stristr() Case-insensitive strstr; finds first stristr("Hello", "e") // "ello"
occurrence.
str_replace() Replaces all occurrences of a search str_replace("a", "b", "aa") //
string. "bb"
strrev() Reverses a string. strrev("abc") // "cba"
Source Code:
44
Output:
SIGN OF FACULTY:
45
Practical No. 7:Forms & Input Data
Prerequisite Theory:
Web forms are one of the most common ways for a user to interact with a
web application. Forms allow users to enter data, which is typically sent to a web server
for processing and storage or used on the client-side to update the interface in some
way immediately.
The HTML of a web form is made up of one or more form controls (also known as
widgets) and some additional elements to help structure the overall form - these are
commonly referred to as HTML forms. Most common controls are single or multi-line
text boxes, dropdown boxes, buttons, checkboxes and radio buttons. There are some
other elements such as date, time, day color, file etc. Form controls can also be
programmed to enforce specific formats or values to be entered (form validation).
Define HTML Form:
The HTML <form> element is used to create an HTML form for user input:
<form>
...
form elements
...
</form>
<formaction="/[Link]" method="get">
<label for="uname">User Name:</label><br>
<input type="text" id="uname" name="uname"><br>
<label for="password">Password:</label><br>
<input type="password" id="password" name="password">
<input type="submit" value="Submit">
</form>
The <label> tag defines a label for many form elements. The <label> element is
useful for screen-reader users, because the screen-reader will read out loud the
label when the user focus on the input element.
The <input type="submit"> defines a button for submitting the form data to a
form-handler. The form-handler is typically a file on the server with a script for
processing input data.
The action attribute defines the action to be performed when the form is
submitted. Usually, the form data is sent to a file on the server when the user
clicks on the submit button.
The method attribute specifies the HTTP method to be used when submitting the
form data. The form-data can be sent as URL variables (with method="get") or as
HTTP post transaction (with method="post").
46
The HTML id attribute is used to specify a unique id for an HTML element. You
cannot have more than one element with the same id in an HTML document.
Each input field must have a name attribute to be submitted. If the name attribute
is omitted, the value of the input field will not be sent at all. It is used by PHP
script to read form data from that input element.
The type attribute defines type of input element. By default value of the type
attribute is "text". Different types of input elements are as follow:
TextBox:
The <input type="text"> provides a single-line input field to input text.
47
<form action="/[Link]" method="get">
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname">
<input type="submit" value="Submit">
</form>
Radio Button:
Radio Button allows user to select only one choice from a limited number of choices.
Check Box:
Check Box allows a user to select zero or more choices from a limited number of
choices.
In PHP, validating and sanitizing form data is the most critical step in preventing
security vulnerabilities like Cross-Site Scripting (XSS) and SQL [Link] is a
48
breakdown of the common functions used to ensure data is safe, present, and in the
correct format.
49
if (!filter_var($url, FILTER_VALIDATE_URL)) { echo "Invalid
URL"; }
50
51
Output:
SIGN OF FACULTY:
52
Prerequisite Theory:
PHP provides a robust set of functions for interacting with the server's file [Link]
is a guide on managing directories and handling text files.
53
$file = fopen("[Link]", "w");
// "w" creates/overwrites; "a" appends
fwrite($file, "Adding a line of text.");
fclose($file);
Mode Description
'r' Read only; starts at the beginning of the file.
Write only; truncates (deletes) file content or creates it
'w'
if it doesn't exist.
Append; opens for writing but preserves existing
'a'
content, adding new data to the end.
'r+' Read and Write; starts at the beginning.
Handling file uploads and downloads involves a combination of HTML forms and
PHP’s server-side filesystem functions.
5. Uploading Files
To upload files, you must use an HTML form with the method="POST" and the
specific attribute enctype="multipart/form-data".
The HTML Logic
<form action="[Link]" method="POST"
enctype="multipart/form-data">
Select image to upload:
<input type="file" name="myFile">
<button type="submit">Upload</button>
</form>
The PHP Logic ([Link])
When a file is uploaded, PHP stores it in a temporary location. You must move it to
your desired folder using move_uploaded_file(). Data about the file is stored in the
$_FILES superglobal array.
if (isset($_FILES['myFile'])) {
$file = $_FILES['myFile'];
$fileName = $file['name'];
$fileTmp = $file['tmp_name'];
$dest = "uploads/" . $fileName;
if (move_uploaded_file($fileTmp, $dest)) {
echo "File uploaded successfully!";
} else {
echo "Upload failed.";
}
}
54
When the file is moved via move_uploaded_file(), you store the path in a variable and
then echo that path into the src attribute of an image tag.
if (isset($_POST['submit'])) {
$targetDir = "uploads/";
$fileName = basename($_FILES["myImage"]["name"]);
$targetFilePath = $targetDir . $fileName;
if (move_uploaded_file($_FILES["myImage"]["tmp_name"],
$targetFilePath)) {
echo "<h3>Uploaded Thumbnail:</h3>";
echo '<img src="' . $targetFilePath . '"
style="width:150px; height:auto; border:1px solid #ccc;
padding:5px;">';
}
}
55
Output:
56
ii. Develop a PHP web application to upload an image file into the server and display a
thumbnail of the uploaded image.
Source Code:
57
58
Output:
59
SIGN OF FACULTY:
60
Practical No. 9:Subscription & Email
Prerequisite Theory:
Emailsare widely used for communication purposes in various web applications, such
as sending verification emails, password reset links, newsletters, and order
confirmations.
PHP primarily uses the built-in mail() function to send and receive emails using
different protocols such as SMTP, IMAP, and POP3. Although for complex tasks like
attachments and high-volume newsletters, professional libraries (like PHPMailer or
Symfony Mailer) are often used.
Here are the basic steps to send an email in PHP.
• Configure the SMTP server settings
• Set up the email headers
• Compose the email message
1. Sending Plain Text Email
This is the simplest form of communication. It sends unformatted text without any
styling.
$to = "user@[Link]";
$subject = "Welcome!";
$message = "Hello, thank you for joining our site.";
$headers = "From: webmaster@[Link]";
61
3. Email with Attachments
Sending attachments with the native mail() function is highly complex because it
requires "Multipart/Mixed" MIME boundaries to separate the text from the file data
(which must be encoded in Base64).
The easier way isusing PHPMailer library, because native PHP code for attachments is
long and prone to errors.
use PHPMailer\PHPMailer\PHPMailer;
$mail->send();
62
Output:
63
SIGN OF FACULTY:
64
Practical No. 10:Session, Cookies
Prerequisite Theory:
In PHP, sessions and cookies are two mechanisms used to store and manage data
related to a user's interaction with a website or web application.
Session
Sessions are a way of storing information on the server about a user's activity on a
website. When a user visits a website, the server assigns them a unique session ID,
which is stored in a cookie on the user's computer. The server then uses this session ID
to keep track of the user's activity as they move around the website. The session data
can include things like user preferences, shopping cart items, or authentication status.
Sessions can be started using the session_start() function and the session data can be
accessed through the $_SESSION superglobal array.
Cookie
Cookies are small text files that are stored on a user's computer by their web browser.
Cookies are often used to remember user preferences or login information, or to track
user behavior across different pages or sessions. In PHP, cookies can be set using the
setcookie() function. Cookies can have an expiration time, after which they are
automatically deleted, or they can be set to expire when the user closes their browser.
Cookie data can be accessed using the $_COOKIE superglobal array.
Comparison
Both sessions and cookies have their advantages and disadvantages. Sessions are
generally more secure because the data is stored on the server, but they can be slower
and less flexible. Cookies are faster and more flexible, but they can be less secure
because the data is stored on the user's computer. When using cookies, it's important to
make sure that sensitive information, such as passwords or credit card numbers, is not
stored in the cookie.
In summary, sessions and cookies are two important mechanisms used to store and
manage user-related data in PHP. By understanding how to use these mechanisms
correctly, developers can create more secure and user-friendly web applications.
Examples
Using Session
Start the session using the session_start() function.
<?php
session_start();
>
65
<?php
$_SESSION[‘username’] = ‘Ashish’;
>
<?php
session_start();
echo "Welcome " .$_SESSION[‘username’];
>
Using Cookie
Set a cookie using the setcookie() function.
<?php
$cookie_name "username";
$cookie_value = "Ashish";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
?>
<?php
if(isset($_COOKIE [$cookie_name])) {
echo "Welcome". $_COOKIE [$cookie_name];
}
?>
Note that when using sessions and cookies, it's important to be careful about what data
is stored and how it's accessed, to prevent security issues. For example, sensitive
information like passwords or credit card numbers should never be stored in a cookie or
session.
66
Output:
67
ii. Develop a PHP web application to demonstrate the use of Cookies in PHP.
Source Code:
68
Output:
SIGN OF FACULTY:
69
Exception Handling is a way to change the normal flow of a script when a specified
error (an exception) occurs. This allows you to handle errors gracefully instead of
letting the script crash with a "Fatal Error".
1. The Core Components
try: The block of code where you expect something might go wrong.
throw: Used to trigger an exception. You "throw" an Exception object.
catch: The block of code that executes only if an exception was thrown in the try
block. It "catches" the error object to handle it.
finally: A block that always runs after the try and catch blocks, regardless of whether
an exception was thrown or not. This is perfect for cleanup tasks (like closing a
database connection).
2. Practical Example: Division by Zero
A common programming error is dividing by zero. Here is how you handle it using
exceptions:
function divide($numerator, $denominator) {
if ($denominator == 0) {
// Trigger an exception
throw new Exception("Division by zero error!");
}
return $numerator / $denominator;
}
try {
// Attempting the operation
echo divide(10, 0);
}
catch (Exception $e) {
// Handle the error
echo "Caught exception: " . $e->getMessage() . "\n";
}
finally {
// This always runs
echo "Process complete.";
}
3. Creating Custom Exceptions
You can create your own exception classes by extending the base Exception class. This
is useful for categorizing errors (e.g., DatabaseException, ValidationException).
70
class InvalidEmailException extends Exception {}
function checkEmail($email) {
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
throw new InvalidEmailException("The email address
is not valid.");
}
}
try {
checkEmail("wrong-email");
} catch (InvalidEmailException $e) {
echo "Email Error: " . $e->getMessage();
} catch (Exception $e) {
echo "General Error: " . $e->getMessage();
}
4. Comparison of Error Handling vs. Exceptions
71
Output:
72
SIGN OF FACULTY:
73
Practical No. 12:Database Operations
Prerequisite Theory:
MySQL is a popular relational database management system that is commonly used in
web development with PHP. Here are some MySQL functions that can be used in PHP
to interact with MySQL databases:
mysqli_connect() - This function is used to establish a connection to a MySQL
database server.
mysqli_query() - This function is used to execute a MySQL query on a connected
database.
mysqli_fetch_array() - This function is used to fetch the result of a MySQL query as
an array.
mysqli_insert_id() - This function is used to get the auto-generated ID of the last
inserted record in a table.
mysqli_real_escape_string() - This function is used to escape special characters in a
string to prevent SQL injection attacks.
mysqli_num_rows() - This function is used to get the number of rows returned by a
MySQL query.
mysqli_error() - This function is used to get the error message associated with the
last MySQL operation.
mysqli_close() - This function is used to close the connection to a MySQL database
server.
These are just a few examples of the MySQL functions that can be used in PHP. There
are many other functions available for working with MySQL databases in PHP, and
their usage depends on the specific needs of your application.
Example
Assuming we have a MySQL database with a table named "users" that has columns
"id", "username", and "password", we can use PHP to perform various operations on
this table.
1. Connect to the MySQL database:
74
<?php
$host = "localhost"; $username = "db_user";
$password = "db_password";
$dbname = "my_database";
// Create connection
$conn = mysqli_connect($host, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: mysqli_connect_error());
}
echo "Connected successfully";
?>
<?php
$username = "john_doe";
$password = "my_password";
75
<?php
// Create and execute the SQL query to retrieve all users
$sql = "SELECT * FROM users";
$result = mysqli_query($conn, $sql);
<?php
$username "ashish";
$new_password = "new_password";
// Create and execute the SQL query to update the password for a
// specific user
$sql = "UPDATE users SET password='$new_password' WHERE
username='$username'
if (mysqli_query($conn, $sql)) {
echo "Record updated successfully";
}
else {
echo "Error updating record: mysqli_error($conn);
}
?>
76
5. Delete a specific user from the "users" table:
<?php
$username "ashish";
77
78
Output:
79
ii. Develop a simple Blog web application that allows users to create, read, update, and delete
blogs (CRUD operations).
Source Code:
80
81
Output:
82
SIGN OF FACULTY:
83
84
85
Output:
86
87
ii. Develop a simple To-Do List web application using PHP with the help of AI code
generation tools such as GitHub Copilot, ChatGPT, Gemini, etc.
Source Code:
88
89
90
Output:
91
92
iii. Develop a simple Inventory Management web application and host it on a web server.
Source Code:
93
94
95
Output:
96
97
SIGN OF FACULTY:
98