1. Write a PHP script to print “hello world”.
<?php
echo "Hello, World!";
?>
-----------------------------------------------------------------------------------
----------------------------------
2. Write a PHPscript to find odd or even number from given number.
<?php
// PHP script to check if a number is odd or even
// Define the num
ber
$number = 10; // You can change this value
// Check if the number is even or odd
if ($number % 2 == 0)
{
echo "$number is even.";
}
else
{
echo "$number is odd.";
}
?>
-----------------------------------------------------------------------------------
----------------------------------
3. Write a PHPscript to find maximum of three numbers.
<?php
$num1 = 12;
$num2 = 45;
$num3 = 29;
// Find the maximum number
if ($num1 >= $num2 && $num1 >= $num3) {
echo "The maximum number is $num1.";
} elseif ($num2 >= $num1 && $num2 >= $num3) {
echo "The maximum number is $num2.";
} else {
echo "The maximum number is $num3.";
}
?>
-----------------------------------------------------------------------------------
----------------------------------
4. Write a PHPscript to swap two numbers.
<?php
// PHP script to swap two numbers
// Define two numbers
$num1 = 5;
$num2 = 10;
// Display the original values
echo "Before swapping:";
echo"\n";
echo "num1 = $num1, num2 = $num2";
// Swap the numbers using a temporary variable
$temp = $num1;
$num1 = $num2;
$num2 = $temp;
// Display the swapped values
echo "After swapping:\n";
echo "num1 = $num1, num2 = $num2\n";
?>
-----------------------------------------------------------------------------------
----------------------------------
5. Write a PHP script to find the factorial of a number.
<?php
// PHP script to find the factorial of a number
// Define the number
$number = 5; // You can change this value to any positive integer
// Initialize factorial as 1
$factorial = 1;
// Calculate the factorial using a loop
for ($i = 1; $i <= $number; $i++) {
$factorial *= $i; // Multiply $factorial by $i
}
// Display the result
echo "The factorial of $number is $factorial.";
?>
-----------------------------------------------------------------------------------
----------------------------------
6. Write a PHPscript to check whether given number is palindrome or not.
<?php
// Function to check if a number is palindrome
function isPalindrome($number) {
// Convert the number to a string
$numStr = strval($number);
// Reverse the string
$reversedStr = strrev($numStr);
// Compare the original and reversed strings
if ($numStr === $reversedStr)
{
return true; // It's a palindrome
}
else
{
return false; // It's not a palindrome
}
}
// Test the function
$number = 121; // Example input
if (isPalindrome($number))
{
echo "$number is a palindrome.";
}
else
{
echo "$number is not a palindrome.";
}
?>
-----------------------------------------------------------------------------------
--------------
7. Write a PHP script to reverse a given number and calculate its sum
<?php
// Function to reverse a number
function reverseNumber($number) {
$reversed = strrev(strval($number)); // Reverse the number as a string
return intval($reversed); // Convert the reversed string back to an integer
}
// Function to calculate the sum of the original number and its reversed version
function calculateSum($number) {
$reversed = reverseNumber($number);
return $number + $reversed; // Sum of original and reversed number
}
// Test the functions
$number = 1234; // Example input
$reversed = reverseNumber($number);
$sum = calculateSum($number);
echo "Original Number: $number\n";
echo "Reversed Number: $reversed\n";
echo "Sum: $sum\n";
?>
-----------------------------------------------------------------------------------
-----------------
8. Write a PHP script to to generate a Fibonacci series using Recursive function
<?php
// Recursive function to calculate Fibonacci number at a given position
function fibonacci($n) {
if ($n <= 1) {
return $n; // Base cases: return 0 for n=0 and 1 for n=1
}
return fibonacci($n - 1) + fibonacci($n - 2); // Recursive calculation
}
// Function to generate Fibonacci series
function generateFibonacciSeries($count) {
$series = [];
for ($i = 0; $i < $count; $i++) {
$series[] = fibonacci($i); // Add Fibonacci number to the series
}
return $series;
}
// Example usage
$count = 10; // Number of terms in the series
$fibonacciSeries = generateFibonacciSeries($count);
echo "Fibonacci Series (First $count Terms):\n";
echo implode(", ", $fibonacciSeries); // Print the series as comma-separated values
?>
-----------------------------------------------------------------------------------
-----------------
9. Write a PHP script to implement atleast seven string functions.
<?php
// Original string
$originalString = "Hello, World!";
// 1. strlen() - Gets the length of a string
echo "Length of the string: " . strlen($originalString) . "\n";
// 2. strtolower() - Converts a string to lowercase
echo "Lowercase: " . strtolower($originalString) . "\n";
// 3. strtoupper() - Converts a string to uppercase
echo "Uppercase: " . strtoupper($originalString) . "\n";
// 4. strrev() - Reverses a string
echo "Reversed String: " . strrev($originalString) . "\n";
// 5. substr() - Extracts a substring from a string
echo "Substring (0-5): " . substr($originalString, 0, 5) . "\n";
// 6. str_replace() - Replaces part of a string
echo "Replace 'World' with 'PHP': " . str_replace("World", "PHP",
$originalString) . "\n";
// 7. strpos() - Finds the position of a substring in a string
$search = "World";
$position = strpos($originalString, $search);
echo "Position of '$search' in the string: " . ($position !== false ? $position :
"Not Found") . "\n";
?>
-----------------------------------------------------------------------------------
---------------------------------------
10. Write a PHP program to insert new item in array on any position in PHP.
<?php
// Function to insert an item into an array at a specific position
function insertAtPosition($array, $item, $position) {
// Use array_splice to insert the item
array_splice($array, $position, 0, $item);
return $array;
}
// Example usage
$originalArray = [10, 20, 30, 40, 50]; // Original array
$newItem = 25; // Item to be inserted
$position = 2; // Desired position (index starts from 0)
echo "Original Array: " . implode(", ", $originalArray) . "\n";
$updatedArray = insertAtPosition($originalArray, $newItem, $position);
echo "Updated Array: " . implode(", ", $updatedArray) . "\n";
?>
-----------------------------------------------------------------------------------
---------------------------------------
11. Write a PHP script to implement constructor and destructor
<?php
// Define a class with a constructor and destructor
class SampleClass {
private $message;
// Constructor method: Automatically called when an object is created
public function __construct($message) {
$this->message = $message;
echo "Constructor: Object created with message '$message'\n";
}
// Method to display the message
public function displayMessage() {
echo "Message: " . $this->message . "\n";
}
// Destructor method: Automatically called when an object is destroyed
public function __destruct() {
echo "Destructor: Object is being destroyed. Goodbye!\n";
}
}
// Example usage
$obj = new SampleClass("Hello, PHP!"); // Create an object of SampleClass
$obj->displayMessage(); // Call a method of the object
// The destructor will be automatically called at the end of the script
?>
-----------------------------------------------------------------------------------
---------------------------------------
12. Write a PHP script to implement form handling using get method
<!DOCTYPE html>
<html>
<head>
<title>Form Handling with GET Method</title>
</head>
<body>
<!-- Form with GET method -->
<h2>Enter Your Details</h2>
<form method="GET" action="form_get.php">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<br><br>
<button type="submit">Submit</button>
</form>
<?php
// Check if form data is submitted
if (!empty($_GET)) {
// Retrieve data from the GET request
$name = htmlspecialchars($_GET['name']); // Use htmlspecialchars to prevent
XSS
$email = htmlspecialchars($_GET['email']);
// Display the submitted data
echo "<h3>Submitted Details:</h3>";
echo "Name: $name<br>";
echo "Email: $email<br>";
}
?>
</body>
</html>
-----------------------------------------------------------------------------------
---------------------------------------
13. Write a PHP script to implement form handling using post method.
<!DOCTYPE html>
<html>
<head>
<title>Form Handling with POST Method</title>
</head>
<body>
<!-- Form with POST method -->
<h2>Enter Your Details</h2>
<form method="POST" action="form_post.php">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<br><br>
<button type="submit">Submit</button>
</form>
<?php
// Check if form data is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Retrieve data from the POST request
$name = htmlspecialchars($_POST['name']); // Use htmlspecialchars to
prevent XSS
$email = htmlspecialchars($_POST['email']);
// Display the submitted data
echo "<h3>Submitted Details:</h3>";
echo "Name: $name<br>";
echo "Email: $email<br>";
}
?>
</body>
</html>
-----------------------------------------------------------------------------------
---------------------------------------
14. Write a PHP script that receive form input by the method post to check the
number is prime or not
<!DOCTYPE html>
<html>
<head>
<title>Check Prime Number</title>
</head>
<body>
<h2>Prime Number Checker</h2>
<form method="POST" action="check_prime.php">
<label for="number">Enter a Number:</label>
<input type="number" id="number" name="number" required>
<br><br>
<button type="submit">Check</button>
</form>
<?php
// Check if the form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Retrieve the number from the POST request
$number = intval($_POST['number']);
// Function to check if a number is prime
function isPrime($num) {
if ($num <= 1) {
return false; // Numbers less than or equal to 1 are not prime
}
for ($i = 2; $i <= sqrt($num); $i++) {
if ($num % $i == 0) {
return false; // If divisible, it's not prime
}
}
return true; // Otherwise, it's prime
}
// Determine if the number is prime
if (isPrime($number)) {
echo "<h3>$number is a prime number.</h3>";
} else {
echo "<h3>$number is not a prime number.</h3>";
}
}
?>
</body>
</html>
-----------------------------------------------------------------------------------
---------------------------------------
15. Write a PHP script that receive string as a form input
<!DOCTYPE html>
<html>
<head>
<title>String Input Form</title>
</head>
<body>
<h2>String Processor</h2>
<form method="POST" action="string_form.php">
<label for="inputString">Enter a String:</label>
<input type="text" id="inputString" name="inputString" required>
<br><br>
<button type="submit">Submit</button>
</form>
<?php
// Check if the form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Retrieve the string from the POST request
$inputString = htmlspecialchars($_POST['inputString']); // Sanitize input
// Process the string
$reversedString = strrev($inputString); // Reverse the string
$stringLength = strlen($inputString); // Calculate the length of the
string
// Display the results
echo "<h3>Results:</h3>";
echo "Original String: $inputString<br>";
echo "Reversed String: $reversedString<br>";
echo "Length of String: $stringLength characters<br>";
}
?>
</body>
</html>
-----------------------------------------------------------------------------------
---------------------------------------
16. Write a PHP script to compute addition of two matrices as a form input.
<!DOCTYPE html>
<html>
<head>
<title>Matrix Addition</title>
</head>
<body>
<h2>Matrix Addition</h2>
<form method="POST" action="matrix_addition.php">
<h3>Matrix A:</h3>
<label>Row 1: </label>
<input type="number" name="a11" required>
<input type="number" name="a12" required>
<br>
<label>Row 2: </label>
<input type="number" name="a21" required>
<input type="number" name="a22" required>
<br>
<h3>Matrix B:</h3>
<label>Row 1: </label>
<input type="number" name="b11" required>
<input type="number" name="b12" required>
<br>
<label>Row 2: </label>
<input type="number" name="b21" required>
<input type="number" name="b22" required>
<br><br>
<button type="submit">Add Matrices</button>
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Retrieve values for Matrix A
$a11 = intval($_POST['a11']);
$a12 = intval($_POST['a12']);
$a21 = intval($_POST['a21']);
$a22 = intval($_POST['a22']);
// Retrieve values for Matrix B
$b11 = intval($_POST['b11']);
$b12 = intval($_POST['b12']);
$b21 = intval($_POST['b21']);
$b22 = intval($_POST['b22']);
// Compute the addition of the two matrices
$result11 = $a11 + $b11;
$result12 = $a12 + $b12;
$result21 = $a21 + $b21;
$result22 = $a22 + $b22;
// Display the result
echo "<h3>Resulting Matrix:</h3>";
echo "<table border='1' cellpadding='5'>";
echo "<tr><td>$result11</td><td>$result12</td></tr>";
echo "<tr><td>$result21</td><td>$result22</td></tr>";
echo "</table>";
}
?>
</body>
</html>
-----------------------------------------------------------------------------------
-----------------------------------------------
17. Write a PHP script to show the functionality of date and time function.
<?php
// Display the current date and time
echo "Current Date and Time: " . date("Y-m-d H:i:s") . "\n";
// Display just the current date
echo "Current Date: " . date("Y-m-d") . "\n";
// Display just the current time
echo "Current Time: " . date("H:i:s") . "\n";
// Display the day of the week
echo "Day of the Week: " . date("l") . "\n";
// Display the time in a different format
echo "Formatted Time: " . date("h:i A") . "\n";
// Add 7 days to the current date
$newDate = date("Y-m-d", strtotime("+7 days"));
echo "Date After 7 Days: " . $newDate . "\n";
// Subtract 1 month from the current date
$prevMonth = date("Y-m-d", strtotime("-1 month"));
echo "Date 1 Month Ago: " . $prevMonth . "\n";
// Display the current timestamp
echo "Current Timestamp: " . time() . "\n";
// Convert a timestamp into a readable date
$timestamp = 1672531200; // Example timestamp
echo "Readable Date from Timestamp: " . date("Y-m-d H:i:s", $timestamp) . "\n";
// Calculate the difference between two dates
$date1 = "2025-03-23";
$date2 = "2025-04-23";
$diff = strtotime($date2) - strtotime($date1);
$daysDiff = $diff / (60 * 60 * 24); // Convert seconds to days
echo "Difference Between $date1 and $date2: $daysDiff days\n";
?>
-----------------------------------------------------------------------------------
-----------------------------------------------
18. Write a PHP program to upload a file
<!DOCTYPE html>
<html>
<head>
<title>File Upload</title>
</head>
<body>
<h2>Upload a File</h2>
<form method="POST" action="file_upload.php" enctype="multipart/form-data">
<label for="file">Choose a file:</label>
<input type="file" name="file" id="file" required>
<br><br>
<button type="submit">Upload</button>
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Check if the file was uploaded without errors
if (isset($_FILES["file"]) && $_FILES["file"]["error"] == 0) {
$fileName = $_FILES["file"]["name"];
$fileType = $_FILES["file"]["type"];
$fileSize = $_FILES["file"]["size"];
$tempPath = $_FILES["file"]["tmp_name"];
// Define the upload directory
$uploadDir = "uploads/";
// Create the directory if it doesn't exist
if (!is_dir($uploadDir)) {
mkdir($uploadDir, 0777, true);
}
// Set the path for the uploaded file
$uploadPath = $uploadDir . basename($fileName);
// Move the file to the desired directory
if (move_uploaded_file($tempPath, $uploadPath)) {
echo "<h3>File uploaded successfully!</h3>";
echo "File Name: $fileName<br>";
echo "File Type: $fileType<br>";
echo "File Size: " . ($fileSize / 1024) . " KB<br>";
echo "File Path: $uploadPath<br>";
} else {
echo "<h3>Error: Unable to upload the file.</h3>";
}
} else {
echo "<h3>Error: No file was uploaded or an error occurred.</h3>";
}
}
?>
</body>
</html>
-----------------------------------------------------------------------------------
-----------------------------------------------
19. Write a PHP script to implement database creation
<?php
// Database connection credentials
$host = "localhost"; // Hostname (use "127.0.0.1" or "localhost")
$username = "root"; // MySQL username
$password = ""; // MySQL password
$dbName = "test_db"; // Name of the database to create
// Create a connection to MySQL
$conn = new mysqli($host, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully to MySQL server.<br>";
// Create a new database
$sql = "CREATE DATABASE $dbName";
if ($conn->query($sql) === TRUE) {
echo "Database '$dbName' created successfully.";
} else {
echo "Error creating database: " . $conn->error;
}
// Close the connection
$conn->close();
?>
-----------------------------------------------------------------------------------
-----------------------------------------------
20. Write a PHP script to create table
<?php
// Database connection credentials
$host = "localhost"; // Hostname (e.g., "127.0.0.1" or "localhost")
$username = "root"; // MySQL username
$password = ""; // MySQL password
$dbName = "test_db"; // Existing database name
// Create a connection to MySQL
$conn = new mysqli($host, $username, $password, $dbName);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully to the database '$dbName'.<br>";
// SQL query to create a table
$tableName = "users";
$sql = "CREATE TABLE $tableName (
id INT(11) AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
email VARCHAR(100) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)";
// Execute the query
if ($conn->query($sql) === TRUE) {
echo "Table '$tableName' created successfully.";
} else {
echo "Error creating table: " . $conn->error;
}
// Close the connection
$conn->close();
?>
-----------------------------------------------------------------------------------
-----------------------------------------------
21. Develop a PHP program to design a college admission form using MYSQL database.
CREATE DATABASE college_admission;
USE college_admission;
CREATE TABLE students (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(100) NOT NULL UNIQUE,
phone VARCHAR(15) NOT NULL,
dob DATE NOT NULL,
course VARCHAR(50) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
<!-- Save this as 'admission_form.php' -->
<!DOCTYPE html>
<html>
<head>
<title>College Admission Form</title>
</head>
<body>
<h2>College Admission Form</h2>
<form method="POST" action="admission_form.php">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<br><br>
<label for="phone">Phone:</label>
<input type="text" id="phone" name="phone" required>
<br><br>
<label for="dob">Date of Birth:</label>
<input type="date" id="dob" name="dob" required>
<br><br>
<label for="course">Course:</label>
<input type="text" id="course" name="course" required>
<br><br>
<button type="submit">Submit</button>
</form>
<?php
// Check if the form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Database connection details
$host = "localhost";
$username = "root";
$password = "";
$dbName = "college_admission";
// Create a connection
$conn = new mysqli($host, $username, $password, $dbName);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Retrieve form data
$name = $conn->real_escape_string($_POST['name']);
$email = $conn->real_escape_string($_POST['email']);
$phone = $conn->real_escape_string($_POST['phone']);
$dob = $conn->real_escape_string($_POST['dob']);
$course = $conn->real_escape_string($_POST['course']);
// Insert data into the database
$sql = "INSERT INTO students (name, email, phone, dob, course)
VALUES ('$name', '$email', '$phone', '$dob', '$course')";
if ($conn->query($sql) === TRUE) {
echo "<h3>Admission successfully submitted!</h3>";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
// Close the connection
$conn->close();
}
?>
</body>
</html>