0% found this document useful (0 votes)
101 views29 pages

PHP Labprograms BCA NEP

The document contains a series of PHP scripts demonstrating various programming tasks such as printing 'Hello World', checking odd/even numbers, finding the maximum of three numbers, swapping values, calculating factorials, and more. Each script is accompanied by HTML structure and outputs the results of the executed code. The tasks also include form handling, matrix addition, file uploads, and using date/time functions.

Uploaded by

chaitrahr2020
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)
101 views29 pages

PHP Labprograms BCA NEP

The document contains a series of PHP scripts demonstrating various programming tasks such as printing 'Hello World', checking odd/even numbers, finding the maximum of three numbers, swapping values, calculating factorials, and more. Each script is accompanied by HTML structure and outputs the results of the executed code. The tasks also include form handling, matrix addition, file uploads, and using date/time functions.

Uploaded by

chaitrahr2020
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/ 29

1.

Write a PHP script to print “hello world”


<!DOCTYPE html>
<html>
<body>
<?php
echo "Hello World!";
?>
</body>
</html>

Output :
Hello world
2. Write a PHP script to find odd or even number from given number.
<!DOCTYPE html>
<html>
<body>
<?php
$number = 21;
if ($number % 2 == 0) {
print "It's even";
}
else
{
print "It's odd";
}

?>
</body>
</html>

Output :
its Odd
3. Write a PHP script to find maximum of three numbers.
<!DOCTYPE html>
<html>
<body>
<?php
$number1 = 123;
$number2 = 72;
$number3 = 151;
$maxNumber = max($number1, $number2, $number3);
echo "The largest number among three is: $maxNumber\n";
?>
</body>
</html>

Output :
The largest number among three numbers is :151

4. Write a PHP script to swap two numbers.


<?php
$a=45;
$b=56;
echo "Before swapping : ";
echo "<br>";
echo "a=",$a ;
echo "<br>";
echo "b=",$b;
echo "<br>";
//Swaping logic
$third=$a;
$a=$b;
$b=$third;
echo "After Swapping : ";
echo "<br>";
echo "a=",$a ;
echo "<br>";
echo "b=",$b;

Output :
Before swapping :
a=45
b=56
After Swapping :
a=56
b=45

5. Write a PHP script to find the factorial of a number.


<?php
function Factorial($number) {
if ($number <= 1) {
return 1;
}
else {
return $number * Factorial ($number - 1);
}
}
$number = 5;
$fact = Factorial($number);
echo "Factorial = $fact";
?>

Output :
Factorial = 120
6. Write a PHP script to check if number is palindrome or not.
<?php

$num = 12321;
$org_num=$num;
$revnum = 0;
while ($num != 0)
{
$revnum = $revnum * 10 + $num % 10;
//below cast is essential to round remainder towards zero
$num = (int)($num / 10); //0
}

if($revnum==$org_num)
{
echo $org_num," is Palindrome number";
}
else
{
echo $org_num." is not Palindrome number";
}
?>

Output :
12321 is palindrome number

7. Write a PHP script to reverse a given number and calculate its sum

<?php

function reverse_number($num) {

$rev_num = 0;

while ($num > 0) {

$rev_num = $rev_num * 10 + $num % 10;


$num = (int)($num / 10);

return $rev_num;

function calculate_sum($num) {

$sum = 0;

while ($num > 0) {

$sum += $num % 10;

$num = (int)($num / 10);

return $sum;

$num = 12345;

$reversed_num = reverse_number($num);

$sum = calculate_sum($reversed_num);

echo "The original number is $num.";

echo "The reversed number is $reversed_num.";

echo "The sum of the digits of the reversed number is $sum.

?>

Output :
The orginal number is 12345
The reversed number is 54321
The sum of the degits of reversed number is 15
8. Write a PHP script to generate a Fibonacci series using Recursive function

<?php

function fibonacci($n, $first_num = 0, $second_num = 1) {

if($n == 0) {

return;

echo $first_num . ", ";

$next_num = $first_num + $second_num;

fibonacci($n - 1, $second_num, $next_num);

$n = 10; // Number of elements you want in the series

echo "Fibonacci Series: ";

fibonacci($n);

?>

Output :
Fibonacci series :
01123

9. Write a PHP script to implement atleast seven string functions

<?php

$str = 'Hello, PHP!';

echo $str;

echo "<br> <br> ";

echo strlen($str);

echo "<br> <br> ";


echo str_replace('Hello', 'Hi', $str);

echo "<br> <br> ";

echo strtolower($str);

echo "<br> <br> ";

echo strtoupper($str);

echo "<br> <br> ";

echo substr($str, 7, 3);

echo "<br> <br> ";

echo strpos($str, 'PHP');

$part = substr($str,7,3);

echo "$part";

?>

Output :
Hello, PHP!

string length is : 11

After replacing string is : Hi, PHP!

string conversion to lowercase : hello, php!

string conversion to uppercase : HELLO, PHP!

substring value is : PHP

string position of PHP is : 7

string word count is : 2

string comparsion value is : -1

string comparsion value is : -1


10. Write a PHP script to insert new item in array on any position in PHP

<?php

$original_array = array( '1', '2', '3', '4', '5' );

echo 'Original array : ' ;

foreach ($original_array as $x)

echo "$x ";

echo "<br> <br> ";

$inserted_value = '11';

$position = 2;

//array_splice() function

array_splice( $original_array, $position, 0, $inserted_value );

echo "After inserting 11 in the array is : ";

foreach ($original_array as $x)

echo "$x ";

?>

Output :
Original array :1 2 3 4 5

After inserting 11 in the aray is :1 2 11 3 4 5


11. Write a PHP script to implement constructor and destructor

<?php

class Employee

Public $name;

Public $position;

function __construct($name,$position)

// This is initializing the class properties

$this->name=$name;

$this->position=$position;

function show_details()

echo $this->name." : ";

echo "Your position is ".$this->position."<br>";

function __destruct() {

echo "<br> <br>";

echo " Inside destructor <br>";

echo "The name is {$this->name} and position is {$this->position}. <br>";

$employee_obj= new Employee("Rakesh","developer");

$employee_obj->show_details();
$employee2= new Employee("Vikas","Manager");

$employee2->show_details();

?>

Output :
Rakesh:your position is :Developer
Vikas:your position is :Manager

Inside destructor,
The name is Vikas and position is Manager,

Inside destructor,
The name is Rakesh and position is Developer,

12. Write a PHP script to implement form handling using get method

<!DOCTYPE html>

<html>

<body>
<h4>PHP Form Handling using GET method</h4>

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="get">


Name: <input type="text" name="name">
Age: <input type="number" name="age">

<input type="submit">
</form>
<?php

if(isset($_GET['name']) && isset($_GET['age'])): ?>

<br/>
Your name is <?php echo $_GET["name"]; ?>

<br/>
Your age is <?php echo $_GET["age"]; ?>
<?php endif; ?>
</body>
</html>
Output :

WRITE WITH URL

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

<!DOCTYPE html>

<html>

<body>

<h4>PHP Form Handling using POST method</h4>

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">

Name: <input type="text" name="name">

Age: <input type="number" name="age">

<input type="submit">

</form>

<?php

if(isset($_POST['name']) && isset($_POST['age'])): ?>

<br/>

Your name is <?php echo $_POST["name"]; ?>

<br/>

Your age is <?php echo $_POST["age"]; ?>


<?php endif; ?>

</body>

</html>

Output :

14.Write a PHP script that receive form input by the method post to check the
number is prime or not

<!DOCTYPE html>

<html>

<body>

<form method="post">

Enter a Number: <input type="text" name="input"><br><br>

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

</form>

<?php

if($_POST)

$input=$_POST['input'];

for ($i = 2; $i <= $input-1; $i++) {

if ($input % $i == 0) {

$value= True;
}

if (isset($value) && $value) {

echo 'The Number '. $input . ' is not prime';

} else {

echo 'The Number '. $input . ' is prime';

?>

</body>

</html>

Output :

15. Write a PHP script that receive string as a form input

<!DOCTYPE html>

<html>

<body>

<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">


Enter a string: <input type="text" name="inputString">

<input type="submit">

</form>

<?php

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

// collect value of input field

$string = $_POST['inputString'];

if (empty($string)) {

echo "String is empty";

} else {

echo "The string you entered is: " . $string;

?>

</body>

</html>

Output :
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="">

<h3>Matrix A</h3>

<label for="a11">A[1][1]:</label>

<input type="number" name="a11" required>

<label for="a12">A[1][2]:</label>

<input type="number" name="a12" required><br><br>

<label for="a21">A[2][1]:</label>

<input type="number" name="a21" required>

<label for="a22">A[2][2]:</label>

<input type="number" name="a22" required><br><br>

<h3>Matrix B</h3>

<label for="b11">B[1][1]:</label>

<input type="number" name="b11" required>

<label for="b12">B[1][2]:</label>

<input type="number" name="b12" required><br><br>

<label for="b21">B[2][1]:</label>

<input type="number" name="b21" required>

<label for="b22">B[2][2]:</label>

<input type="number" name="b22" required><br><br>

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

</form>

<?php

if (isset($_POST['submit'])) {
// Get the values from the form for Matrix A

$a11 = (int)$_POST['a11'];

$a12 = (int)$_POST['a12'];

$a21 = (int)$_POST['a21'];

$a22 = (int)$_POST['a22'];

// Get the values from the form for Matrix B

$b11 = (int)$_POST['b11'];

$b12 = (int)$_POST['b12'];

$b21 = (int)$_POST['b21'];

$b22 = (int)$_POST['b22'];

// Add the corresponding elements of Matrix A and Matrix B

$c11 = $a11 + $b11;

$c12 = $a12 + $b12;

$c21 = $a21 + $b21;

$c22 = $a22 + $b22;

// Display the result

echo "<h3>Resultant Matrix (A + B)</h3>";

echo "<table border='1'>";

echo "<tr><td>$c11</td><td>$c12</td></tr>";

echo "<tr><td>$c21</td><td>$c22</td></tr>";

echo "</table>";

?>

</body>

</html>

Output :
Write the numbers in
blank boxes

5 2 6 7

9 2 7 8

17. Write php script to show the functionality of date time function.

<?php

// Set the default timezone to UTC

date_default_timezone_set('UTC');

// Display the current date and time in various formats

echo "Current date and time: " . date('Y-m-d H:i:s') . "\n";

echo "Current year: " . date('Y') . "\n";

echo "Current month: " . date('m') . "\n";

echo "Current day: " . date('d') . "\n";

echo "Current hour: " . date('H') . "\n";

echo "Current minute: " . date('i') . "\n";

echo "Current second: " . date('s') . "\n";

// Display the current timestamp

echo "Current timestamp: " . time() . "\n";


// Use mktime to create a specific date and time

$timestamp = mktime(14, 30, 0, 3, 10, 2024); // 14:30:00 on March 10, 2024

echo "Specific date and time (March 10, 2024 14:30:00): " . date('Y-m-d H:i:s', $timestamp) . "\n";

// Use strtotime to convert a string into a timestamp

$strToTime = strtotime('next Monday');

echo "Next Monday: " . date('Y-m-d H:i:s', $strToTime) . "\n";

?>

Output :
Current date and time :24-06-15 15:29:50
Current year :24
Current month :06
Current day :15
Current hour :15
Current minute :29
Current second :50
Current time slap :1718465390
specific date and time (March 10,2024 14:30:00) : 24-03-10 14:30:00
Next Monday :24-06-17 00:00:00

18. Write a PHP program to upload a file

index.html
<!DOCTYPE html>

<html>

<body>

<form action="fileupload.php" method="post"

enctype="multipart/form-data">

Directory<input type="text" name="dirname"


id="dirname"><br>

Select file to upload:

<input type="file" name="fileToUpload"

id="fileToUpload"><br>

<input type="submit" value="Upload "

name="submit">

</form>

</body>

</html>

fileupload.php
<!DOCTYPE html>

<?php

$target_dir = $_POST["dirname"]."/";

$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);

$uploadOk = 1;

$imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));

$extensions = array("jpeg","jpg","png","pdf","gif");

if(isset($_POST["submit"])) {

// To check whether directory exist or not

if(!empty($_POST["dirname"])){

if(!is_dir($_POST["dirname"])) {

mkdir($_POST["dirname"]);

$uploadOk = 1;

else {
echo "Specify the directory name...";

$uploadOk = 0;

exit;

// To check extensions are correct or not

if(in_array($imageFileType, $extensions) === true) {

$uploadOk = 1;

else {

echo "No file selected or Invalid file extension...";

$uploadOk = 0;

exit;

// Check if file already exists

if (file_exists($target_file)) {

echo "Sorry, file already exists.";

$uploadOk = 0;

exit;

// Check file size

if ($_FILES["fileToUpload"]["size"] > 10000000) {

echo "Sorry, your file is too large.";

$uploadOk = 0;

exit;

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

if ($uploadOk == 0)

echo "Sorry, your file was not uploaded.";

else

// If everything is ok, try to upload file

if (move_uploaded_file($_FILES["fileToUpload"]

["tmp_name"], $target_file))

echo "The file ". $_FILES["fileToUpload"]

["name"]. " has been uploaded.";

else

echo "Sorry, there was an error uploading your file.";

?>

</body>

</html>

Output :
19. Write a PHP script to implement database creation

<?php

$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 database

$sql = "CREATE DATABASE employeeDB";

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

echo "Database created successfully";

} else {

echo "Error creating database: " . $conn->error;

$conn->close();

?>

Output :
Database created successfully
20. Write a PHP script to create table
<?php

$servername = "localhost";

$username = "root";

$password = "";

$conn = mysqli_connect($servername, $username, $password);

// Create database

$sql = "CREATE DATABASE empDB";

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

echo "<br> Database created successfully";

} else {

echo "<br> Error creating database: " . $conn->error;

$dbname = "empDB";

$conn = mysqli_connect($servername, $username, $password,$dbname);

// sql to create table

$sql = "CREATE TABLE My_Employees (

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

)";

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

echo "<br> Table MyEmployees created successfully";

} else {
echo "<br> Error creating table: " . $conn->error;

$conn->close();

?>

Output :

Database created successfully


Table MyEmployees created successfully

21. Develop a PHP program to design a college admission form using MYSQL database.
Form.html

<!DOCTYPE html>

<html lang="en">

<body>

<h1>College Admission Form</h1>

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

<p>

FirstName:

<input type="text" name="first_name" id="firstName"/>

<span style="color:red;">*</span>

<br>

<br>

</p>

<p>

LastName:

<input type="text" name="last_name" id="lastName"/>


<span style="color:red;">*</span>

<br>

<br>

</p>

<p>

<label for="Gender">Gender:</label>

<input type="text" name="gender" id="Gender">

<span style="color:red;">*</span>

</p>

<p>

Address:

<input type="text" name="address" id="Address"/>

<span style="color:red;">*</span>

<br>

<br>

</p>

<p>

Email:

<input type="email" name="email" id="emailAddress"/>

<span style="color:red;">*</span>

<br>

<br>

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

</form>

</center>

</body>

</html>

insert.php

<!DOCTYPE html>

<html>

<head>

<title>Insert Page page</title>

</head>

<body>

<center>

<?php

$servername = "localhost";

$username = "root";

$password = "";

$dbname = "admission_DB";

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

// Check connection

if($conn === false){

die("ERROR: Could not connect. "

. mysqli_connect_error());
}

// Create database if it doesn't exist

$sql = "CREATE DATABASE IF NOT EXISTS $dbname";

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

echo "Database created successfully";

} else {

echo "Error creating database: " . $conn->error;

// Select the database

$conn->select_db($dbname);

// sql to create table

$sql = "CREATE TABLE IF NOT EXISTS Admission_Details (

first_name VARCHAR(30) NOT NULL,

last_name VARCHAR(30) NOT NULL,

gender VARCHAR(30) NOT NULL,

address VARCHAR(255) NOT NULL,

email VARCHAR(50)

)";

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

echo "Table admission table created successfully";

} else {

echo "Error creating table: " . $conn->error;

}
// Taking all 5 values from the form data(input)

$first_name = $_REQUEST['first_name'];

$last_name = $_REQUEST['last_name'];

$gender = $_REQUEST['gender'];

$address = $_REQUEST['address'];

$email = $_REQUEST['email'];

// Performing insert query execution

// here our table name is college

$sql = "INSERT INTO Admission_Details VALUES ('$first_name',

'$last_name','$gender','$address','$email')";

if(mysqli_query($conn, $sql)){

echo "<h3>data stored in a database successfully."

. " Please browse your localhost php my admin"

. " to view the updated data</h3>";

echo nl2br("\n$first_name\n $last_name\n "

. "$gender\n $address\n $email");

} else{

echo "ERROR: Hush! Sorry $sql. "

. mysqli_error($conn);

}
// Close connection

mysqli_close($conn);

?>

</center>

</body>

</html> Output :

You might also like