0% found this document useful (0 votes)
10 views18 pages

WP PROGRAM AND OUTPUT 1

Uploaded by

sanu mathew
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
10 views18 pages

WP PROGRAM AND OUTPUT 1

Uploaded by

sanu mathew
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 18

PROGRAM :8

Write a program in PHP to change background color based


on day of the week using if else if statements and using
arrays

<!DOCTYPE html>
<html>
<head>
<title>Color Change by Day</title>
<?php
// Array of days with corresponding colors
$daysOfWeek = array(
'Sunday' => '#FF5733',
'Monday' => '#33FF57',
'Tuesday' => '#3357FF',
'Wednesday' => '#FFFF33',
'Thursday' => '#FF33FF',
'Friday' => '#33FFFF',
'Saturday' => '#FF3333'
);

// Get the current day


$currentDay = date('l'); // Full textual representation of the day
$backgroundColor = '#FFFFFF'; // Default color

// Check if the current day exists in the array


if (array_key_exists($currentDay, $daysOfWeek)) {
$backgroundColor = $daysOfWeek[$currentDay];
}
?>
<style>
body {
background-color: <?php echo $backgroundColor; ?>;
}
</style>
</head>
<body>
<h1>Welcome! Today is <?php echo $currentDay; ?>.</h1>
</body>
</html>

OUTPUT:

PROGRAM: 9
Write a simple program in PHP for i) generating Prime
number ii) generate Fibonacci series.
o<?php
function generatePrimes($maxNumber) {
echo "Prime numbers up to $maxNumber: ";
for ($number = 2; $number <= $maxNumber; $number++) {
$isPrime = true;
for ($i = 2; $i <= sqrt($number); $i++) {
if ($number % $i == 0) {
$isPrime = false;
break;
}
}
if ($isPrime) {
echo $number . " ";
}
}
echo "<br>";
}

function fibonacciSeries($numTerms) {
$first = 0;
$second = 1;
echo "Fibonacci Series ($numTerms terms): ";
for ($i = 0; $i < $numTerms; $i++) {
echo $first . " ";
$next = $first + $second;
$first = $second;
$second = $next;
}
echo "<br>";
}

// Call the functions with desired parameters


generatePrimes(50); // Generate prime numbers up to 50
fibonacciSeries(10); // Generate 10 terms of the Fibonacci series
?>
OUTPUT:

PROGRAM :10
Write a PHP program to remove duplicates from a sorted
list
<?php
function removeDuplicates($array) {
$result = array_values(array_unique($array));
return $result;
}

$sortedList = [1, 1, 2, 2, 3, 3, 4, 5, 5];


$uniqueList = removeDuplicates($sortedList);

echo "Original List: ";


print_r($sortedList);
echo "<br> Unique List: ";
print_r($uniqueList);
?>

OUTPUT: Commented [AR1]: BWLIUEWHE


PROGRAM :11
Write a PHP Script to print the following pattern on the
Screen
<?php
$rows = 5;

for ($i = $rows; $i >= 1; $i--) {


for ($j = $rows; $j > $i; $j--) {
echo "&nbsp;";
}
for ($k = 1; $k <= $i; $k++) {
echo "* ";
}
echo "<br>";
}
?>
OUTPUT:

PROGRAM 12:
Write a simple program in PHP for Searching of data by
different criteria
<?php

$data = [
['id' => 1, 'name' => 'alan', 'age' => 30],
['id' => 2, 'name' => 'sebin', 'age' => 35],
['id' => 3, 'name' => 'sebin', 'age' => 50],
['id' => 4, 'name' => 'sanu', 'age' => 45],
['id' => 5, 'name' => 'ghh', 'age' => 50] // Changed id to 5 for Saatvik
];

function searchByCriteria($data, $criteria) {


$results = [];

foreach ($data as $entry) {


$match = true;
foreach ($criteria as $key => $value) {
if (!isset($entry[$key]) || $entry[$key] != $value) {
$match = false;
break;
}
}
if ($match) {
$results[] = $entry;
}
}

return $results;
}
$criteria = ['age' => 50];

$result = searchByCriteria($data, $criteria); O


print_r($result);
?>

OUTPUT:

PROGRAM :13
Write a function in PHP to generate captcha code
<?php

session_start();
function generateCaptchaCode($length = 6) {
$characters =
'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';

for ($i = 0; $i < $length; $i++) {


$randomString .= $characters[rand(0, $charactersLength - 1)];
}

return $randomString;
}

echo "Captcha Code is " . generateCaptchaCode();

?>

OUTPUT:

PROGRAM 14:
<?php
// Database connection
$conn = new mysqli("localhost", "root", "", "myDB"); // Update with your
credentials

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

// Display Image by ID
if (isset($_GET['id'])) {
$id = intval($_GET['id']);
$stmt = $conn->prepare("SELECT image_type, image_data FROM images WHERE id
= ?");
$stmt->bind_param("i", $id);
$stmt->execute();
$stmt->bind_result($imageType, $imageData);
if ($stmt->fetch()) {
header("Content-Type: " . $imageType);
echo $imageData;
}
$stmt->close();
exit;
}

// Handle Image Upload


if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_FILES["image"])) {
// File validation
$imageName = $_FILES["image"]["name"];
$imageTmpName = $_FILES["image"]["tmp_name"];
$imageType = $_FILES["image"]["type"];
$allowedTypes = ['image/jpeg', 'image/png', 'image/gif']; // Allowed image
types
$maxFileSize = 5 * 1024 * 1024; // 5 MB

if (!in_array($imageType, $allowedTypes)) {
die("Invalid file type. Only JPEG, PNG, and GIF are allowed.");
}

if ($_FILES["image"]["size"] > $maxFileSize) {


die("File size exceeds the 5 MB limit.");
}

$imageData = file_get_contents($imageTmpName);

$stmt = $conn->prepare("INSERT INTO images (image_name, image_type,


image_data) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $imageName, $imageType, $imageData);
if ($stmt->execute()) {
echo "Image uploaded successfully.<br>";
} else {
echo "Failed to upload image.<br>";
}
$stmt->close();
}

// Function to Display Uploaded Images


function displayImages($conn) {
$sql = "SELECT id, image_name FROM images";
$result = $conn->query($sql);

while ($row = $result->fetch_assoc()) {


echo "<div>";
echo "<p>" . htmlspecialchars($row["image_name"]) . "</p>";
echo "<img src='?id=" . $row["id"] . "' alt='" .
htmlspecialchars($row["image_name"]) . "' style='max-width: 200px; max-height:
200px;'><br>";
echo "</div>";
}
}
?>

<!DOCTYPE html>
<html>
<head>
<title>Image Upload and Display</title>
</head>
<body>
<h1>Upload and Display Images</h1>
<!-- Image Upload Form -->
<form method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="image" id="image" required>
<input type="submit" value="Upload Image" name="submit">
</form>

<h2>Uploaded Images:</h2>
<?php displayImages($conn); ?>

<?php $conn->close(); ?>


</body>
</html>

OUTPUT:
PROGRAM 15:
<!DOCTYPE html>
<html>
<head>
<title>File Reader and Writer</title>
</head>
<body>

<form action="FileReadWrite.php" method="post">


<label for="textdata">Enter Text: </label><br>
<textarea name="textdata" id="textdata"></textarea>
<input type="submit" value="Write to File"><br><br>
</form>

<form action="FileReadWrite.php" method="post" enctype="multipart/form-data">


<label for="filedata">Upload File to Read File Contents:</label><br>
<input type="file" name="filedata" id="filedata">
<input type="submit" value="Read File Contents"><br><br>
</form>

</body>
</html>

<?php

if ($_SERVER["REQUEST_METHOD"] == "POST") {

// Writing text data to a file


if (!empty($_POST['textdata'])) {
file_put_contents("output.txt", $_POST['textdata']);
echo "Data written to file.<br>";
}

// Reading content from an uploaded file


if (!empty($_FILES['filedata']['tmp_name'])) {
$fileContent = file_get_contents($_FILES['filedata']['tmp_name']);
echo "File content: " . htmlspecialchars($fileContent) . "<br>";
}
}

?>

OUTPUT:

PROGRAM 16:

<!DOCTYPE html>
<html>
<head>
<title>Student Database Operations</title>
</head>
<body>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "studentdb";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

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

// Check for form action


if ($_SERVER["REQUEST_METHOD"] == "POST") {
$action = $_POST['action'];
$regno = $_POST['regno'];
$name = $_POST['name'];
$age = $_POST['age'];
$course = $_POST['course'];

// Add Action
if ($action == "Add") {
$add_sql = "INSERT INTO students (regno, name, age, course) VALUES
('$regno', '$name', '$age', '$course')";
if ($conn->query($add_sql) === TRUE) {
echo "New record added successfully.<br><br>";
} else {
echo "Error adding record: " . $conn->error . "<br>";
}
}

// Update Action
elseif ($action == "Update") {
$update_sql = "UPDATE students SET name = '$name', age = '$age',
course = '$course' WHERE regno = '$regno'";
if ($conn->query($update_sql) === TRUE) {
echo "Record updated successfully.<br><br>";
} else {
echo "Error updating record: " . $conn->error . "<br>";
}
}

// Delete Action
elseif ($action == "Delete") {
$delete_sql = "DELETE FROM students WHERE regno = '$regno'";
if ($conn->query($delete_sql) === TRUE) {
echo "Record deleted successfully.<br><br>";
} else {
echo "Error deleting record: " . $conn->error . "<br>";
}
}
}

// Function to display students from the database


function displayStudents($conn) {
$sql = "SELECT regno, name, age, course FROM students";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<h2>Student List:</h2>";
echo "<table
border='1'><tr><th>Regno</th><th>Name</th><th>Age</th><th>Course</th></tr>";
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["regno"]. "</td><td>" . $row["name"].
"</td><td>" . $row["age"]. "</td><td>" . $row["course"]. "</td></tr>";
}
echo "</table>";
} else {
echo "No students found.<br>";
}
}

// Display students after any action


displayStudents($conn);

// Close connection
$conn->close();
?>

<h1> Manage Student</h1>


<form method="post">
Regno: <input type="text" name="regno" required><br><br>
Name: <input type="text" name="name"><br><br>
Age: <input type="number" name="age"><br><br>
Course: <input type="text" name="course" required><br><br>

<input type="submit" name="action" value="Add">


<input type="submit" name="action" value="Update">
<input type="submit" name="action" value="Delete">
</form>

</body>
</html>

OUTPUT:
PROGRAM 17:
<!DOCTYPE html>
<html>
<head>
<title>Input Validation</title>
</head>
<body>
<form method="post">
Name: <input type="text" name="name"><br><br>
Email: <input type="text" name="email"><br><br>
<input type="submit" name="submit" value="Submit">
</form>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST['name'];
$email = $_POST['email'];

// Validate Name
if (empty($name)) {
echo "Name is required.<br><br>";
} else {
echo "Name: " . $name . "<br><br>";
}

// Validate Email
if (empty($email)) {
echo "Email is required.<br><br>";
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Invalid email format.<br><br>";
} else {
echo "Email: " . $email . "<br><br>";
}
}
?>
</body>
</html>

OUTPUT:

PROGRAM 18:
<!DOCTYPE html>
<html>
<head>
<title>Cookie Handler</title>
</head>
<body>
<?php

if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Set the cookie with a name and value from the form
setcookie("username", $_POST['username'], time() + (10 * 30), "/");
echo "<p>Cookie set. Reload the page to see the cookie value.</p>";
}

// Check if the cookie named "username" exists


if (isset($_COOKIE["username"])) {
echo "<p>Welcome back, " . htmlspecialchars($_COOKIE["username"]) .
"!</p>";
} else {
echo "<p>Welcome, guest!</p>";
}
?>

<!-- HTML form to set a cookie -->


<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);
?>">
<label for="username">Enter your name:</label><br>
<input type="text" id="username" name="username"><br>
<input type="submit" value="Set Cookie">
</form>
</body>
</html>

OUTPUT:

PROGRAM 19:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Skyward Institute of Computer Applications</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
line-height: 1.6;
}
header {
background-color: #f8f9fa;
padding: 20px;
text-align: center;
border-bottom: 1px solid #ddd;
}
nav {
margin: 20px 0;
text-align: center;
}
nav a {
margin: 0 15px;
text-decoration: none;
color: #007bff;
font-weight: bold;
}
nav a:hover {
text-decoration: underline;
}
main {
padding: 20px;
text-align: center;
}
main h2 {
color: #333;
}
</style>
</head>
<body>
<header>
<img src="logo.jpg" alt="Skyward Institute of Computer Applications
Logo" width="100">
<h1>Skyward Institute of Computer Applications</h1>
<p>157, 3RD MAIN, CHAMRAJPET BANGALORE 560018</p>
</header>
<nav>
<a href="index.php">Home</a>
<a href="about.php">About Us</a>
<a href="courses.php">Courses</a>
<a href="contact.php">Contact Us</a>
</nav>
<main>
<h2>Welcome to Skyward Institute of Computer Applications</h2>
<p>We provide the best training in computer application courses.</p>
</main>
</body>
</html>
OUTPUT:

PROGRAM 20:
<?php

function divide($numerator, $denominator) {


if ($denominator == 0) {
throw new Exception("Cannot divide by zero.");
}
return $numerator / $denominator;
}

function checkDateFormat($date, $format = 'Y-m-d') {


$dateTime = DateTime::createFromFormat($format, $date);
if (!$dateTime || $dateTime->format($format) != $date) {
throw new Exception("Invalid date format.");
}
echo "The date " . $date . " is valid. <br>";
return true;
}

try {
echo divide(10, 2) . "<br>"; // Should work
echo divide(10, 0) . "<br>"; // Should throw exception
} catch (Exception $e) {
echo "Division error: ". $e->getMessage() . "<br>";
}
try {
CheckDateFormat("2023-03-10"); // Should work and confirm validity
CheckDateFormat("10/03/2023"); // Should throw exception
} catch (Exception $e) {
echo "Date error: " . $e->getMessage() . "<br>";
}
?>

OUTPUT:

You might also like