0% found this document useful (0 votes)
7 views24 pages

Iicsa Php Lab

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

Iicsa Php Lab

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

EX.

NO: 1 Develop a PHP program using controls and functions

AIM:

To create a PHP program that demonstrates the use of controls (such as loops,
conditionals) and user- defined functions.

ALGORITHM:

STEP 1: Accepts input from the user (e.g., a number).

STEP 2: Validates the input (e.g., check if it’s a positive integer

STEP 3: Performs an operation (e.g., calculates the factorial of a number )

. STEP 4: Displays the result to the user.


SOURCE CODE:

<html>
<head>

</head>
<body>
<h4>Factorial of a Given Number</h4>
<?php
if(isset($_POST['submit'])){
function fact($n){
if($n <= 1){
return 1;
}
else{
return $n * fact($n - 1);
}
}
$n =$_POST['number'];
$f = fact($n);
echo "Factorial of $n is $f";
}
?>
<form method="post">
<p>Enter the Number </p>
<input type="text" name="number" required>
<input type="submit" name="submit">
</form>
</body>
</html>
EX.NO:2 Develop a PHP program and check message passing mechanism between
pages.

AIM

To create a PHP program that passes messages between different pages using

sessions.

ALGORITHMS:

STEP 1: Input Page:

Create an HTML form that collects user input (e.g., name, email, or any

relevant data). Submit the form to a PHP script for processing.

STEP 2: Processing Page:

In the PHP script that receives the form submission, validate the

input data. If the data is valid, set a success message in a session

variable.

If there are errors, set an error message in the

session. STEP 3: Output Page:

Redirect the user to another page


SOURCE CODE:

Form.html

<html>
<head>
<title>Simple Form</title>
</head>
<body>
<h1>Simple Form</h1>
<form action="process_form.php" method="post">
Name:<input type="text" name="name"><br><br>
Email:<input type="email" id="email" name="email"><br><br>
Message:<textarea id="message" name="message" rows="5"
cols="30"></textarea><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
process_form.php:
<html>
<head>
<title>Form Data</title>
</head>
<body>
<h1>Form Data</h1>
<?php
echo "Name: " . $_POST['name'] . "<br>";
echo "Email: " . $_POST['email'] . "<br>";
echo "Message: " . $_POST['message'] . "<br>";
?>
<form action="form.php">
<input type="submit" value="message again">
</form>
</body>
</html>
EX.NO:3 Develop a PHP program using String function and Arrays.

AIM:

To create a PHP program that demonstrates the use of string functions and arrays.

ALGORITHM:

SETP 1: Input:

Prompt the user to enter a string (e.g., their name or any other text).

SETP 2: String Functions:

Use PHP string functions to perform the required operations (uppercase


conversion, length calculation, and string reversal).

STEP: 3 Array Creation:

Create an array to store the individual characters of the string.

STEP 4: Output Display:

Display the transformed string (uppercase, length, and reversed) along with the
array of characters.
SOURCE CODE:
<html>
<html>
<head>

<title>PHP String and Array </title>


</head>
<body>
<h1>PHP String and Array </h1>

<?php

$text = "Hello, welcome to PHP!";


$upperText = strtoupper($text); // Convert string to uppercase

$fruits = array("Apple", "Banana", "Cherry", "Date");

echo "<h2>Original String:</h2><p>$text</p>";


echo "<h2>Uppercase String:</h2><p>$upperText</p>";

echo "<h2>Fruits Array:</h2><ul>";


foreach($fruits as $fruit) {
echo "<li>$fruit</li>";
}
echo "</ul>";
?>
</body>
</html>
EX.NO: 4 Develop a PHP program to display student information using MYSQL
table.

AIM:
To create a PHP program to display student information using MYSQL table

ALGORITHM:

STEP: 1 Database Setup:

Create a MySQL database (if not already done).

Inside the database, create a table named students with the following

columns: id (auto-increment primary key)

name (student’s name)

roll_number (student’s roll number)

STEP: 2 Connect to the Database:

Establish a connection to the MySQL database using PHP.

Use appropriate credentials (hostname, username, password, and database


name).

STEP: 3 Retrieve Student Data:

Write a SQL query to retrieve all records from the student’s

table. Execute the query and fetch the results.

STEP: 4 Display Student Information:

Iterate through the fetched

records.

Display each student’s name and roll number.

STEP: 5 Close the Database Connection:

Close the database connection to free up resources.


SOURCE CODE:

<html>
<head>
<title>Student Information Form</title>
</head>
<body>
<form method="post">
Name of the student: <input type="text" name="full_name"><br><br>
Email ID: <input type="text" name="email"><br><br>
Phone Number: <input type="text" name="phone_number"><br><br>
<input type="submit" name="OK" value="Submit">
<input type="submit" name="DISPLAY" value="Display Data">
</form>

<?php
$con = mysqli_connect("localhost", "root", "", "student");
if (isset($_POST['OK']))
{
$full_name = mysqli_real_escape_string($con, $_POST['full_name']);
$email = mysqli_real_escape_string($con, $_POST['email']);
$phone_number = mysqli_real_escape_string($con, $_POST['phone_number']);
$sql = $con->prepare("INSERT INTO `college` (`full_name`, `email`, `phone_number`)
VALUES (?, ?, ?)");
$sql->bind_param("sss", $full_name, $email, $phone_number);
$sql->execute();
echo "Data has been successfully submitted!";
}
if (isset($_POST['DISPLAY'])) {
$result = mysqli_query($con, "SELECT * FROM `college`");
if ($result)
{
echo "<table border='1'>";
echo "<tr><th>Name</th><th>Email</th><th>Phone Number</th></tr>";
while ($row = mysqli_fetch_assoc($result)) {
echo "<tr><td>" . $row['full_name'] . "</td><td>" . $row['email'] . "</td><td>" .
$row['phone_number'] . "</td></tr>";
}
echo "</table>";
} else
{
echo "No data found.";
}
}
?>
</body>
</html>
EX.NO: 5 Develop a PHP program to design a college application form using

MYSQL table.

AIM:

ALGORITHM:

STEP: 1 Database Setup:

Create a MySQL database (if not already done).

Inside the database, create a table named college_applications with the


following columns:

id (auto-increment primary key)

full_name (applicant’s full name)

email (applicant’s email

address)

phone_number (applicant’s phone number)

Other relevant columns (e.g., address, program of interest,

etc.) STEP: 2 HTML Form Creation:

Create an HTML form that collects applicant information.

Include input fields for full name, email, phone number, and other relevant

details. Use appropriate form elements (text fields, radio buttons,

checkboxes, etc.).

STEP: 3 PHP Script for Form Submission:

Write a PHP script that handles form submission.

Retrieve data from the submitted form (using $_POST or

$_GET). Validate the input data (e.g., check if email format

is valid).
STEP: 4 Insert Data into MySQL Table:

Establish a connection to the MySQL database using

PHP. Insert the form data into the

college_applications table.

Use prepared statements to prevent SQL injection.


SOURCE CODE:

<html>
<head>
<style>
div {
align: center; width: 400px; height: 300px; border: solid black;
background-color: orange; padding: 20px;
}
</style>
</head>
<body>
<div>
<h1>COLLEGE APPLICATION FORM </h1>
<form method="post">
Name: <input type="text" name="name"><br><br>
Roll Number: <input type="text" name="rollNumber"><br><br><br>
EMailid:<input type="text" name="mailid"><br><br>
<input type="submit" name="OK">
</form>
<?php
$con = mysqli_connect("localhost", "root", "", "student");
if (isset($_POST['OK']))
{
$name = $_POST['name'];
$rollNumber = $_POST['rollNumber'];
$mailid = $_POST['mailid'];

$sql = mysqli_query($con, "INSERT INTO `student1`(`name`, `rollNumber`, `mailid`)


VALUES ('$name', '$rollNumber','$mailid')");
}
?>
</div>
</body>
</html>
EX.NO: 6 Develop a PHP program using parsing functions (use Tokenizing)

AIM:

To Develop a PHP program using parsing functions (use Tokenizing)


ALGORITHM:

STEP: 1 Enable the PHP Tokenizer Library:

Ensure that the PHP Tokenizer extension is enabled in your PHP configuration
(usually found in php.ini). Remove the semicolon (;) from the line that starts
with extension=tokenizer.

STEP: 2 Create a PHP File:

Create a new PHP file (e.g.,

parse_code.php). Write Code to Parse:

Write or obtain the PHP code that you want to tokenize and parse. This can be
any valid PHP code snippet.

STEP: 3 Use token_get_all Function:

Use the token_get_all function to tokenize the input code.

This function takes the input code as a string and returns an array of tokens.

Each token can be a single character or an array with three elements: the token
ID, the token text, and the line number where the token appears in the code.

STEP:4 Process the Tokens:

Iterate through the array of tokens.

If the token is a string, it represents a simple 1-character token (e.g.,

parentheses). If the token is an array, extract the token ID and text.

You can use the token_name function to convert the token ID to a human-
readable string.
STEP: 5 Display or Manipulate the Tokens:

sourcecode

<?php
$code = 'echo "Hello, world!";';

$tokens = token_get_all($code);

foreach ($tokens as $token) {


if (is_array($token)) {
echo token_name($token[0]) . ": " . $token[1] . PHP_EOL;
} else {
echo $token . PHP_EOL;
}
}
?>
EX.NO: 7 Develop a PHP program and check Regular Expression, HTML functions,
Hashing functions.
AIM:
To develop a PHP program and check Regular Expression, HTML functions,
Hashing functions.

ALGORITHM:
STEP: 1 Regular Expressions (Regex):

Regular expressions are used to match patterns within strings.

Define the specific patterns you want to search for (e.g., email addresses,
phone numbers, etc.).

Use the preg_match or preg_match_all functions to check if a string matches


the specified pattern.

STEP: 2 HTML Functions:

HTML functions in PHP allow you to generate HTML content

dynamically. Use functions like echo, print, or printf to output HTML

tags and content.

You can also use loops and conditionals to create dynamic HTML structures.

STEP: 3 Hashing Functions:

Hashing functions are used to convert data (such as passwords) into fixed-
length hash values.

Common hashing functions in PHP include md5, sha1, and

password_hash. Use these functions to securely store sensitive data

(e.g., user passwords).

STEP: 4 Combine Everything:

Create a PHP file that includes regular expressions, HTML functions, and
hashing functions.

Define sample data (e.g., an email address, HTML content, or a

password). Apply regular expressions to validate the data.

Generate HTML output using PHP functions.


Hash sensitive data using appropriate hashing functions.
SOURCE CODE:

<?php

$email = 'user@example.com';
if (preg_match('/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/', $email))
{
echo "Valid email address: $email<br><br>";
} else {
echo "Invalid email address<br>";
}

echo "<p>Welcome to our website!</p>";

$password = 'my_secure_password';
$hashedPassword = password_hash($password, PASSWORD_DEFAULT);
echo "Hashed password: $hashedPassword<br><br><br>";
?>
EX.NO: 8. Develop a PHP program and check File System functions, Network
functions, Date and time functions.

AIM:
To develop a PHP program and check File System functions, Network functions, Date
and time functions.

ALGORITHM:
STEP: 1 File System Functions:

File system functions allow you to interact with files and directories on the
server.

Use functions like fopen, file_get_contents, file_put_contents, and unlink to


read, write, and delete files.

Create, move, and manipulate directories using functions like mkdir, rmdir, and
scandir.

STEP: 2 Network Functions:

Network functions involve communication over networks (e.g., HTTP requests,


socket programming).

Use functions like file_get_contents (for fetching data from URLs), curl (for more
advanced HTTP requests), and fsockopen (for socket connections).

STEP: 3 Date and Time Functions:

PHP provides built-in functions to work with dates and times.

Use functions like date, strtotime, time, and strftime to format, parse, and
manipulate dates and times.

STEP: 4 Combine Everything:

Create a PHP file that includes examples of file system operations, network
requests, and date/time manipulations.

Customize the code according to your specific use case.


SOURCE CODE:
<?
php
echo "<h2>File System Functions:</h2>";

$file = 'example.txt';
if (file_exists($file))
{
echo "The file '$file' exists.<br>";
}
else
{
echo "The file '$file' does not exist.<br>";
}

if (is_file($file))
{
echo "'$file' is a regular file.<br>";
}
else
{
echo "'$file' is not a regular file.<br>";
}

$dir = 'exampleDir';
if (is_dir($dir))
{
echo "'$dir' is a directory.<br>";
}
else
{
echo "'$dir' is not a directory.<br>";
}
if (file_exists($file))
{
echo "The size of '$file' is " . filesize($file) . " bytes.<br>";
}
else
{
echo "File '$file' does not exist to get its size.<br>";
}

echo "<h2>Network Functions:</h2>";


$hostname = gethostname();
echo "The hostname of this machine is: $hostname<br>";
$ip = gethostbyname($hostname);
echo "The IP address of '$hostname' is: $ip<br>";
$server_name = $_SERVER['SERVER_NAME'];
echo "The server name is: $server_name<br>";
$host = 'www.google.com';
$port = 80;
$connection = @fsockopen($host, $port);
if (is_resource($connection))
{
echo "The host '$host' is reachable.<br>";
fclose($connection);
} else {
echo "The host '$host' is not reachable.<br>";
}
echo "<h2>Date and Time Functions:</h2>";

echo "The current date and time is: " . date('Y-m-d H:i:s') . "<br>";

echo "The current timestamp is: " . time() . "<br>";


echo "Formatted date: " . date('l, F j, Y') . "<br>";

$next_day = date('Y-m-d', strtotime('+1 day'));


echo "Tomorrow's date will be: $next_day<br>";
echo "Today is: " . date('l') . "<br>";
$timestamp = time();
echo "The timestamp " . $timestamp . " corresponds to: " . date('Y-m-d H:i:s', $timestamp) . "<br>";

?>
EX.NO: 9. Develop a PHP program using

session.

AIM:

To develop a PHP program using session.

ALGORITHM:

STEP: 1 Start a Session:

At the beginning of your PHP script, call session_start() to start a new

session. This initializes a session or resumes an existing one.

STEP: 2 Store Data in Session Variables:

Use the $_SESSION superglobal array to store session data.

Assign values to session variables (e.g., $_SESSION['username'] = 'TAMIL';).

STEP: 3 Access Session Data:

Retrieve session data by accessing the session

variables. For example: $username =

$_SESSION['username'];.

STEP: 4 Modify Session Data:

Update session variables as needed during the user’s session.

STEP: 5 SET SESSION USER NAME:

When the user logs out or their session expires, call $_SESSION['username']
Source Code:
start_session
<?php
session_start();

$_SESSION['username'] = 'Tamil';

echo "Session variable 'username' has been set.<br>";


echo "<a href='display_session.php'>Go to Display Page</a>";
?>

display_session.php

<?php
session_start();

if(isset($_SESSION['username'])){
echo "Welcome, " . $_SESSION['username'] . "!";
} else {
echo "Session variable 'username' is not set.";
}
?>
EX.NO:10 Develop a PHP program using cookie and

session. AIM:

To develop a PHP program using cookie and

session. ALGORITHM:

STEP: 1 Cookies:

Cookies are small pieces of data stored on the client-side (user’s

browser). They are used to persist information across different

requests.

STEP: 2 To create a cookie:

Use the setcookie function with the desired cookie name, value, and optional
parameters (such as expiration time, path, and domain).

STEP: 3 Sessions:

Sessions are server-side mechanisms to store user-specific data.

A session is unique for each user and lasts until the user closes the browser or
logs out.

STEP: 4 To use sessions:

Start a session using session_start().

Store data in the $_SESSION superglobal

array. Retrieve and manipulate session data

as needed.

STEP: 5 Combine Cookies and Sessions:

Set a cookie with a unique identifier (e.g., user ID).

Use the session to store user-specific data (e.g., username, role).


SOURCE CODE:
<?php
session_start();
if (isset($_SESSION['visited'])) {
$_SESSION['username'] = 'TAMIL';

echo "Welcome back, " . $_SESSION['username'] . "!<br>";


$_SESSION['visit_count']++;
echo "You have visited " . $_SESSION['visit_count'] . " times.";
} else {
$_SESSION['username'] = 'TAMIL';
setcookie('username', $_SESSION['username'], time() + 3600);
$_SESSION['visited'] = true;
$_SESSION['visit_count'] = 1;
echo "Welcome to our site, " . $_SESSION['username'] . "!<br>";
echo "This is your first visit.";
}
?>

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy