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

PHP Practical Codes Final

Uploaded by

HARSH MAGHNANI
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
52 views

PHP Practical Codes Final

Uploaded by

HARSH MAGHNANI
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

1.

Program to find given number is even or odd

Code:
<?php
$n=18;
echo"Number=",$n,"<br>";
if($n%2==0)
echo"Number is even";
else
echo"Number is odd";
?>

2. Program to check number is positive or negative

Code:
<?php
$n=-11;
echo"Number=",$n,"<br>";
if($n>0)
echo"Number is positive";
elseif($n<0)
echo"Number is negative";
else
echo"Number is Zero"
?>

3. Calendar program using switch statement Code:

Code:
<?php
$month=5;
echo"Month=",$month,"<br>";
switch($month)
{
case 1:
echo"January";
break;
case 2:
echo"February";
break;
case 3:
echo"March";
break;
case 4:
echo"April";
break;
case 5:
echo"May";
break;
case 6:
echo"June";
break;
case 7:
echo"July";
break;
case 8:
echo"August";
break;
case 9:
echo"September";
break;
case 10:
echo"October";
break;
case 11:
echo"November";
break;
case 12:
echo"December";
break;
default:
echo"Invalid Month";
}
?>

4. Print first 30 even numbers using(for, while, do


while)

Code:
<?php
$i=2;
echo "for loop:\n";
for($i=2; $i<=60; $i+=2)
echo $i," ";

$i=2;
echo "\n\nWhile loop:\n";
while($i<=60)
{
echo $i," ";
$i+=2;
}

$i=2;
echo "\n\nDo-While loop:\n";
do{
echo $i," ";
$i+=2;
}while($i<=60)
?>

5. Display following patterns:


a) 11111
1111
111
1

Code:
<?php
for ($i = 5; $i >= 1; $i--) {
for ($j = 1; $j <= $i; $j++) {
echo "1";
}
echo "<br>";
}
?>

b) 54321
4321
321
21
1

Code:
<?php
for ($i = 5; $i >= 1; $i--) {
for ($j = $i; $j >= 1; $j--) {
echo $j;
}
echo "\n";
}
?>

c)
55555
4444
333
22
1

Code:
<?php
for($i = 5; $i >= 1; $i--){
for($j = 1; $j <= $i; $j++){
echo$i;
}
echo"<br>";
}
?>

d)
*
**
***
****
*****
Code:
<?php
for($i=1;$i<=5;$i++){
for($j=1;$j<=$i;$j++){
echo"*";
}
echo"<br>";
}
?>

6. Display current date and time Code:


<?php
//for ist time
date_default_timezone_set('Asia/Kolkata');
$cdt = date("d-m-Y H:i:s");
echo "Current Date and Time: $cdt";
?>

7. Program for arithmetic operations


Code:
<?php
$a=20;
$b=10;
echo"First Number=",$a,"<br>";
echo"Second Number=",$b,"<br>";
echo"Addition=",$a+$b,"<br>";
echo"Subraction=",$a-$b,"<br>";
echo"Multiplication=",$a*$b,"<br>";
echo"Division=",$a/$b,"<br>";
echo"Exponential of ",$a,"^2 =",$a**2
?>

8. Number is palindrome or not(input from user)


Code:
<html>
<body>
<form method="post" action="">
Enter a number: <input type="text" name="number">
<input type="submit" name="submit" value="check">
</form>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$no = $_POST["number"];

$no2 = strrev($no);

if($no == $no2)
echo "Palindrome";
else
echo "Not a Palindrome";
}
?>
</body>
</html>

9. Program to display multidimensional array


Code:
<?php
// Define a multidimensional array
$multiArray = array(
array(1, 2, 3),
array(4, 5, 6),
array(7, 8, 9)
);

// Display the multidimensional array


echo "<pre>";
print_r($multiArray);
echo "</pre>";
?>

10. Count no of words in a string without using built in function


Code:
<?php
$str = "HELLO SAGAR";
$count = 1;

for ($i = 0; $i < strlen($str); $i++)


{
if($str[$i] === " ")
$count++;
}

echo "String: ",$str;


echo "<br>Length: ",strlen($str);
echo "<br>Number of words: ",$count;
?>
11. Count words with built in function and convert string in
uppercase
Code:
<?php
$str = "Sagar Chanchlani";
echo "String: ",$str;
echo "<br>No of words: ",str_word_count($str);
echo "<br>Uppercase: ",strtoupper($str);
?>

12. Multilevel inheritance


Code:
<?php
class Vehicle {
function startEngine(){
echo "Engine started<br>";
}
}

class Car extends Vehicle {


function drive(){
echo "Driving Car<br>";
}
}

class SportsCar extends Car {


function accelerate(){
echo "Sports car<br>";
}
}

$sportsCar = new SportsCar();


$sportsCar->startEngine();
$sportsCar->drive();
$sportsCar->accelerate();
?>
13. Multiple inheritance
Code:
<?php
interface Engine {
function startEngine();
}

interface Wheels {
function rotateWheels();
}

class Car implements Engine, Wheels {


function startEngine() {
echo "Engine started<br>";
}

function rotateWheels() {
echo "Wheels rotating<br>";
}
}

$car = new Car();


$car->startEngine();
$car->rotateWheels();
?>

14. Parameterized and default constructor


Code:
<?php
class MyClass {
function __construct() {
echo "My name is Harsh Maghnani";
}
}

class MyClass2 {
function __construct($num1, $num2) {
$sum = $num1 + $num2;
echo "<br>The sum of $num1 and $num2 is $sum<br>";
}
}
$ob = new MyClass();
$ob1 = new MyClass2(5, 5);
?>
15. Introspection and serialization
Code:
<?php
//Serialization
echo "Serialization:<br>";
$data = array(
'name' => 'John',
'age' => 30,
'city' => 'New York'
);

$serialized_data = serialize($data);
echo $serialized_data, "<br><br>";

$unserialized_data = unserialize($serialized_data);
print_r($unserialized_data);

//Introspection
echo "<br><br>Introspection:<br>";
class MyClass {
public $prop1 = "Property 1";
public $prop2 = "Property 2";

public function method1() {


echo "This is method1.<br>";
}

public function method2() {


echo "This is method2.<br>";
}
}

$obj = new MyClass();

echo "Class Name: " . get_class($obj) . "<br><br>";

echo "Class Methods: <br>";


print_r(get_class_methods($obj));
echo "<br><br>";

echo "Class Properties: <br>";


print_r(get_object_vars($obj));
?>
16. WAP for Registration form
Code:

<!DOCTYPE html>
<html>
<head>
<title>Registration Form</title>
</head>

<body>
<form action="" method="post">
Full Name: <input type="text" name="name" required> <br><br>
Mobile Number: <input type="text" name="mbno"
maxlength="10" required><br><br>
Address: <textarea name="address" rows="3" cols="20"
required></textarea><br>
Gender:
<input type="radio" name="gender" value="male">Male
<input type="radio" name="gender" value="female">Female<br>
Select Subjects:<br>
<input type="checkbox" name="subjects[]"
value="Python">Python<br>
<input type="checkbox" name="subjects[]" value="Mobile
App">Mobile App<br>
<input type="checkbox" name="subjects[]"
value="PHP">PHP<br>
<input type="submit" name="submit">
</form>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (!empty($_POST['gender'])) {
if (!empty($_POST['subjects'])) {
echo "Your Name: ", $_POST['name'], "<br>";
echo "Your Mobile Number: ", $_POST['mbno'], "<br>";
echo "Address:", $_POST['address'], "<br>";
echo "Gender:", $_POST['gender'], "<br>";
echo "Selected Subjects:";
foreach ($_POST['subjects'] as $checked) {
echo $checked, " ";
}
} else {
echo "Select subjects";
}
} else {
echo "Select gender";
}
}
?>
</body>
</html>

17. Develop a web page and do validations on control textbox,


radio button, checkbox and button
Code:
Same as above(Q16.)

18. Form using listbox combo box and hidden field


Code:
<!DOCTYPE html>
<html lang="en">
<body>
<form method="post">
<p>Select a colour from the List Box:</p>
<select size=4 name="colors">
<option value="Red">Red</option>
<option value="Blue">Blue</option>
<option value="Green">Green</option>
<option value="Black">Black</option>
</select>
<p>Select a fruit from the Combo Box:</p>
<select name="fruits">
<option value="Apple">Apple</option>
<option value="Banana">Banana</option>
<option value="Grapes">Grapes</option>
</select><br><br>
<input type="hidden" value="Hidden Value" name="hidden" />
<input type="submit" value="Submit" />
</form>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$color = $_POST['colors'] ?? null;
$hidden = $_POST['hidden'] ?? null;
$fruits = $_POST['fruits'] ?? null;

if ($color !== null) {


echo "<br>You selected color: $color<br>";
} else {
echo "<br>No color selected.";
}

if ($fruits !== null) {


echo "You selected fruit: $fruits<br>";
echo "Hidden value: $hidden";
} else {
echo "No fruit selected.";
}
}
?>
</body>
</html>

19. Create delete and modify cookie


Code:
<?php
// Create a cookie
echo "<b>Creating a Cookie:</b> <br>";
setcookie("user", "JohnWick", time() + 3600);

// Check if the cookie is set and display its value


if(isset($_COOKIE["user"])) {
echo "Cookie value: " . $_COOKIE["user"] . "<br>";
} else {
echo "Cookie not set!<br>";
}

echo "<br><b>Updating a Cookie:</b> <br>";


// Update the cookie value by setting a new cookie
$new_cookie_value = "WickJohn";
setcookie("user", $new_cookie_value, time() + 3600);
echo "Modified cookie value: " . $new_cookie_value ;

//Delete the cookie


echo "<br><br><b>Deleting a Cookie:</b> <br>";
setcookie("user", "", time() - 3600);
echo "Cookie deleted.";
?>
20. Start and destroy session
Code:
<?php
// Start the session
session_start();

// Set session variables


$_SESSION["username"] = "JohnWick";

// Display session variable


echo "Session started. <br>Username: " .
$_SESSION["username"] . "<br>";

//Destroy the session


session_destroy();
echo "<br>Session destroyed.";
?>

21. Send email


Code:
<html>
<body>
<form method="post" action= " " >
Email From: <textarea type="email" name="from"
required></textarea><br><br>
Email To: <textarea type="email" name="to"
required></textarea><br><br>
Subject:<input type="text" name="subject" required><br><br>
Message:<textarea name="message" rows="2" cols="16"
required></textarea><br><br>
<input type="submit" value="Send Email">
</form>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$from = $_POST["from"];
$to = $_POST["to"];
$sub = $_POST["subject"];
$mess = $_POST["message"];
$header = "From: $from";
if (mail($to, $sub, $mess, $header)) {
echo "<H4><B>mail sent</B></H4>";
} else {
echo "<H4><B>fail to send email</B></H4>";
}
}
?>
</body>
</html>

22. Check email are valid


Code:
<html>
<body>
<form action="" method="post">
Enter email: <input type="email" name="mail" /><br>
<input type="submit" name="btn" />
</form>
</body>
<?php
if (isset($_POST['btn'])) {
$mail = $_POST['mail'];
if (!filter_var($mail, FILTER_VALIDATE_EMAIL)) {
echo "Invalid email";
} else {
echo "Valid email";
}
}
?>
</body>
</html>

23. Insert data into employee table


Code:
<?php
$servername="localhost";
$username="root";
$password="";
$db="test";

$con=mysqli_connect($servername,$username,$password,$db);
if(!$con)
echo "Something went wrong";
else
echo"Database connected";
$sql="INSERT INTO employee (empid,name,age) VALUES
(01,'JOHN',18)";

if(mysqli_query($con,$sql))
echo"Record inserted";
else
echo"Error";
?>

24. Update data from database


Code:
<?php
$hostname = "localhost";
$username = "root";
$password = "";
$db = "test";

$con = mysqli_connect($hostname, $username, $password, $db);

if (!$con) {
echo "Something went wrong";
} else {
echo "Database connected";
}

$sql = "UPDATE employee SET empid = 22 WHERE empid = 01";

if (mysqli_query($con, $sql)) {
echo "Record Updated";
} else {
echo "Error";
}
?>
25. Delete data from database
Code:
<?php
$hostname = "localhost";
$db = "test";
$username = "root";
$password = "";
$con = mysqli_connect($hostname, $username, $password, $db);

if (!$con) {
echo "Something went wrong";
} else {
echo "Database connected";
}

$sql = "DELETE FROM employee WHERE empid = 22";

if (mysqli_query($con, $sql)) {
echo "Record Deleted";
} else {
echo "Error";
}
?>
26. Write a script to create an image.
Note: Enable gd extension from php.ini (config file)
Steps: (For Understanding)
1. Open Xamp -> Click on Config of Apache

2. Click on PHP(php.ini)
3. Search the following line ;extension=gd
4. Remove the semicolon from the beginning of the line to
uncomment it and save the changes
5. Restart Xampp

Code:
<?php
// Set content type to PNG image
header("Content-Type: image/png");

// Create a 500x500 true color image


$img = imagecreatetruecolor(500, 500);

// Allocate background color (150, 150, 150)


$bgcolor = imagecolorallocate($img, 150, 150, 150);

// Allocate font color (120, 60, 200)


$fcolor = imagecolorallocate($img, 120, 60, 200);

// Add text "Example" at (5, 5) with font size 1


imagestring($img, 1, 5, 5, "Example", $fcolor);

// Output image as PNG


imagepng($img);

// Free memory
imagedestroy($img);
?>
27. Write a program to create a PDF file.
Note: Download fpdf zip file from google

Steps: (For understanding)


1. Download fpdf zip file from here http://www.fpdf.org/
2. Extract the file
3. Here, I have created a folder “fpdf” in C:\xampp\htdocs\ and
then I have extracted the zip file in it (C:\xampp\htdocs\fpdf)
4. Write the program and run

Code:

<?php

// Include the FPDF library


require("C:/xampp/htdocs/fpdf/fpdf.php");

// Create a new instance of FPDF


$pdf = new FPDF();

// Add a page to the PDF


$pdf->AddPage();

// Set the font for the PDF


$pdf->SetFont('Arial', 'B', 16);

// Add text to the PDF


$pdf->Cell(40, 10, 'Hello, world!');

// Output the PDF to the browser and force download as 'example.pdf'


$pdf->Output('example.pdf', 'D');
?>

You might also like