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

PHP Lab

Uploaded by

mahimahee777
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)
34 views

PHP Lab

Uploaded by

mahimahee777
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/ 18

1. Write a PHP Script to print “hello world”.

<!DOCTYPE html>
<html>
<head>
<title>program to print hello world</title>
</head>
<body>
<h1>My first PHP page</h1>
<?php
echo "Hello World!";
?>
</body>
</html>

2. Write a PHP Script to find odd or even number from given number.

<!DOCTYPE html>
<html>
<head>
<title>program check given number is even or odd</title>
</head>
<body>
<?php
$number=3;
if($number%2==0)
{
echo "$number is Even Number";
}
else
{
echo "$number is Odd Number";
}
?>
</body>
</html>
3. Write a PHP Script to find maximum of three numbers.

<!DOCTYPE html>
<html>
<head>
<title>program check maximum of two numbers</title>
</head>
<body>
<?php
$number1 = 3;
$number2 = 7;
$number3 = 11;
if ($number1 > $number2 and $number1 > $number3) {
echo "The largest number is: $number1\n";
}
elseif ($number2 > $number3 )
{
echo "The largest number is: $number2\n";
}
else
{
echo "The largest number is: $number3\n";
}
?>
</body>
</html>

4. Write a PHP Script to swap two numbers.

<!DOCTYPE html>
<html>
<head>
<title>program swap two numbers</title>
</head>
<body>
<?php
$a = 45;
$b = 78;
echo "before swapping:<br>";
echo "a =".$a." b=".$b;
$third = $a;
$a = $b;
$b = $third;
echo "<br><br>After swapping:<br>";
echo "a =".$a." b=".$b;
?>
</body>
</html>
5. Write a PHP Script to find the factorial of a number.

<html>
<head>
<title>Factorial Program using loop in PHP</title>
</head>
<body>
<?php
$num = 4;
$factorial = 1;
for ($x=$num; $x>=1; $x--)
{
$factorial = $factorial * $x;
}
echo "Factorial of $num is $factorial";
?>
</body>
</html>

6. Write a PHP Script to check whether given number is palindrome or not.

<!DOCTYPE html>
<html>
<body>
<?php
$original = 1221;
$temp = $original;
$reverse = 0;
while ($temp>1)
{
$rem = $temp % 10;
$reverse = ($reverse * 10) + $rem;
$temp = $temp/10;
}
if ($reverse == $original)
{
echo "$original is a Palindrome number";
}
else
{
echo "$original is not a Palindrome number";
}
?>
</body>
</html>
7. Write a PHP Script to reverse a given number and calculate its sum

<!DOCTYPE html>
<html>
<head>
<title>PHP Program To find the Reverse and sum of a given number</title>
</head>
<body>
<?php
$original = 123;
$temp = $original;
$reverse = 0;
$sum=0;
while($temp>1)
{
$rem = $temp%10;
$reverse =($reverse*10)+$rem;
$sum=$sum+$rem;
$temp = $temp/10;
}
echo "Reverse of number $original is: $reverse";
echo "<br>Sum of digits of given number $original is: $sum";
return 0;
?>
</body>
</html>

8. Write a PHP Script to generate a Fibonacci series using Recursive function

<html>
<head>
<title>PHP Program To find the Fibonacci series of a given number</title>
</head>
<body>
<?php
function fibonacci($n) {
// base case
if ($n <= 1) {
return $n;
} else {
return fibonacci($n - 1) + fibonacci($n - 2);
}
}
$num_terms = 10;
echo "Fibonacci Series: ";
for ($i = 0; $i < $num_terms; $i++) {
echo fibonacci($i) . ", ";
}
?>
</body>
</html>
9. Write a PHP Script to implement at least seven string functions.

<!DOCTYPE html>
<head>
<title>PHP Program to implement string functions</title>
</head>
<html>
<body>
<?php
$str="Banglore";
echo"<br>original string is:".$str;
//reverese
$nstr=strrev($str);
echo"<br>reverse of the string is: ".$nstr;

//string length
$nstr=strlen($str);
echo"<br>length of the string is: ".$nstr;

//string position
$nstr=strpos($str,"n");
echo"<br>position of the substring is: ".$nstr;

//lower case
$nstr=strtolower($str);
echo"<br>lowercase of the string is: ".$nstr;

//upper case
$nstr=strtoupper($str);
echo"<br>uppercase of the string is: ".$nstr;

//substring
$nstr=substr($str,3);
echo"<br>substring of the string is: ".$nstr;

//replace
$nstr=str_replace("B","M",$str);
echo"<br>string after replacement: ".$nstr;
?>
</body>
</html>
10. Write a PHP program to insert new item in array on any position in PHP.

<!DOCTYPE html>
<html>
<body>
<?php
$original_array = array( '1', '2', '3', '4', '5' );
echo 'Original array : ';
foreach ($original_array as $x)
{
echo "$x ";
}
echo "\n";
$inserted_value = '11';
$position = 2;
array_splice( $original_array, $position, 0, $inserted_value );
echo "<br>After inserting 11 in the array is : ";
foreach ($original_array as $x)
{
echo "$x ";
}
?>
</body>
</html>

11. Write a PHP Script to implement Constructor and Destructor

<!DOCTYPE html>
<html>
<body>
<?php
class ExampleClass {
private $name;
public function __construct($name) {
$this->name = $name;
echo "Constructor called. Hello, {$this->name}!<br>";
}
public function __destruct() {
echo "Destructor called. Goodbye, {$this->name}!<br>";
}
public function greet() {
echo "Hello, {$this->name}!<br>";
}
}
$instance = new ExampleClass("John");
$instance->greet();
?>
</body>
</html>
12. Write a PHP script to implement form handling using get method

<!DOCTYPE html>
<html>
<head>
<title>GET Form Handling</title>
</head>
<body>
<h2>GET Form Example</h2>
<form action = "<?php $PHP_SELF ?>" method = "GET">
Name: <input type = "text" name = "name" /><br><br>
<input type = "submit" /><br>
</form>
<?php
if(isset($_GET["name"])) {
echo "Hi ". $_GET['name']. "<br><br>";
exit();
}
?>
</body>
</html>

13. Write a PHP script to implement form handling using post method

<!DOCTYPE html>
<html>
<head>
<title>POST Form Handling</title>
</head>
<body>

<h2>POST Form Example</h2>

<form action = "<?php $PHP_SELF ?>" method = "POST">


Name: <input type = "text" name = "name" /><br><br>
<input type = "submit" /><br>
</form>
<?php
if(isset($_POST["name"])) {
echo "Hi ". $_POST['name']. "<br><br>";
exit();
}
?>
</body>
</html>
14. Write a PHP script that receive form input by the method post to check the number is
prime or not

<html>
<head>
<title>PHP Program To Check a given number is Prime number or Not</title>
</head>
<body>
<form method="post">
<input type="text" name="num" placeholder="Enter positive interger"/> </td>
<input type="submit" name="submit" value="Submit"/> </td>
</form>
<?php
if(isset($_POST['submit']))
{
$n = $_POST['num'];
$flag = 0;
for($i = 2; $i <= $n/2; $i++)
{
if($n%$i == 0)
{
$flag = 1;
break;
}
}
if($flag == 0)
echo "$n is a prime number";
else
echo "$n is not a prime number";
return 0;
}
?>
</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>Enter a String</h2>
<form action = "<?php $PHP_SELF ?>" method = "POST">
<input type="text" name="name">
<input type="submit" name="submit" value="Submit">
</form>
<?php
if (isset($_POST["submit"])) {
if (!empty($_POST['name'])) {
$name = $_POST ['name'];
echo "<h2>You entered:</h2>";
echo "<p>$name</p>";
}
else
{
echo "<h2>Please enter a string</h2>";
}
}
?>
</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">
Enter the dimensions of the matrices:<br><br>
Rows: <input type="number" name="rows" min="1" required><br><br>
Columns: <input type="number" name="columns" min="1" required><br><br>
<input type="submit" value="Submit">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$rows = $_POST["rows"];
$columns = $_POST["columns"];
echo '<h3>Enter values for Matrix 1:</h3>';
echo '<form method="post">';
for ($i = 0; $i < $rows; $i++) {
for ($j = 0; $j < $columns; $j++) {
echo 'Value at position (' . ($i + 0) . ', ' . ($j + 0) . '): <input type="number" name="matrix1[' .
$i . '][' . $j . ']" required><br>';
}
}
echo '<input type="hidden" name="rows" value="' . $rows . '">';
echo '<input type="hidden" name="columns" value="' . $columns . '">';
echo '<input type="submit" value="Next">';
echo '</form>';
if(isset($_POST["matrix1"])) {
$matrix1 = $_POST["matrix1"];

echo '<h3>Enter values for Matrix 2:</h3>';


echo '<form method="post">';
for ($i = 0; $i < $rows; $i++) {
for ($j = 0; $j < $columns; $j++) {
echo 'Value at position (' . ($i + 0) . ', ' . ($j + 0) . '): <input type="number"
name="matrix2[' . $i . '][' . $j . ']" required><br>';
}
}
echo '<input type="hidden" name="rows" value="' . $rows . '">';
echo '<input type="hidden" name="columns" value="' . $columns . '">';
echo '<input type="hidden" name="matrix1" value="' . htmlentities(serialize($matrix1)) . '">';
echo '<input type="submit" value="Calculate">';
echo '</form>';
}
if(isset($_POST["matrix2"])) {
$matrix1 = unserialize(html_entity_decode($_POST["matrix1"]));
$matrix2 = $_POST["matrix2"];
echo '<h3>Matrix 1:</h3>';
foreach ($matrix1 as $row) {
foreach ($row as $value) {
echo $value . " ";
}
echo "<br>";
}
echo '<h3>Matrix 2:</h3>';
foreach ($matrix2 as $row) {
foreach ($row as $value) {
echo $value . " ";
}
echo "<br>";
}
echo '<h3>Result of Matrix Addition:</h3>';
for ($i = 0; $i < $rows; $i++) {
for ($j = 0; $j < $columns; $j++) {
echo ($matrix1[$i][$j] + $matrix2[$i][$j]) . " ";
}
echo "<br>";
}
}
}
?>
</body>
</html>
17. Write a PHP script to show the functionality of date and time function.

<!DOCTYPE html>
<html>
<body>
<?php
// Set the default timezone
date_default_timezone_set('Asia/Kolkata');
// Get the current date and time
$currentDateTime = date('Y-m-d H:i:s');
echo "Current Date and Time: $currentDateTime<br>";
// Get the current date
$currentDate = date('Y-m-d');
echo "Current Date: $currentDate<br>";
// Get the current time
$currentTime = date('H:i:s');
echo "Current Time: $currentTime<br>";
// Get the day of the week
$dayOfWeek = date('l');
echo "Day of the Week: $dayOfWeek<br>";
// Get the current year
$currentYear = date('Y');
echo "Current Year: $currentYear<br>";
// Get the current month
$currentMonth = date('F');
echo "Current Month: $currentMonth<br>";
// Get the number of days in the current month
$daysInMonth = date('t');
echo "Number of Days in the Current Month: $daysInMonth<br>";
// Get the current timestamp
$timestamp = time();
echo "Current Timestamp: $timestamp<br>";
// Format a custom date and time
$customDateTime = date('l, F jS Y \a\t h:i:s A');
echo "Custom Formatted Date and Time: $customDateTime<br>";
// Using strtotime() function to manipulate dates
$futureDate = strtotime('+1 week');
echo "Future Date (1 week later): " . date('Y-m-d', $futureDate) . "<br>";
$futureTime = strtotime('+1 day');
echo "Future Time (1 day later): " . date('H:i:s', $futureTime) . "<br>";

// Calculate the difference between two dates


$startDate = strtotime('2024-01-01');
$endDate = strtotime('2024-04-07');
$daysDifference = ($endDate - $startDate) / (60 * 60 * 24);
echo "Days difference between two dates: $daysDifference days<br>";
?>
</html>
</body>
18. Write a PHP program to upload a file

<!DOCTYPE html>
<html>
<head>
<title>File Upload Script</title>
</head> <body>
<form enctype="multipart/form-data" action="<?php echo
htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="2048000">
<input type="file" name="fupload"><br>
<input type="submit" value="Send file!">
</form>
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$upload_dir = 'uploads/'; // Ensure this directory exists and is writable
$allowed_types = ['image/gif', 'image/jpeg', 'image/png', 'application/pdf']; // Allowed file types
$max_size = 2048000; // 2 MB
if (isset($_FILES['fupload']) && $_FILES['fupload']['error'] == 0) {
$file_tmp = $_FILES['fupload']['tmp_name'];
$file_name = basename($_FILES['fupload']['name']);
$file_size = $_FILES['fupload']['size'];
$file_type = $_FILES['fupload']['type'];

echo "Path: $file_tmp<br>\n";


echo "Name: $file_name<br>\n";
echo "Size: $file_size bytes<br>\n";
echo "Type: $file_type<p>\n\n";

if ($file_size > $max_size) {


die("File size exceeds the maximum limit of $max_size bytes.");
}
if (in_array($file_type, $allowed_types)) {
if (move_uploaded_file($file_tmp, $upload_dir . $file_name)) {
echo "File uploaded successfully.<br>\n";
if (strpos($file_type, 'image') !== false) {
echo "<img src=\"$upload_dir$file_name\" alt=\"$file_name\" style=\"max-
width:500px;\"><p>\n\n";
} else {
echo "<a href=\"$upload_dir$file_name\">Download $file_name</a><p>\n\n";
}
} else {
die("Couldn't move the file.");
}
} else {
die("Invalid file type. Only GIF, JPEG, PNG, and PDF files are allowed.");
}
} else {
die("File upload error: " . $_FILES['fupload']['error']);
} }
?> </body> </html>
19. Write a PHP script to implement database creation

<?php
// MySQL server configuration
$servername = "localhost"; // If MySQL is on the same server as PHP
$username = "root"; // Your MySQL username
$password = ""; // Your MySQL password

// Create connection
$conn = mysqli_connect($servername, $username, $password);

// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

echo "Connected successfully";

// Create a new database


$sql = "CREATE DATABASE mydatabase";

if (mysqli_query($conn, $sql)) {
echo "Database created successfully";
} else {
echo "Error creating database: " . mysqli_error($conn);
}

// Close connection
mysqli_close($conn);
?>
20. Write a PHP script to create table

<?php
// MySQL server configuration
$servername = "localhost"; // If MySQL is on the same server as PHP
$username = "root"; // Your MySQL username
$password = ""; // Your MySQL password
$database = "mydatabase"; // Your MySQL database name

// Create connection
$conn = mysqli_connect($servername, $username, $password, $database);

// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

echo "Connected successfully";

// SQL query to create a table


$sql = "CREATE TABLE userss (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE
CURRENT_TIMESTAMP
)";

// Execute query
if (mysqli_query($conn, $sql)) {
echo "Table users created successfully";
} else {
echo "Error creating table: " . mysqli_error($conn);
}

// Close connection
mysqli_close($conn);
?>
21. Develop a PHP program to design a college admission form using MYSQL database.

<!DOCTYPE html>
<html>
<head>
<title>College Admission Form</title>
<style>
.container {
max-width: 600px;
margin: 50px auto;
background-color: powderblue;
padding: 20px;
border-radius: 5px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
}

h2 {
text-align: center;
color: blue;
}

form {
margin-top: 20px;
}

label {
font-weight: bold;
color: brown;

}
</style>
</head>
<body>
<h2>College Admission Form</h2>
<div class="container">
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
<label for="name">Name:</label><br>
<input type="text" id="name" name="name" required><br><br>

<label for="email">Email:</label><br>
<input type="email" id="email" name="email" required><br><br>

<label for="phone">Phone:</label><br>
<input type="text" id="phone" name="phone" required><br><br>

<label for="address">Address:</label><br>
<textarea id="address" name="address" required></textarea><br><br>

<label for="dob">Date of Birth:</label><br>


<input type="date" id="dob" name="dob" required><br><br>
<label for="gender">Gender:</label><br>
<select id="gender" name="gender" required>
<option value="Male">Male</option>
<option value="Female">Female</option>
<option value="Other">Other</option>
</select><br><br>

<label for="course">Course:</label><br>
<input type="text" id="course" name="course" required><br><br>

<input type="submit" value="Submit">


</form>
</div>

<?php
// Database connection parameters
$servername = "localhost";
$username = "root";
$password = "";

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

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

// Create new database


$sql_create_db = "CREATE DATABASE IF NOT EXISTS college_admission";

if ($conn->query($sql_create_db) === TRUE) {


echo "Database created successfully<br>";
} else {
echo "Error creating database: " . $conn->error;
}

// Select the newly created database


$conn->select_db("college_admission");

// SQL to create table


$sql_create_table = "CREATE TABLE IF NOT EXISTS admission_form (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
email VARCHAR(100),
phone VARCHAR(20),
address VARCHAR(255),
dob DATE,
gender ENUM('Male', 'Female', 'Other'),
course VARCHAR(100),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)";

// Execute SQL query to create table


if ($conn->query($sql_create_table) === TRUE) {
echo "Table admission_form created successfully<br>";
} else {
echo "Error creating table: " . $conn->error;
}

// Check if form is submitted


if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Retrieve form data
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$address = $_POST['address'];
$dob = $_POST['dob'];
$gender = $_POST['gender'];
$course = $_POST['course'];

// SQL to insert data


$sql_insert_data = "INSERT INTO admission_form (name, email, phone, address, dob, gender,
course) VALUES ('$name', '$email', '$phone', '$address', '$dob', '$gender', '$course')";

// Execute SQL query to insert data


if ($conn->query($sql_insert_data) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql_insert_data . "<br>" . $conn->error;
}
}

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

You might also like