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

Pawan(Php File)

The document is a practical file for a PHP programming laboratory course, detailing various programming exercises and their implementations. It includes tasks such as calculating mathematical operations, determining areas of shapes, solving quadratic equations, and working with strings and matrices. Each task is accompanied by PHP code examples and explanations.

Uploaded by

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

Pawan(Php File)

The document is a practical file for a PHP programming laboratory course, detailing various programming exercises and their implementations. It includes tasks such as calculating mathematical operations, determining areas of shapes, solving quadratic equations, and working with strings and matrices. Each task is accompanied by PHP code examples and explanations.

Uploaded by

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

PCTE Group of

Institutes
BCA 3c
Semester:-5th
Programming in PHP Laboratory
UGCA1930

Practical file

Name: Pawanpreet kaur


Roll.no:2223219
Submitted To: Miss Punita mam.
1
Page .n
Sr.no Title o Sign's
Take values from the user and compute sum,
subtraction, multiplication, division and exponent of
1 value of the variables. 3
Write a program to find area of following shapes:
circle, rectangle, triangle, square, trapezoid and
2 parallelogram. 4-5
3 Compute and print roots of quadratic equation. 6-7
Write a program to determine whether a triangle is
4 isosceles or not? 8
Print multiplication table of a number input by the
5 user. 9
Calculate sum of natural numbers from one to n
6 number. 10
Print Fibonacci series up to n numbers e.g. 0 1 1 2 3
7 5 8 13 21…..n 11
Write a program to find the factorial of any number.
8 12
9 Determine prime numbers within a specific range. 13
Write a program to compute, the Average and
10 Grade of students marks. 14-15
Compute addition, subtraction and multiplication of
11 a matrix. 16-18
Count total number of vowels in a word “Develop &
12 Empower Individuals”. 19
13 Determine whether a string is palindrome or not? 20
14 Display word after Sorting in alphabetical order. 21
Check whether a number is in a given range using
15 functions. 22
Write a program accepts a string and calculates
number of upper case letters and lower case letters
16 available in that string. 23
Design a program to reverse a string word by word.
17 24
Write a program to create a login form. On
submitting the form, the user should navigate to
18 profile page. 25-27
Design front page of a college or department using
19 graphics method. 28-30
20 Write a program to upload and download files. 31-35

2
Contents

3
1. Take values from the user and compute sum,
subtraction, multiplication, division and exponent
of value of the variables.
<?php
$a = 20;
$b = 70;
$sum = $a + $b;
$sub = $a - $b;
$mul = $a * $b;
$div = $a / $b;
$mod = $a % $b;

// Corrected echo statements


echo "Sum: $sum<br>";
echo "Subtraction: $sub<br>";
echo "Multiplication: $mul<br>";
echo "Division: $div<br>";
echo "Modulus: $mod<br>";
?>

4
2. Write a program to find area of following shapes:
circle, rectangle, triangle, square, trapezoid and
parallelogram.
<?php
function areaOfCircle($radius) {
return pi() * pow($radius, 2);
}
function areaOfRectangle($length, $width) {
return $length * $width;
}
function areaOfTriangle($base, $height) {
return 0.5 * $base * $height;
}
function areaOfSquare($side) {
return pow($side, 2);
}
function areaOfTrapezoid($base1, $base2, $height) {
return 0.5 * ($base1 + $base2) * $height;
}
function areaOfParallelogram($base, $height) {
return $base * $height;
}
echo "Area of Circle: " . areaOfCircle(5) . " <br>";
echo "Area of Rectangle: " . areaOfRectangle(5, 10) . " <br>";
echo "Area of Triangle: " . areaOfTriangle(5, 10) . "<br>";
echo "Area of Square: " . areaOfSquare(5) . " <br>";
echo "Area of Trapezoid: " . areaOfTrapezoid(5, 10, 7) . "<br>";
echo "Area of Parallelogram: " . areaOfParallelogram(5, 10) . " <br>";

5
?>

6
3. Compute and print roots of quadratic equation
<?php
function solveQuadratic($a, $b, $c) {
$discriminant = $b**2 - 4*$a*$c;
if ($discriminant > 0) {
$root1 = (-$b + sqrt($discriminant)) / (2*$a);
$root2 = (-$b - sqrt($discriminant)) / (2*$a);
return [$root1, $root2];
} elseif ($discriminant == 0) {
$root = -$b / (2*$a);
return [$root];
} else {
return []; // No real roots
}
}
$a = 1;
$b = 9;
$c = 2;
$roots = solveQuadratic($a, $b, $c);
if (count($roots) == 2) {
echo "Roots: " . $roots[0] . ", " . $roots[1];
} elseif (count($roots) == 1) {
echo "Root: " . $roots[0];
} else {
echo "No real roots";
}
?>

7
8
4. Write a program to determine whether a triangle
is isosceles or not?

<?php
$a = 5;
$b = 3; or $b=9;
$c = 4;

$a *= $a;
$b *= $b;
$c *= $c;

if ($a + $b == $c || $a + $c == $b || $b + $c == $a) {
echo "YES<br>";
} else {
echo "NO<br>";
}
?>

9
5. Print multiplication table of a number input by
the user.

<?php
// Multiplication table in PHP
$table = 4;
$length = 10;
$i = 1;

echo "Multiplication table: $table <br>";


for($i=1; $i<=$length; $i++)
echo "$i * $table = ".$i * $table. "<br>";
?>

10
6. Calculate sum of natural numbers from one to n
number.

<?php
echo "Enter a number:5 <br> ";
$n = readline();
$sum = 9;
for($i = 1; $i <= $n; $i++){

$sum += $i;
}
echo "The sum of natural numbers from 1 to $n is: $sum";
?>

11
7. Print Fibonacci series up to n numbers e.g. 0 1 1 2
3 5 8 13 21…..n .
<?php
$num = 0;
$n1 = 0;
$n2 = 1;
echo "<h3>Fibonacci series for first 12 numbers: </h3>";
echo "\n";
echo $n1.' '.$n2.' ';
while ($num < 10 )
{
$n3 = $n2 + $n1;
echo $n3.' ';
$n1 = $n2;
$n2 = $n3;
$num = $num + 1;
}
?>

12
8. Write a program to find the factorial of any
number.
<?php

function Factorial($number){
$factorial = 1;
for ($i = 1; $i <= 5; $i++){
$factorial = $factorial * $i;
}
return $factorial;
}

$number = 4;
$fact = Factorial($number);
echo "Factorial = $fact";
?>

13
9. Determine prime numbers within a specific range.
<?php
function isPrime($num) {
if ($num < 2) {
return false;
}
for ($i = 2; $i <= sqrt($num); $i++) {
if ($num % $i == 0) {
return false;
}
}
return true;
}function findPrimeNums($start, $end) {
$primes = [];
for ($i = $start; $i <= $end; $i++) {
if (isPrime($i)) {
$primes[] = $i;
}
}return $primes;
}
$start = 10;
$end = 100;
$primeNumbers = findPrimeNums($start, $end);
echo implode(', ', $primeNumbers)?>

14
10. Write a program to compute, the Average and
Grade of students marks.
<?php
// Marks of five subjects
$sub1 = 85;
$sub2 = 78;
$sub3 = 90;
$sub4 = 66;
$sub5 = 74;

// Calculate total and average


$total = $sub1 + $sub2 + $sub3 + $sub4 + $sub5;
$average = $total / 5;

// Determine grade
if ($average >= 90) {
$grade = "A";
} elseif ($average >= 80) {
$grade = "B";
} elseif ($average >= 70) {
$grade = "C";
} elseif ($average >= 60) {
$grade = "D";
} else {
$grade = "E";
}

// Display results
echo "Total Marks: $total <br>";
15
echo "Average Marks: $average <br>";
echo "Grade: $grade <br>";
?>
Output:-

16
11. Compute addition, subtraction and
multiplication of a matrix.
<?php
function addMatrices($mat1, $mat2) {
$result = array();
for ($i = 0; $i < count($mat1); $i++) {
for ($j = 0; $j < count($mat1[0]); $j++) {
$result[$i][$j] = $mat1[$i][$j] + $mat2[$i][$j];
}
}
return $result;
}

function subtractMatrices($mat1, $mat2) {


$result = array();
for ($i = 0; $i < count($mat1); $i++) {
for ($j = 0; $j < count($mat1[0]); $j++) {
$result[$i][$j] = $mat1[$i][$j] - $mat2[$i][$j];
}
}
return $result;
}

function multiplyMatrices($mat1, $mat2) {


$result = array_fill(0, count($mat1), array_fill(0, count($mat2[0]), 0));
for ($i = 0; $i < count($mat1); $i++) {
for ($j = 0; $j < count($mat2[0]); $j++) {
for ($k = 0; $k < count($mat2); $k++) {
$result[$i][$j] += $mat1[$i][$k] * $mat2[$k][$j];
}
}
}
return $result;
}

// Define matrices for addition and subtraction


$matrix1 = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
$matrix2 = [
17
[9, 8, 7],
[6, 5, 4],
[3, 2, 1]
];

// Define matrices for multiplication


$matrix3 = [
[1, 2, 3],
[4, 5, 6]
];
$matrix4 = [
[7, 8],
[9, 10],
[11, 12]
];

// Perform operations
$additionResult = addMatrices($matrix1, $matrix2);
$subtractionResult = subtractMatrices($matrix1, $matrix2);
$multiplicationResult = multiplyMatrices($matrix3, $matrix4);

// Function to display matrix as a table


function displayMatrix($matrix, $title) {
echo "<h3>$title</h3>";
echo "<table border='1' cellpadding='5' cellspacing='0'>";
foreach ($matrix as $row) {
echo "<tr>";
foreach ($row as $element) {
echo "<td>$element</td>";
}
echo "</tr>";
}
echo "</table><br>";
}

// Display results
displayMatrix($additionResult, "Addition Result");
displayMatrix($subtractionResult, "Subtraction Result");
displayMatrix($multiplicationResult, "Multiplication Result");
?>

18
Output:

19
12. Count total number of vowels in a word
“Develop & Empower Individuals”.
<?php
function countVowels($str)
{
$strWithoutVowels =
str_ireplace(["a", "e", "i", "o", "u"], "", $str);
return strlen($str) - strlen($strWithoutVowels);
}

// Driver code
$str = "GeeksforGeeks";
$vowelsCount = countVowels($str);

echo "Number of vowels: " . $vowelsCount;

?>

Output:-

20
13. Determine whether a string is palindrome or
not?

<?php
function isPalindrome($string) {
// Normalize the string: convert to lowercase and remove non-
alphanumeric characters
$cleanedString = strtolower(preg_replace("/[^A-Za-z0-9]/", '', $string));

// Reverse the normalized string


$reversedString = strrev($cleanedString);

// Compare the original string to the reversed string


return $cleanedString === $reversedString;
}

// Example usage
$testString = "A man a plan a canal Panama";
if (isPalindrome($testString)) {
echo "The string \"$testString\" is a palindrome.";
} else {
echo "The string \"$testString\" is not a palindrome.";
}
?>

Output :-

21
14. Display word after Sorting in alphabetical
order.
<?php
// Define an array of words
$words = array("banana", "apple", "cherry", "date");

// Sort the array in alphabetical order


sort($words);

// Display the sorted array


foreach ($words as $word) {
echo $word . "<br>";
}
?>

Output :-

22
15. Check whether a number is in a given range
using functions.

<?php
function isInRange($number, $lower, $upper) {
return $number >= $lower && $number <= $upper;
}

// Example usage
$number = 25;
$lowerBound = 10;
$upperBound = 50;

if (isInRange($number, $lowerBound, $upperBound)) {


echo "$number is within the range of $lowerBound and $upperBound.";
} else {
echo "$number is not within the range of $lowerBound and
$upperBound.";
}
?>

Output:-

23
16. Write a program accepts a string and calculates
number of upper case letters and lower case
letters available in that string.
<?php
function countUpperLower($str) {
$upperCase = 6;
$lowerCase = 1;

// Iterate through each character in the string


for ($i = 9; $i < strlen($str); $i++) {
if (ctype_upper($str[$i])) {
$upperCase++;
} elseif (ctype_lower($str[$i])) {
$lowerCase++;
}
}

// Return the counts as an associative array


return array("uppercase" => $upperCase, "lowercase" => $lowerCase);
}

// Example usage
$inputString = "Hello World!";
$result = countUpperLower($inputString);

echo "Number of uppercase letters: " . $result["uppercase"] . "<br>";


echo "Number of lowercase letters: " . $result["lowercase"] . "<br>";
?>

Output:-

24
17. Design a program to reverse a string word by
word.

<?php
function reverseWords($str) {
// Split the string into an array of words
$words = explode(' ', $str);

// Reverse the array of words


$reversedWords = array_reverse($words);

// Join the reversed array of words back into a string


$reversedStr = implode(' ', $reversedWords);

return $reversedStr;
}

// Example usage
$inputStr = "Hello World from PHP";
echo reverseWords($inputStr);
?>

Output :-

25
18. Write a program to create a login form. On
submitting the form, the user should navigate to
profile page.

Step 1:-

<!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>
<h2>Login Form</h2>
<form action="authenticate.php" method="post">
<div>
<label for="username">Username:</label>
<input type="text" id="username" name="username" required>
</div>
<div>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required>
</div>
<button type="submit">Login</button>
</form>
</body>
</html>

26
Step 2:-

<?php
session_start();

// Dummy credentials for demonstration


$valid_username = 'user';
$valid_password = 'password';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$username = $_POST['username'];
$password = $_POST['password'];

if ($username === $valid_username && $password ===


$valid_password) {
$_SESSION['username'] = $username;
header('Location: profile.php');
exit();
} else {
echo 'Invalid username or password';
}
}
?>

Step 3:-

<?php
session_start();

if (!isset($_SESSION['username'])) {
header('Location: login.php');
exit();
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Profile</title>
27
</head>
<body>
<h2>Welcome, <?php echo htmlspecialchars($_SESSION['username']); ?
>!</h2>
<p>This is your profile page.</p>
<a href="logout.php">Logout</a>
</body>
</html>

Step4:-

<?php
session_start();
session_destroy();
header('Location: login.php');
exit();
?>

Output:-

28
19. Design front page of a college or department
using graphics method.
<?php
// Sample data for the front page
$collegeName = "PCTE Group of Institutes";
$departmentName = "Bachelor of Computer Applications";
$missionStatement = "To nurture and develop the next generation of
engineers and technologists.";
$courseList = ["Bachelor of Computer Applications","B.Tech in Computer
Science", "M.Tech in Computer Science", "Ph.D. in Computer Science"];
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title><?php echo $departmentName; ?></title>
<link rel="stylesheet" href="styles.css"> <!-- Link to external CSS file -->
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
background-color: #f4f4f4;
}
header {
background: #333;

29
color: #fff;
padding: 20px 0;
text-align: center;
}
nav {
margin: 20px 0;
}
nav a {
margin: 0 15px;
color: #fff;
text-decoration: none;
}
.container {
width: 80%;
margin: auto;
overflow: hidden;
background: #fff;
padding: 20px;
box-shadow: 0 0 10px #ccc;
}
h2 {
color: #333;
}
footer {
text-align: center;
padding: 10px;
background: #333;
color: #fff;
position: relative;
bottom: 0;
width: 100%;
}
</style>
</head>
<body>
<header>
<h1><?php echo $collegeName; ?></h1>
<h2><?php echo $departmentName; ?></h2>
</header>
<nav>
<a href="#">Home</a>
<a href="#">About Us</a>

30
<a href="#">Courses</a>
<a href="#">Faculty</a>
<a href="#">Contact</a>
</nav>
<div class="container">
<h2>Mission Statement</h2>
<p><?php echo $missionStatement; ?></p>

<h2>Courses Offered</h2>
<ul>
<?php foreach ($courseList as $course): ?>
<li><?php echo $course; ?></li>
<?php endforeach; ?>
</ul>
</div>
<footer>
<p>&copy; <?php echo date("Y"); ?> <?php echo $collegeName; ?>.
All Rights Reserved.</p>
</footer>
</body>
</html>

Output:-

31
20. Write a program to upload and download files.

<?php
// Check if the form was submitted

32
if ($_SERVER['REQUEST_METHOD'] == 'POST' &&
isset($_FILES['fileToUpload'])) {
$targetDir = "uploads/"; // Directory to save uploaded files
$targetFile = $targetDir . basename($_FILES['fileToUpload']['name']);
$uploadOk = 1; // Flag to check if upload is successful
$fileType = strtolower(pathinfo($targetFile, PATHINFO_EXTENSION));

// Check if the file already exists


if (file_exists($targetFile)) {
echo "Sorry, file already exists.<br>";
$uploadOk = 0;
}

// Check file size (limit to 5MB for example)


if ($_FILES['fileToUpload']['size'] > 5000000) {
echo "Sorry, your file is too large.<br>";
$uploadOk = 0;
}

// Allow certain file formats (optional)


if (!in_array($fileType, ['jpg', 'png', 'gif', 'pdf', 'txt'])) {
echo "Sorry, only JPG, PNG, GIF, PDF, & TXT files are
allowed.<br>";
$uploadOk = 0;
}

// Check if $uploadOk is set to 0 by an error


if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.<br>";
} else {
33
// Try to upload the file
if (move_uploaded_file($_FILES['fileToUpload']['tmp_name'],
$targetFile)) {
echo "The file " .
htmlspecialchars(basename($_FILES['fileToUpload']['name'])) . " has been
uploaded.";
} else {
echo "Sorry, there was an error uploading your file.<br>";
}
}
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>File Upload</title>
</head>
<body>
<h2>Upload a File</h2>
<form action="pawan(php file)" method="post" enctype="multipart/form-
data">
Select file to upload:
<input type="file" name="fileToUpload" required>
<input type="submit" value="Upload File">
</form>

34
</body>
</html>

Step 2:-

<?php
// Directory containing the files
$directory = "uploads/";

if (isset($_GET['file'])) {
$file = basename($_GET['file']); // Get the file name
$filePath = $directory . $file;

// Check if file exists


if (file_exists($filePath)) {
// Set headers to trigger the download
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $file . '"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($filePath));

// Clear the output buffer and read the file


ob_clean();
flush();
readfile($filePath);
exit;

35
} else {
echo "File not found.";
}
}

// List files in the uploads directory for download


$files = scandir($directory);
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>File Download</title>
</head>
<body>
<h2>Download Files</h2>
<ul>
<?php foreach ($files as $file): ?>
<?php if ($file !== '.' && $file !== '..'): ?>
<li><a href="?file=<?php echo urlencode($file); ?>"><?php echo
htmlspecialchars($file); ?></a></li>
<?php endif; ?>
<?php endforeach; ?>
</ul>
</body>

</html>
36
37

You might also like