You are on page 1of 42

IT Dept 3151606(WD) Year 2023-24

Experiment No: 15

Write a PHP program to check if number is prime or not.


Date:

Competency and Practical Skills:

Relevant CO: 5

Objectives:

1. To understand how to write simple php program


2. To understand how to use php conditional and Loops Statement Theory:

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

• Example : demonstrate printing Hello World


<!DOCTYPE html>
<html>
<body>

<?php
echo "Hello World";
?>
</body>
</html>

• Creating (Declaring) PHP Variables

SEM 5 210280116126 P a g e | 127


IT Dept 3151606(WD) Year 2023-24

<?php
$txt = "Hello world!";
$x = 5;
$y = 10.5;
?>

• PHP Conditional Statements


Statement Syntax

PHP - The if Statement if (condition) {


code to be executed if
condition is true;

PHP - The if...else Statement

if (condition) { code
to be executed if
condition is true;
} else {
code to be executed if
condition is false;
}

PHP - The if...elseif...else Statement

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;
}

SEM 5 210280116126 P a g e | 128


IT Dept 3151606(WD) Year 2023-24
• PHP Loop Statements
Statement Syntax

The PHP while Loop while (condition is true) {


code to be executed;

The PHP do...while Loop

do {
code to be executed; }
while (condition is
true);

The PHP for Loop

for (init counter; test


counter; increment counter)
{
code to be executed for each
iteration;
}

The PHP foreach Loop foreach ($array as $value)

code to be executed;

SEM 5 210280116126 P a g e | 129


IT Dept 3151606(WD) Year 2023-24
Implementation:

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

SEM 5 210280116126 P a g e | 130


IT Dept 3151606(WD) Year 2023-24
Quiz:

1. What is PHP? Explain PHP Syntax.

2. Explain foreach Loop in PHP.

Suggested Reference:

• https://www.w3schools.com/php/php_looping.asp

References used by the students:

Rubric wise marks obtained:


Rubrics 1 2 3 Total
Marks

SEM 5 210280116126 P a g e | 131


IT Dept 3151606(WD) Year 2023-24

Experiment No: 16

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.
Date:

Competency and Practical Skills:

Relevant CO: 5

Objectives:

1. To understand how to use MySql database


2. To understand how to perform CRUD operations.
Theory:

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:

1. connect to the mysql database


2. execute mysql queries
3. check the status of your mysql commands
4. disconnect from the mysql database

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.

1. Connect to the MySQL database

Here is an example of connecting to the MySQL database from within PHP:

$conn=mysql_connect($mysql_host,$mysql_user,$mysql_password) or die('Could not


connect: ’.mysql_error()); echo ’Connected successfully’; mysql_select_db( $mysql_db ) or
die( ’Could not select database’ );

SEM 5 210280116126 P a g e | 132


IT Dept 3151606(WD) Year 2023-24
You will need to replace the variables $mysql_host, $mysql_user, $mysql_password and
$mysql_db with strings containing the values for connecting to your database. $mysql_host is
"localhost"

Notice that there are two functions invoked:

- Logs into mysql: mysql_connect()


- Selects the database to use: mysql_select_db()
Also notice that you put your un-encrypted password in the script that connects to the
database. So be careful where you put that script! Make sure it is in a directory where there is
a default index.html (or index.php) file so that nobody can get to the script from a web
browser.

2. Execute MySQL queries

Here is an example of executing a SELECT query from within PHP:


// set up and execute the MySQL query

$query = ’SELECT * FROM my_table’;

$result = mysql_query( $query ) or die( ’Query failed: ’. mysql_error() );

// print the results as an HTML table echo " \n"; while (

$row = mysql_fetch_array( $result, MYSQL_ASSOC ))

echo "\t \n"; foreach (

$row as $item )

echo "\t\t $item\n";

echo "\t\n";

echo "\n"; // free result


mysql_free_result( $result
);

SEM 5 210280116126 P a g e | 133


IT Dept 3151606(WD) Year 2023-24
There are three functions used here:

- 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().

Finally, note the use of mysql_error() in the query function.

3. Check the status of your MySQL commands

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:

$conn=mysql_connect($mysql_host,$mysql_user,$mysql_password) or die('Could not

connect: ’.mysql_error()); echo ’Connected successfully’;

4. Disconnect from the MySQL database

To disconnect from MySQL, there is one function needed:

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"];

// $sql = "Select * from users where username='$username' AND password='$password'";


$sql = "SELECT * from users where username='$username'";

SEM 5 210280116126 P a g e | 134


IT Dept 3151606(WD) Year 2023-24

$result = mysqli_query($conn, $sql);


$num = mysqli_num_rows($result);
if ($num == 1){
while($row=mysqli_fetch_assoc($result)){
if (password_verify($password, $row['password'])){
$login = true;
session_start();
$_SESSION['loggedin'] = true;
$_SESSION['username'] = $username;
header("location: welcome.php");
}
else{
$showError = "Invalid Credentials";
}
}
}
else{
$showError = "Invalid Credentials";
}
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Log In</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css"
rel="stylesheet" integrity="sha384-
T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN"
crossorigin="anonymous">
</head>

<body>

SEM 5 210280116126 P a g e | 135


IT Dept 3151606(WD) Year 2023-24

<?php require 'partials/_nav.php' ?>


<?php
// if ($login) {
// echo '<div class="alert alert-success" role="alert">
// Logged In succesfully <a href="/log_in_sys/login.php" class="alert-link"></a>.
// </div>';
// }
if ($showError) {
echo '<div class="alert alert-danger" role="alert">
Passwords do not match <a href="/log_in_sys/login.php" class="alert-link">LogIn</a>.
</div>';
}
?>
<div class="container my-4">
<!-- <h1 class="text-center">Sign Up to over website</h1> -->
<form action="/log_in_sys/login.php" method="post">
<div class="mb-3">
<label for="username" class="form-label">Username</label>
<input type="text" class="form-control" id="username" name="username" aria-
describedby="emailHelp">
</div>
<div class="mb-3">
<label for="password" class="form-label">Password</label>
<input type="password" class="form-control" id="password" name="password">
</div>
<button type="submit" class="btn btn-primary">LogIn</button>
</form>
</div>
<script
src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"
integrity="sha384-
C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL"
crossorigin="anonymous"></script>
</body>
</html>

SEM 5 210280116126 P a g e | 136


IT Dept 3151606(WD) Year 2023-24
Output :

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:

Rubric wise marks obtained:


Rubrics 1 2 3 Total
Marks

SEM 5 210280116126 P a g e | 137


IT Dept 3151606(WD) Year 2023-24

Experiment No: 17

Write a PHP script for user authentication using PHP-MYSQL. Use session
for storing username
Date:

Competency and Practical Skills:

Relevant CO: 3

Objectives:

1. To understand session in PHP Theory:

What is a PHP Session?

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.

Start a PHP Session

A session is started with the session_start() function.

Session variables are set with the PHP global variable: $_SESSION.

Now, let's create a new page called "demo_session1.php". In this page, we start a new PHP
session and set some session variables:

SEM 5 210280116126 P a g e | 138


IT Dept 3151606(WD) Year 2023-24

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

Get PHP Session Variable Values

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:

SEM 5 210280116126 P a g e | 139


IT Dept 3151606(WD) Year 2023-24

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

Modify a PHP Session Variable

To change a session variable, just overwrite it:

<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// to change a session
variable, just overwrite it
$_SESSION["favcolor"]
= "yellow";
print_r($_SESSION);
?>

</body>
</html>

Destroy a PHP Session

SEM 5 210280116126 P a g e | 140


IT Dept 3151606(WD) Year 2023-24
To remove all global session variables and destroy the session, use session_unset() and
session_destroy():

<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// remove all session
variables session_unset();

// destroy the session


session_destroy();
?>

</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'];

// Connect to the database (replace with your database credentials)


$hostname = "localhost";
$dbUsername = "your_db_username";
$dbPassword = "your_db_password";
$database = "registrations";

$conn = new mysqli($hostname, $dbUsername, $dbPassword, $database);

if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// Use prepared statements to prevent SQL injection


$query = "SELECT * FROM users WHERE username=?";

SEM 5 210280116126 P a g e | 141


IT Dept 3151606(WD) Year 2023-24

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

SEM 5 210280116126 P a g e | 142


IT Dept 3151606(WD) Year 2023-24
Output :

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:

1. What is PHP Session?


2. How to destroy PHP Session?
Suggested Reference:

• https://www.w3schools.com/php/php_sessions.asp
References used by the students:

Rubric wise marks obtained:


Rubrics 1 2 3 Total
Marks

SEM 5 210280116126 P a g e | 143


IT Dept 3151606(WD) Year 2023-24

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:

Competency and Practical Skills:

Relevant CO: 6

Objectives:

1. To understand how Ajax works.


Theory:

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.

Ref: https://www.w3schools.com/js/js_ajax_intro.asp Steps:


1. An event occurs in a web page (the page is loaded, a button is clicked)
2. An XMLHttpRequest object is created by JavaScript
3. The XMLHttpRequest object sends a request to a web server
4. The server processes the request

SEM 5 210280116126 P a g e | 144


IT Dept 3151606(WD) Year 2023-24
5. The server sends a response back to the web page
6. The response is read by JavaScript
7. Proper action (like page update) is performed by JavaScript

The keystone of AJAX is the XMLHttpRequest object.

1. Create an XMLHttpRequest object

variable = new XMLHttpRequest();

2. Define a callback function

xhttp.onload = function() {
// What to do when the response is ready
}

3. Open the XMLHttpRequest object

xhttp.open("GET", "ajax_info.txt");

4. Send a Request to a server

xhttp.send();

XMLHttpRequest Object Methods

Method Description

new XMLHttpRequest() Creates a new XMLHttpRequest object

abort() Cancels the current request

getAllResponseHeaders() Returns header information

getResponseHeader() Returns specific header information

SEM 5 210280116126 P a g e | 145


IT Dept 3151606(WD) Year 2023-24

open(method, url, async, user, psw) Specifies the request

method: the request type GET or POST url:


the file location
async: true (asynchronous) or false
(synchronous) user:
optional user name psw:
optional password

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

XMLHttpRequest Object Properties

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")

SEM 5 210280116126 P a g e | 146


IT Dept 3151606(WD) Year 2023-24
Call back function
With the XMLHttpRequest object you can define a callback function to be executed when the
request receives an answer. The function is defined in the onload property of the
XMLHttpRequest object:

xhttp.onload = function() {
document.getElementById("demo").innerHTML = this.responseText;
}
xhttp.open("GET", "ajax_info.txt"); xhttp.send();

The onreadystatechange Property


The readyState property holds the status of the XMLHttpRequest.
The onreadystatechange property defines a callback function to be executed when the
readyState changes. The status property and the statusText properties hold the status of the
XMLHttpRequest object.

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

Status 200: "OK"


403: "Forbidden"
404: "Page not found"
For a complete list go to the Http Messages Reference

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 {

SEM 5 210280116126 P a g e | 147


IT Dept 3151606(WD) Year 2023-24

font-family: Arial, sans-serif;


background-color: #f2f2f2;
text-align: center;
}

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>

<label for="stucourse"><i class="fas fa-book"></i> <b>Course:</b></label>


<select id="stucourse" name="stucourse">
<option value="Course">Course</option>
<option value="BCA">BCA</option>
<option value="BBA">BBA</option>
<option value="B.Tech">B.Tech</option>
<option value="MBA">MBA</option>

SEM 5 210280116126 P a g e | 148


IT Dept 3151606(WD) Year 2023-24

<option value="MCA">MCA</option>
<option value="M.Tech">M.Tech</option>
</select><br>

<label for="gender"><i class="fas fa-user"></i> <b>Gender:</b></label><br>


<input type="radio" id="male" name="gender" value="Male" checked> Male
<input type="radio" id="female" name="gender" value="Female"> Female
<input type="radio" id="other" name="gender" value="Other"> Other<br>

<label for="phone"><i class="fas fa-phone"></i> <b>Phone:</b></label>


<input type="text" name="country code" placeholder="Country Code" value="+91"
size="2" />
<input id="phone" type="text" name="phone" placeholder="phone no." size="10"
required><br><br><br>

<label for="address"><i class="fas fa-address-book"></i> <b>Current


Address:</b></label>
<textarea id="address" cols="30" rows="5" placeholder="Current Address"
name="address"
required></textarea><br><br><br>

<i class="fas fa-envelope"></i> <label for="email"><b>Email</b></label>


<input id="email" type="text" placeholder="Enter Email" name="email"
required><br><br>

<label for="psw"><i class="fas fa-lock"></i> <b>Password</b></label>


<input id="psw" type="password" placeholder="Enter Password" name="psw"
required><br>

<label for="psw_repeat"><b>Re-type Password</b></label>


<input id="psw_repeat" type="password" placeholder="Retype Password"
name="psw_repeat" required><br><br>
<hr>
<lable for="img">Upload Photo:</lable>
<input type="file" id="photo" name="img" accept="document/*"><br>
<br>
<lable for="sign">Upload Signature:</lable>
<input type="file" id="signature" name="sign" accept="image/*"><br>
<br>
<input type="submit" target="_blank" value="Confirm Registration" name="submit_btn">
<input type="reset" value="Reset" name="reset_btn">
<input type="button" value="Update" name="update_btn">
<input type="button" value="Delete" name="delete_btn">
<button type="button" onclick="combineInfo()">Combine Information</button><br><br>
<hr>
</form>

SEM 5 210280116126 P a g e | 149


IT Dept 3151606(WD) Year 2023-24

<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

SEM 5 210280116126 P a g e | 150


IT Dept 3151606(WD) Year 2023-24
Quiz:

1. What is Ajax?
2. Explain XMLHttpRequest.
Suggested Reference:

• https://www.w3schools.com/xml/ajax_intro.asp
References used by the students:

Rubric wise marks obtained:


Rubrics 1 2 3 Total
Marks

SEM 5 210280116126 P a g e | 151


IT Dept 3151606(WD) Year 2023-24

Experiment No: 19

Create a REST API using php.


Date:

Competency and Practical Skills:

Relevant CO: 6

Objectives:

1. To understand how REST API works.


Theory:

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

 POST is used to create new record which is similar to Create


 PUT is used to update record which is similar to Update
 DELETE is used to delete record which is similar to Delete

How to Create and Consume Simple REST API in PHP


JSON format is the most common output format of REST API, we will use the JSON format to
consume our simple REST API. We will developed an online transaction payment REST API
for our example. I will try to keep it as simple as possible so i will use GET request to retrieve
information.
1. Create REST API in PHP
2. Consume REST API in PHP

1. Create REST API in PHP

SEM 5 210280116126 P a g e | 152


IT Dept 3151606(WD) Year 2023-24
To create a REST API, follow these steps:
A. Create a Database and Table with Dummy Data
B. Create a Database Connection
C. Create a REST API File
A. Create a Database and Table with Dummy Data
To create database run the following query.

CREATE DATABASE allphptricks;

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.

CREATE TABLE IF NOT EXISTS `transactions` (


`id` int(20) NOT NULL AUTO_INCREMENT,
`order_id` int(50) NOT NULL,
`amount` decimal(9,2) NOT NULL,
`response_code` int(10) NOT NULL,
`response_desc` varchar(50) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `order_id` (`order_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 ;

B. Create a Database Connection


Just create a db.php file and paste the following database connection in it. Make sure that you
update these credentials with your database credentials.
// Enter your Host, username, password, database below.
$con = mysqli_connect("localhost","root","","allphptricks");
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
die();
}

C. Create a REST API File


Create a api.php file and paste the following script in it.
<?php
header("Content-Type:application/json"); if
(isset($_GET['order_id']) && $_GET['order_id']!="") {
include('db.php');
$order_id = $_GET['order_id'];
$result = mysqli_query(
$con,

SEM 5 210280116126 P a g e | 153


IT Dept 3151606(WD) Year 2023-24
"SELECT * FROM `transactions` WHERE order_id=$order_id");
if(mysqli_num_rows($result)>0){ $row =
mysqli_fetch_array($result);
$amount = $row['amount'];
$response_code = $row['response_code'];
$response_desc = $row['response_desc'];
response($order_id, $amount, $response_code,$response_desc);
mysqli_close($con);
}else{
response(NULL, NULL, 200,"No Record Found");
}
}else{
response(NULL, NULL, 400,"Invalid Request");
}

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

You will get the following output.

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

RewriteRule ^api/([0-9a-zA-Z_-]*)$ api.php?order_id=$1 [NC,L]

Now you can get the transaction information by browsing the following URL.
http://localhost/rest/api/15478959

SEM 5 210280116126 P a g e | 154


IT Dept 3151606(WD) Year 2023-24

You will get the following output.

2. Consume REST API in PHP


To consume a REST API, follow these steps:
1. Create an Index File with HTML Form
2. Fetch Records through CURL
1. Create an Index File with HTML Form
<form action="" method="POST">
<label>Enter Order ID:</label><br />
<input type="text" name="order_id" placeholder="Enter Order ID" required/> <br
/><br />
<button type="submit" name="submit">Submit</button>
</form>

2. Fetch Records through CURL


<?php
if (isset($_POST['order_id']) && $_POST['order_id']!="") {
$order_id = $_POST['order_id'];
$url = "http://localhost/rest/api/".$order_id;

$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.

SEM 5 210280116126 P a g e | 155


IT Dept 3151606(WD) Year 2023-24
Implementation:

Create a REST API using php.


<?php
try {
$conn = mysqli_connect("localhost", "root", "manish@123", "API");
require_once "Practical_19.php";
}catch (Exception $e){
$error = $e->getMessage();
echo $error;
}
$response = array();
if ($conn) {
$sql = "SELECT * FROM users;";
$result = mysqli_query($conn, $sql);
if ($result) {
$x = 0;
while ($row = mysqli_fetch_array($result)) {
$response[$x]['ID'] = $row['ID'];
$response[$x]['Name'] = $row['Name'];
$response[$x]['Age'] = $row['Age'];
$response[$x]['Email'] = $row['Email'];
$x++;
}
echo json_encode($response, JSON_PRETTY_PRINT);
}
} else {
echo "Connection Failed...!!!";
}
Output :

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.

SEM 5 210280116126 P a g e | 156


IT Dept 3151606(WD) Year 2023-24
Quiz:

1. What is REST API?


Suggested Reference:

• https://www.allphptricks.com/create-and-consume-simple-rest-api-in-php/)

References used by the students:

Rubric wise marks obtained:


Rubrics 1 2 3 Total
Marks

SEM 5 210280116126 P a g e | 157


IT Dept 3151606(WD) Year 2023-24

Experiment No: 20

Create an Image slider using jQuery.


Date:

Competency and Practical Skills:

Relevant CO: 6

Objectives:

1. To understand how JQuery Works.


Theory:

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>

The jQuery syntax is tailor-made for selecting HTML elements


and performing some action on the element(s).
Basic syntax is:

SEM 5 210280116126 P a g e | 158


IT Dept 3151606(WD) Year 2023-24
$(selector).action()

• A $ sign to define/access jQuery


• A (selector) to "query (or find)" HTML elements
• A jQuery action() to be performed on the element(s)

Examples:

$(this).hide() - hides the current element.


$("p").hide() - hides all <p> elements.
$(".test").hide() - hides all elements with class="test".
$("#test").hide() - hides the element with id="test".

All jQuery methods in our examples, are inside a document ready event:

$(document).ready(function(){

// jQuery methods go here…

});

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 allow you to select and manipulate HTML element(s).

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: $().

When a user clicks on a button, all <p> elements will be hidden:

$(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.

SEM 5 210280116126 P a g e | 159


IT Dept 3151606(WD) Year 2023-24

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:

Mouse Events Keyboard Events Form Events Document/Window


Events
Click Keypress submit Load
Dblclick Keydown change Resize
Mouseenter Keyup focus Scroll
Mouseleave blur Unload

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:

SEM 5 210280116126 P a g e | 160


IT Dept 3151606(WD) Year 2023-24
$("p").click(function(){
// action goes here!!
});

Commonly Used jQuery Event Methods

$(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:

Create an Image slider using jQuery.


<!DOCTYPE html>
<html>
<head>
<title>Image Slider Gallery</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
.slider {
width: 500px;
height: 300px;
margin: 0 auto;

SEM 5 210280116126 P a g e | 161


IT Dept 3151606(WD) Year 2023-24

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

SEM 5 210280116126 P a g e | 162


IT Dept 3151606(WD) Year 2023-24

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:

SEM 5 210280116126 P a g e | 163


IT Dept 3151606(WD) Year 2023-24

• https://www.w3schools.com/jquery/jquery_intro.asp

References used by the students:

Rubric wise marks obtained:


Rubrics 1 2 3 Total
Marks

SEM 5 210280116126 P a g e | 164


IT Dept 3151606(WD) Year 2023-24

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:

Competency and Practical Skills:

Relevant CO: 6

Objectives:

1. To understand use of COOKIES.


Theory:

Cookie

• Cookie is used to identify a user


• It is a small file which server embeds on the user’s computer
• Each time same computer requests a page with a browser, it will send the cookie also.
• Using PHP cookies values can be created and retrieved.

Create Cookies With PHP

setcookie() function is used to create a cookie

Syntax

setcookie(name, value, expire, path, domain, secure, httponly);

Here name parameter is required while other parameters are optional.

PHP Create and Retrieve a Cookie

Example

SEM 5 210280116126 P a g e | 165


IT Dept 3151606(WD) Year 2023-24

<?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.

For cookie modification again use setcookie() function.

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>

SEM 5 210280116126 P a g e | 166


IT Dept 3151606(WD) Year 2023-24

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) {

SEM 5 210280116126 P a g e | 167


IT Dept 3151606(WD) Year 2023-24

const value = `; ${document.cookie}`;


const parts = value.split(`; ${name}=`);
if (parts.length === 2) return parts.pop().split(';').shift();
}

const savedColor = getCookie("backgroundColor");


if (savedColor) {
document.body.style.backgroundColor = savedColor;
}
</script>
</body>
</html>
Output :

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

References used by the students:

Rubric wise marks obtained:

Rubrics 1 2 3 Total
Marks

SEM 5 210280116126 P a g e | 168

You might also like