Professional Documents
Culture Documents
Webd
Webd
Experiment No: 15
Relevant CO: 5
Objectives:
PHP
• PHP is a server scripting language, and a powerful tool for making dynamic and
interactive Web pages.
• PHP is a widely-used, free, and efficient alternative to competitors such as Microsoft's
ASP.
• Syntax
<?php
// PHP code goes here
?>
<?php
echo "Hello World";
?>
</body>
</html>
<?php
$txt = "Hello world!";
$x = 5;
$y = 10.5;
?>
if (condition) { code
to be executed if
condition is true;
} else {
code to be executed if
condition is false;
}
if (condition) { code to
be executed if this
condition is true; } elseif
(condition) { code to be
executed if first condition
is false and this condition
is true;
} else {
code to be executed if
all conditions are false;
}
do {
code to be executed; }
while (condition is
true);
code to be executed;
<?php
function check_prime($num)
{
if ($num == 1)
return 0;
for ($i = 2; $i <= $num/2; $i++)
{
if ($num % $i == 0)
return 0;
}
return 1;
}
$num = 47;
$flag_val = check_prime($num);
if ($flag_val == 1)
echo "It is a prime number";
else
echo "It is a non-prime number"
?>
Output :
Conclusion:
checking if a number is prime in PHP involves implementing a basic algorithm, which can be
encapsulated in a function for reusability or integrated into a web form for user interaction. •
A common and simple way to check for prime numbers is to iterate from 2 to the number in
question. For each iteration, check if the number is divisible by the current iterator. • It
avoids unnecessary iterations and provides a clear way to determine the primality of a given
number
Suggested Reference:
• https://www.w3schools.com/php/php_looping.asp
Experiment No: 16
Relevant CO: 5
Objectives:
Accessing MySQL from PHP Note that documentation is available online here:
http://www.php.net/manual/en/ref.mysql.php
Basically, there are four things you want to be able to do in MySQL from within PHP:
Queries can be any kind of MySQL query, including SELECT, UPDATE, INSERT, etc. Using
SELECT queries, you can execute MySQL/PHP functions to put the data read from the MySQL
database into PHP variables. Then you can use the PHP variables in your PHP script to do
whatever analysis, display, etc. that you want.
$row as $item )
echo "\t\n";
- To execute the query and store the result in a local variable: mysql_query()
- Parse the data read returned from the query as an array: mysql_fetch_array()
- Free the memory used by the query result: mysql_free_result()
NOTE that if the result returned is a scalar and not an array, then only mysql_query() needs
to be called and does not need to be followed by a call to mysql_fetch_array().
If errors occur, the functions return errors. These errors can be read as strings using the
function mysql_error(). Note the usage in this statement:
mysql_close($conn);
Implementation:
Use Registration Form from practical number 5 to store user registration details in MySql
database. On submission next page displays all registration data in in html table using php.
Also provide feature to update and delete the registration data.
<?php
$login = false;
$showError = false;
if($_SERVER["REQUEST_METHOD"] == "POST"){
include 'partials/_dbconnect.php';
$username = $_POST["username"];
$password = $_POST["password"];
<body>
Conclusion:
Users can input their information into an HTML form, which is processed by PHP and stored
in a MySQL database. • This experiment provided practical experience in web development,
including HTML form creation, PHP scripting for data handling, and database integration with
MySQL. • This experiment is a valuable exercise for understanding the fundamentals of web
development, user registration systems, and database interactions
Quiz:
1. What is MySql?
2. Write a sample code to demonstrate php mysql connectivity.
Suggested Reference:
• http://www.php.net/manual/en/ref.mysql.php References
used by the students:
Experiment No: 17
Write a PHP script for user authentication using PHP-MYSQL. Use session
for storing username
Date:
Relevant CO: 3
Objectives:
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, session variables last until the user closes
the browser.
So; Session variables hold information about one single user, and are available to all pages in
one application.
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>
Next, we create another page called "demo_session2.php". From this page, we will access the
session information we set on the first page ("demo_session1.php").
Notice that session variables are not passed individually to each new page, instead they are
retrieved from the session we open at the beginning of each page (session_start()).
Also notice that all session variable values are stored in the global $_SESSION variable:
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Echo session variables
that were set on previous
page
echo "Favorite color is "
. $_SESSION["favcolor"]
. ".<br>";
echo "Favorite animal is "
. $_SESSION["favanimal"]
. ".";
?>
</body>
</html>
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// to change a session
variable, just overwrite it
$_SESSION["favcolor"]
= "yellow";
print_r($_SESSION);
?>
</body>
</html>
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// remove all session
variables session_unset();
</body>
</html>
Implementation:
Write a PHP script for user authentication using PHP-MYSQL. Use session for storing
username.
<?php
session_start();
if (isset($_POST['login_btn'])) {
$username = $_POST['username'];
$password = $_POST['password'];
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$stmt = $conn->prepare($query);
$stmt->bind_param("s", $username);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows == 1) {
$user = $result->fetch_assoc();
if (password_verify($password, $user['password'])) {
$_SESSION['username'] = $username;
echo "Login successfully";
} else {
echo "Invalid username or password";
}
} else {
echo "Invalid username or password";
}
$stmt->close();
$conn->close();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login</title>
</head>
<body>
<h1>Login</h1>
<form method="post"> <!-- Replace 'yourphpfilename.php' with your PHP file name -->
<label for="username">Username:</label>
<input type="text" id="username" name="username" required><br><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required><br><br>
<input type="submit" value="Login" name="login_btn">
</form>
</body>
</html>
Conclusion:
we created a PHP script for user authentication using PHP and MySQL, with the username
stored in a session. User authentication is a fundamental aspect of web applications to ensure
that only authorized individuals can access certain features or data. • The script begins by
starting a session using session_start(). It checks if the user is already logged in by verifying if
the username is stored in the session. • When the user submits the login form, the script
establishes a connection to a MySQL database. It retrieves the username and password
entered by the user and queries the database to check if there is a matching record in the
database
Quiz:
• https://www.w3schools.com/php/php_sessions.asp
References used by the students:
Experiment No: 18
Using AJAX Create visual search feature to search using name for practical
number 16 which list name, mobile number and email id of matching
users.
Date:
Relevant CO: 6
Objectives:
What is AJAX?
AJAX = Asynchronous JavaScript And XML.
AJAX is not a programming language.
AJAX just uses a combination of:
- A browser built-in XMLHttpRequest object (to request data from a web server)
- JavaScript and HTML DOM (to display or use the data)
AJAX allows web pages to be updated asynchronously by exchanging data with a web server
behind the scenes. This means that it is possible to update parts of a web page, without
reloading the whole page.
xhttp.onload = function() {
// What to do when the response is ready
}
xhttp.open("GET", "ajax_info.txt");
xhttp.send();
Method Description
send()
Sends the request to the server Used
for GET requests
send(string)
Sends the request to the server. Used
for POST requests
setRequestHeader()
Adds a label/value pair to the header to be
sent
Property Description
Onload Defines a function to be called when the
request is recieved (loaded)
Onreadystatechange Defines a function to be called when the
readyState property changes
readyState Holds the status of the XMLHttpRequest.
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready
responseText Returns the response data as a string
responseXML Returns the response data as XML data
Status Returns the status-number of a request
200: "OK"
403: "Forbidden"
404: "Not Found"
For a complete list go to the Http Messages
Reference
statusText Returns the status-text (e.g. "OK" or "Not
Found")
xhttp.onload = function() {
document.getElementById("demo").innerHTML = this.responseText;
}
xhttp.open("GET", "ajax_info.txt"); xhttp.send();
Implementation:
Using AJAX Create visual search feature to search using name for practical number 16 which
list name, mobile number and email id of matching users.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Registration Form</title>
<style>
/* Add your CSS rules here */
body {
h1 {
color: #0074D9;
}
input[type="text"] {
padding: 5px;
}
button {
padding: 5px 10px;
background-color: #0074D9;
color: #FFFFFF;
border: none;
cursor: pointer;
}
#results {
margin-top: 20px;
padding: 10px;
background-color: #FFFFFF;
border: 1px solid #CCCCCC;
}
</style>
</head>
<body>
<h1>Registration Form</h1>
<form id="registration-form">
<label for="firstname"><i class="fas fa-user"></i> <b>Firstname:</b></label>
<input id="firstname" type="text" name="firstname" placeholder="Firstname" size="15"
required /><br>
<option value="MCA">MCA</option>
<option value="M.Tech">M.Tech</option>
</select><br>
<div id="display-info"></div>
<script src="script14.js"></script>
</body>
</html>
Output :
Conclusion:
we implemented a visual search feature using AJAX to search for users by name and displaying
their name, mobile number, and email id. • This feature enhances the user experience by
allowing them to find information quickly and efficiently. • By using AJAX, we enable real-time
searching, where the results are updated dynamically as the user types, providing instant
feedback and reducing the need for page reloads. • A visual search feature with AJAX is a
powerful tool for improving user interactions and search experiences. • It leverages the
capabilities of modern web development to create a dynamic and responsive search
functionality
1. What is Ajax?
2. Explain XMLHttpRequest.
Suggested Reference:
• https://www.w3schools.com/xml/ajax_intro.asp
References used by the students:
Experiment No: 19
Relevant CO: 6
Objectives:
What is REST?
REST stands for Representational State Transfer, REST is an architectural style which defines
a set of constraints for developing and consuming web services through standard protocol
(HTTP). REST API is a simple, easy to implement and stateless web service. There is another
web service available which is SOAP which stands for Simple Object Access Protocol which is
created by Microsoft.
REST API is widely used in web and mobile applications as compared to SOAP. REST can
provide output data in multiple formats such as JavaScript Object Notation (JSON), Extensible
Markup Language (XML), Command Separated Value (CSV) and many others while SOAP
described output in Web Services Description Language (WSDL).
How Does REST API Work
REST requests are related to CRUD operations (Create, Read, Update, Delete) in database,
REST uses GET, POST, PUT and DELETE requests. Let me compare them with CRUD.
GET is used to retrieve information which is similar to Read
To create a table run the following query. Note: I have already attached the SQL file of this
table with dummy data, just download the complete zip file of this tutorial.
function response($order_id,$amount,$response_code,$response_desc){
$response['order_id'] = $order_id;
$response['amount'] = $amount;
$response['response_code'] = $response_code;
$response['response_desc'] = $response_desc;
$json_response = json_encode($response);
echo $json_response;
}
?>
The above script will accept the GET request and return output in the JSON format.
I have created all these files in folder name rest, now you can get the transaction information
by browsing the following URL.
http://localhost/rest/api.php?order_id=15478959
Above URL is not user friendly, therefore we will rewrite URL through the .htaccess file, copy
paste the following rule in .htaccess file.
RewriteEngine On # Turn on the rewriting engine
Now you can get the transaction information by browsing the following URL.
http://localhost/rest/api/15478959
$client = curl_init($url);
curl_setopt($client,CURLOPT_RETURNTRANSFER,true);
$response = curl_exec($client);
$result = json_decode($response);
echo "<table>";
echo "<tr><td>Order ID:</td><td>$result->order_id</td></tr>"; echo
"<tr><td>Amount:</td><td>$result->amount</td></tr>"; echo
"<tr><td>Response Code:</td><td>$result->response_code</td></tr>"; echo
"<tr><td>Response Desc:</td><td>$result->response_desc</td></tr>"; echo
"</table>";
}
?>
You can do anything with these output data, you can insert or update it into your own database
if you are using REST API of any other service provider. Usually in case of online transaction,
the service provider provides status of payment via API. You can check either payment is
made successfully or not. They also provide a complete guide of it.
Note: Make sure CURL is enabled on your web server or on your localhost when you are
testing demo.
Conclusion:
Creating a REST API using PHP is a powerful way to expose your application's functionality
to other developers and systems. • API design is a critical aspect of the process. • It can be a
valuable tool for enabling data access and interaction between different software systems. •
Documentation is key to making your API user-friendly. • Proper planning, security
considerations, and thorough testing are essential to building a robust and reliable REST API
that meets the needs of any project.
• https://www.allphptricks.com/create-and-consume-simple-rest-api-in-php/)
Experiment No: 20
Relevant CO: 6
Objectives:
JQUERY
The purpose of jQuery is to make it much easier to use JavaScript on your website. jQuery
takes a lot of common tasks that require many lines of JavaScript code to accomplish, and
wraps them into methods that you can call with a single line of code. jQuery also simplifies a
lot of the complicated things from JavaScript, like AJAX calls and DOM manipulation.
The jQuery library contains the following features:
A. HTML/DOM manipulation
B. CSS manipulation
C. HTML event methods
D. Effects and animations
E. AJAX
There are several ways to start using jQuery on your web site.
You can:
• Download the jQuery library from jQuery.com
• Include jQuery from a CDN, like Google
<head>
<script src="jquery-3.6.4.min.js"></script>
</head>
OR
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js
">
</script>
</head>
Examples:
All jQuery methods in our examples, are inside a document ready event:
$(document).ready(function(){
});
This is to prevent any jQuery code from running before the document is finished loading (is
ready). It is good practice to wait for the document to be fully loaded and ready before
working with it. This also allows you to have your JavaScript code before the body of your
document, in the head section.
jQuery selectors are used to "find" (or select) HTML elements based on their name, id, classes,
types, attributes, values of attributes and much more. It's based on the existing CSS Selectors,
and in addition, it has some own custom selectors.
All selectors in jQuery start with the dollar sign and parentheses: $().
$(document).ready(function(){
$("button").click(function(){
$("p").hide();
});
});
The jQuery #id selector uses the id attribute of an HTML tag to find the specific element.
An id should be unique within a page, so you should use the #id selector when you want to
find a single, unique element.
To find an element with a specific id, write a hash character, followed by the id of the HTML
element:
$("#test")
When a user clicks on a button, the element with id="test" will be hidden:
$(document).ready(function(){
$("button").click(function(){
$("#test").hide();
});
});
All the different visitors' actions that a web page can respond to are called events. An event
represents the precise moment when something happens.
Examples:
• moving a mouse over an element
• selecting a radio button
• clicking on an element
The term "fires/fired" is often used with events. Example: "The keypress event is fired, the
moment you press a key". Here are some common DOM events:
In jQuery, most DOM events have an equivalent jQuery method. To assign a click event to all
paragraphs on a page, you can do this:
$("p").click();
The next step is to define what should happen when the event fires. You must pass a function
to the event:
$(document).ready()
The $(document).ready() method allows us to execute a function when the document is fully
loaded.
click()
The click() method attaches an event handler function to an HTML element. The function is
executed when the user clicks on the HTML element. The following example says: When a
click event fires on a <p> element; hide the current <p> element:
$("p").click(function(){
$(this).hide();
});
dblclick()
The dblclick() method attaches an event handler function to an HTML element. The function is
executed when the user double-clicks on the HTML element:
$("p").dblclick(function(){
$(this).hide();
});
mouseenter()
The mouseenter() method attaches an event handler function to an HTML element. The function
is executed when the mouse pointer enters the HTML element:
$("#p1").mouseenter(function(){
alert("You entered p1!");
});
Implementation:
overflow: hidden;
}
.slides {
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
}
.slide {
width: 500px;
height: 300px;
display: none;
}
.slide img {
width: 100%;
height: 100%;
}
.nav {
position: absolute;
bottom: 10px;
left: 50%;
transform: translateX(-50%);
}
.nav a {
display: inline-block;
width: 10px;
height: 10px;
background-color: black;
margin: 0 5px;
border-radius: 50%;
}
.nav a.active {
background-color: white;
}
</style>
</head>
<body>
<div class="slider">
<div class="slides">
<div class="slide">
<img src="https://imgs.search.brave.com/TCKzOVIvOLWPdffaguJVmxbbGFsBZ-CLFmtBjpNqo
alt="Image 1">
</div>
<div class="slide">
src="https://imgs.search.brave.com/ODaFDHNGPBcG7XqmN0sFFACRijroqG0VOTKxzMYpfBk/rs:fit:
LmpwZw" alt="Image 2">
</div>
<div class="slide">
BLrj8/rs:fit:500:0:0/g:ce/aHR0cHM6Ly9zdDIu/ZGVwb3NpdHBob3Rv/cy5jb20vMTAzODA3/Ni8
</div>
</div>
<nav class="nav">
<a href="#" class="active"></a>
<a href="#"></a>
<a href="#"></a>
</nav>
</div>
<script>
$(document).ready(function() {
var currentSlide = 0;
$('.slides .slide').eq(currentSlide).show();
$('.nav a').click(function(e) {
e.preventDefault();
var slideIndex = $(this).index();
$('.slides .slide').eq(currentSlide).hide();
currentSlide = slideIndex;
$('.slides .slide').eq(currentSlide).show();
$('.nav a').removeClass('active');
$(this).addClass('active');
});
});
</script>
</body>
</html>
Output :
Conclusion:
jQuery is properly included in the HTML code, allowing for the use of jQuery functions to
manipulate the slider elements.
Quiz:
1. What is jquery?
2. Javascript Vs. Jquery Suggested Reference:
• https://www.w3schools.com/jquery/jquery_intro.asp
Experiment No: 21
Cookie Example
Create HTML form with one textbox and button. Keep button label as SAVE. User will enter
color name in textbox and click on save button. On save, the value of textbox color name
should be saved in COOKIE. Whenever user opens page again, the background color should be
same as saved in cookie. Whenever user opens page again, the background color should be
same as saved in cookie.
Date:
Relevant CO: 6
Objectives:
Cookie
Syntax
Example
<?php
$cookie_name = "email"; $cookie_value
= "abc@xyz.com";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); //
86400 = 1 day
?>
<html>
<body>
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
</body>
</html>
Above example creates a cookie named “email” with value abc@xyz.com which will expire
after 30 days.
Delete a Cookie
To delete a cookie use setcookie() function with an expiration date in the past.
Example
<?php
// set the expiration date to one hour ago setcookie("user",
"", time() - 3600);
?>
<html>
<body>
<?php
echo "Cookie 'user' is deleted.";
?>
</body>
</html>
Implementation:
Create HTML form with one textbox and button. Keep button label as SAVE. User will enter
color name in textbox and click on save button. On save, the value of textbox color name
should be saved in COOKIE. Whenever user opens page again, the background color should be
same as saved in cookie. Whenever user opens page again, the background color should be
same as saved in cookie.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Background Color Changer</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
}
#colorInput {
padding: 5px;
}
#colorButton {
padding: 5px 10px;
background-color: #0074D9;
color: #FFFFFF;
border: none;
cursor: pointer;
}
</style>
</head>
<body>
<h1>Background Color Changer</h1>
<form id="colorForm">
<input type="text" id="colorInput" placeholder="Enter a color name">
<button type="button" id="colorButton" onclick="saveColor()">SAVE</button>
</form>
<script>
function saveColor() {
const colorInput = document.getElementById("colorInput").value;
if (colorInput) {
document.cookie = "backgroundColor=" + colorInput + "; expires=365; path=/";
document.body.style.backgroundColor = colorInput;
}
}
function getCookie(name) {
Conclusion:
Cookies are used to store and persist the background color data.
Quiz:
1. What is cookie?
2. What is the life of cookie?
Suggested Reference:
• https://www.w3schools.com/php/php_cookies.asp
Rubrics 1 2 3 Total
Marks