0% found this document useful (0 votes)
55 views101 pages

J It PHP Manual

Uploaded by

meet40945
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
55 views101 pages

J It PHP Manual

Uploaded by

meet40945
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 101

Enrollment No: 226480316029

SIGMA UNIVERSITY

DEPARTMENT OF
FACULTY OF COMPUTER SCIENCE AND APPLICATIONS

LAB MANUAL

ADVANCE WEB TECHNOLOGIES

IT(I-SEM)
Prof. – Kajal Patel

1
Enrollment No: 226480316029

Lab Exercises

1 Install and configure PHP, web server, and MYSQL

2 Write a PHP program.


a. to print "Welcome to PHP”.
b. using expressions and operators
3 Write a PHP program to demonstrate the use of Decision Making Control
structure Using-
a. If-Statement
b. If-Else Statement
c. Switch Statement
4 Write a PHP program to demonstrate the use of Looping structure Using-
a. While Statement
b. Do-While Statement
c. For Statement
d. Foreach Statement
5 Write a PHP program for Creating and Manipulating-
a. Indexed Array
b. Associative Array
c. Multidimensional Array
6 a. Write a PHP program to-
i. Calculate length of String
ii. Count the number of words in a string without using string functions.
b. Write a simple PHP program demonstrate use of various built-in string function.
7 Write a simple PHP program to create PDF document buy
using graphics concepts
8 Design a web page using following form controls:
a. Text box,
b. Radio button,
c. Check box,
d. Buttons List box,
e. Combo box,
f. f. Hidden field box
9
Write simple PHP program to -
a. Set cookies and read it.
b. Demonstrate session management

2
Enrollment No: 226480316029

10 Develop web page with data validation


A . Form validation is required to prevent web form abuse by
malicious users. Impropervalidation of form data is one of the
main causes of security vulnerabilities. It exposes your website
to attacks such as header injections, cross-site scripting, and SQL
injections.
b. header injection attacks can be used to send email spam from
your web server.
c. cross-site scripting may allow an attacker to post any data to your

3
Enrollment No: 226480316029

site.
d. SQL injection may corrupt your database backend
11 Develop a simple application to -
a. Enter data into database.
b. Retrieve and present data from database
12 Develop a simple application to Update , Delete table data from
database. PHP MySQL Update Query
13 Write a PHP script for Swapping of Three numbers.

14 Write a PHP script to find maximum number out of three given numbers.

15 Write a PHP script to Check the given number is Palindrome or Not.

16 Write a PHP script to print Fibonacci series.

17 Write a PHP script to check the given number is prime or not.

18 Write PHP Script to calculate total marks of student and display grade .

19 19-1. Write a PHP script to get type of variable using gettype().


19-2. Write a PHP script to set type of variable using settype().

4
Enrollment No: 226480316029

20 A. Write PHP script to demonstrate use of string function- chr() and ord().

B. Write PHP script to demonstrate use of string function-


strtolower () & strtoupper () & strlen().

C. Write PHP script to demonstrate use of string function-


ltrim() & rtrim() & trim().

D. Write PHP script to demonstrate use of string function- substr().

E. Write PHP script to demonstrate use of string function- substr().

F. Write PHP script to demonstrate use of string function- strcmp ().

G. Write PHP script to demonstrate use of string function- strcasecmp ().

H. Write PHP script to demonstrate use of string function- strpos().

I. Write PHP script to demonstrate use of string function- - str_replace ().

J.Write PHP script to demonstrate use of string function- strrev ().


21 A. Write PHP script to demonstrate use of date/time functions - date().
B. Write PHP script to demonstrate use of date/time functions -
getDate().

5
Enrollment No: 226480316029

C. Write PHP script to demonstrate use of date/time functions – Setdate


().
D. Write PHP script to demonstrate use of date/time functions –
mktime().
E. Write PHP script to demonstrate use of date/time functions – time()
& checkdate().
22 A. Write PHP Script to demonstrate use of Indexed/Numeric arrays
and for FOR EACH loop execution.
B. Write PHP Script to demonstrate use of associative arrays and
for FOR EACH loop execution.
C. Write PHP Script to demonstrate use of mixed array indexed
+associative arrays and print using prinr_r() function.
D.
i. Write PHP Script to demonstrate use of
multidimensional arrays .
ii. Write PHP Script to demonstrate sorting arrays .

6
Enrollment No: 226480316029

1/ Install and configure PHP, web server, and MYSQL


Step1:
Open Mycomputer >C drive >xampp >htdocs >create your folder >save your
fitst.php file
Ex: C:\xampp\htdocs\mahesh\first.php

Step2:
double click on “XAAMP CONTROL PANEL” on desktop and START “Apache”

Step3:
Type localhost on your browser and press enter:
It will show the following:

Step4:
Now type the following on browser:
localhost/your folder name/
EX: localhost/Mahesh

Step5 :
Click on “first.php” and it will show the following:

2/ Write a PHP program.


a. to print "Welcome to PHP”.

Program :

<?php

echo"Welcome to PHP ."

?>

Output :

7
Enrollment No: 226480316029

b. using expressions and operators

Program:

<?php

# arithmetic
$a = 10;
$b = 4;
echo($a + $b);
echo "<br>";
echo($a - $b);
echo "<br>";
echo($a * $b);
echo "<br>";
echo($a / $b);
echo "<br>";
echo($a %
$b);
?>

<br>

<?php

#comparison
$x = 100;
$y = 100;
var_dump($x == $y);
var_dump($x != $y);
var_dump($x <> $y);
var_dump($x !== $y);

?>

<br>

<?php
#comparison
$m = 100;
$r = 50;
8
Enrollment No: 226480316029

var_dump($m > $r);


?>

<br>

<?php
#comparison
$s = 10;
$t = 50;

var_dump($s < $t);


?>
<br>

<?php
#comparison
$n = 50;
$p = 50;

var_dump($n >= $p);


var_dump($n <= $p);

?>

<br>

<?php

#assignment
$v = 42;
$q = 20;

$c = $v + $q;
echo "addition Result: $c \n";

$c += $v;
echo "Add Result: $c \n";

$c -= $v;
echo "Subtract Result: $c \n";

$c *= $v;
echo "Multiply Result: $c \n";
9
Enrollment No: 226480316029

$c /= $v;
echo "Division Result: $c \n";

$c %= $v;
echo "Modulus Result: $c";
?>

<br>

<?php

/*increment & decrement*/


$u=5;
$i=5;
$u++; //postfix increment
$i--; //postfix decrement
echo "u = $u i = $i" . "
";
++$i; //prefix increment
--$u; //prefix decrement
echo "u = $u i = $i" . "
";;
?>

<br>

<?php

#logical
$d = 42;
$h = 0;

if ($d && $h) {


echo "TEST1 : Both d dnd h dre true \n";
} else {
echo "TEST1 : Either d or h is false \n";
}

echo"<br>";

if ($d || $h)

1
Enrollment No: 226480316029
{

1
Enrollment No: 226480316029

echo "TEST2 : Either d or h is true \n";


} else {
echo "TEST2 : Both d dnd h dre false \n";
}

echo"<br>";

if (!$d) {
echo "TEST7 : d is true \n";
} else {
echo "TEST7 : d is false \n";
}

if (!$h) {
echo "TEST8 : h is true \n";
} else {
echo "TEST8 : h is false";
}
?>

<?php

#string
$l="Hello";
$k=" ";
$e="PHP";
$str=$l . $k . $e;
echo $str;
?>

<br>

<?php

#array
$arr1=array("phy"=>70, "che"=>80, "math"=>90);
$arr2=array("Eng"=>70, "Bio"=>80,"CompSci"=>90);
$arr3=$arr1+$arr2;
var_dump($arr3);
?>

<?php
$arr4=array(0=>70, 2=>80, 1=>90);
1
Enrollment No: 226480316029

$arr5=array(70,90,80);
var_dump($arr4==$arr5);
var_dump($arr5!=$arr4); var_dump($arr5!
==$arr4);
?>

<br>

<?php

#conditional
$w = 10;
$z = 20;

$result = ($w > $z ) ? $w :$z;

echo "TEST1 : Value of result is $result \n";

$result = ($w < $z ) ? $w :$z;

echo "TEST2 : Value of result is $result";


?>

Output:

1
Enrollment No: 226480316029

3/ Write a PHP program to demonstrate the use of Decision Making Control


structure Using-

a/ If Statement
b/ If-else Statement
c/ Switch
Statement

Program :

<?php

#a.If

$d = date("D");
if($d=="Tue")
echo "Have a nice Tuesday!";
?>
<br></br>
<?php

#b.If-else

$d = date("D");
if($d=="Fri")
echo "Have a nice weekend!";
else
echo " Have a nice day!";
?>
<br></br>
<?php

#c.Switch

$d = date("D");

switch($d)
{
case"Mon";
echo " Today is Monday";
1
Enrollment No: 226480316029
break;

1
Enrollment No: 226480316029

case"Tue";
echo " Today is Tuesday";
break;

case"Wed";
echo " Today is Wednesday";
break;

case"Thu";
echo " Today is Thursday";
break;

case"Fri";
echo " Today is Friday";
break;

case"Sat";
echo " Today is
Saturday"; break;

case"Sun";
echo " Today is Sunday";
break;
}
?>

Output :

1
Enrollment No: 226480316029

4/ Write a PHP program to demonstrate the use of Looping structure Using-


a. While Statement
b. Do-While Statement
c. For Statement
d. Foreach Statement

Program :

<?php

#a.while

$i=1;
while($i <= 3)
{
echo"The number is".$i."<br>";
$i++;
}
?>

<br></br>

<?php

#b.do-while

1
Enrollment No: 226480316029

$a=1;
do
{
echo " The number is".$a."<br>";
$a++;
}
while($a<=4);
?>

<br></br>

<?php
#c.for

for($m=1;$m<=8;$m++)
{
echo"The number is".$m."<br>";
}
?>

<br></br>

<?php

#d.foreach

$names=array("Mohit","Mohan","Bhrumin");
foreach($names as $value)
{
echo $value."<br>";
}
echo"";
?>

Output :

1
Enrollment No: 226480316029

5/ Write a PHP program for Creating and Manipulating-


a. Indexed Array
b. Associative Array
c. Multidimensional Array

Program :

<?php

#a) Indexed

$numbers = array(1,2,3,4,5);
foreach($numbers as
$value)
{
echo"Value is $value <br/>";
}
echo"<br/>";
#second method
$numbers[0] = "one";
$numbers[1] = "two";
$numbers[2] = "three";
1
Enrollment No: 226480316029

$numbers[3] = "four";
$numbers[4] = "five";

foreach($numbers as

$value)

{
echo"Value is $value <br/>";
}
?>

<br>

<?php

#b)Associative

$Salary = array("Bhrumin"=>"350000","Mohit"=>"450000", "Mohan"=>"200000");

echo "Bhrumin salary: " .$Salary["Bhrumin"],"<br/>";

echo "Mohit salary: " .$Salary["Mohit"],"<br/>" ;

echo "Mohan salary: " .$Salary["Mohan"],"<br/>" ;


?>

<br>

<?php

#c)Multidimensional

$emp = array (

array(1,"Akshay",350000), array(2,"Davinder",450000), array(3,"Nikul",200000) );

for ($row = 0; $row < 3; $row++)

for ($col = 0; $col < 3; $col++)

2
Enrollment No: 226480316029
{

2
Enrollment No: 226480316029

echo $emp[$row][$col]." ";

echo "<br/>";

}
?>

Output :

6/ a. Write a PHP program to-


i. Calculate length of String
ii. Count the number of words in a string without using
string functions.

Program :

<?php

/* Calculate length of string */

$input = 'Kajal Patel';


2
Enrollment No: 226480316029

echo strlen($input);
?>

<br>

<?php

/* Count the number of words in a string without using string functions */

function countWords($string) {
$wordCount = 0;
$length = strlen($string);
$isWord = false;

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

if ($string[$i] != ' ') {


if (!$isWord) {
$wordCount++;
$isWord = true;
}
} else {
$isWord = false;
}
}
return $wordCount;
}

$string = "Hello, this is a test string.";


echo "Number of words: " . countWords($string);
?>

Output :

2
Enrollment No: 226480316029

b. Write a simple PHP program demonstrate use of various built-in


string function.

Program :

<?php

// Sample string
$string = "Hello, World!";

// String length
$length = strlen($string);
echo "String Length: $length <br>";

// Convert to uppercase
$uppercase = strtoupper($string);
echo "Uppercase: $uppercase <br>";

// Convert to lowercase
$lowercase = strtolower($string);
echo "Lowercase: $lowercase <br>";

2
Enrollment No: 226480316029

// Substring
$substring = substr($string, 0, 5); // Get the first 5 characters
echo "Substring: $substring <br>";

// String position
$position = strpos($string, "World"); // Find the position of "World"
echo "Position of 'World': $position <br>";

// String replacement
$newString = str_replace("Hello", "Hi", $string); // Replace "Hello" with "Hi"
echo "Replaced string: $newString <br>";

// String splitting
$parts = explode(" ", $string); // Split the string by space
echo "String parts: <pre>";
print_r($parts);
echo "</pre>";

// Joining array elements into a string


$newString = implode("-", $parts); // Join the array elements with "-"
echo "Joined string: $newString <br>";

?>

Output :

2
Enrollment No: 226480316029

7/ Write a simple PHP program to create PDF document buy using


graphics concepts.

Program :

Explanation -
Importing FPDF: require('fpdf.php'); includes the FPDF library.
Extending FPDF: We create a custom class PDF that extends the FPDF class to add custom
methods for drawing shapes.
Header and Footer: Overriding the Header and Footer methods to add a header and footer to the
PDF.
Custom Draw Functions: Methods DrawRectangle, DrawLine, and DrawEllipse for drawing
shapes.
Creating the PDF:
AddPage(): Adds a new page.
SetFont(): Sets the font for the text.
Cell(): Adds a cell with text.
Custom draw functions to draw shapes on the PDF.
Output the PDF: Output() generates and sends the PDF to the browser.
Note
FPDF does not support ellipse drawing out of the box. You might need to use additional libraries
or custom functions to draw ellipses. For this example, I have included a placeholder for an
ellipse drawing function.

Running the Script


Place the create_pdf.php file in your web server's root directory and navigate to it via your web
browser. This should generate and display a PDF document with the specified graphics.

Feel free to customize the script further to suit your specific requirements.

<?php
require('fpdf.php');

class PDF extends FPDF {


// Page header
function Header()
{
// Arial bold 15
$this->SetFont('Arial', 'B', 15);
// Move to the right
$this->Cell(80);
// Title
2
Enrollment No: 226480316029

$this->Cell(30, 10, 'Title', 0, 1, 'C');


// Line break
$this->Ln(20);
}

// Page footer
function Footer() {
// Position at 1.5 cm from bottom
$this->SetY(-15);
// Arial italic 8
$this->SetFont('Arial', 'I', 8);
// Page number
$this->Cell(0, 10, 'Page ' . $this->PageNo(), 0, 0, 'C');
}

// Custom function to draw a rectangle


function DrawRectangle($x, $y, $w, $h) {
$this->Rect($x, $y, $w, $h);
}

// Custom function to draw a line


function DrawLine($x1, $y1, $x2, $y2) {
$this->Line($x1, $y1, $x2, $y2);
}

// Custom function to draw an ellipse


function DrawEllipse($x, $y, $rx, $ry) {
$this->Ellipse($x, $y, $rx, $ry);
}
}

// Instantiation of inherited class


$pdf = new PDF();
$pdf->AddPage();

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

// Add a cell
$pdf->Cell(40, 10, 'Hello World!');

2
Enrollment No: 226480316029

// Draw a rectangle
$pdf->SetDrawColor(0, 0, 255); // Blue color
$pdf->DrawRectangle(50, 50, 100, 50);

// Draw a line
$pdf->SetDrawColor(255, 0, 0); // Red color
$pdf->DrawLine(10, 100, 200, 100);
// Draw an ellipse (note: FPDF does not support ellipse by default, so this part is illustrative)
$pdf->SetDrawColor(0, 255, 0); // Green color
// To draw an ellipse, you might need an extension or custom function

// Output the PDF


$pdf->Output();
?>

Output :

2
Enrollment No: 226480316029

8/ Design a web page using following form controls:


a. Text box,
b. Radio button,
c. Check box,
d. Buttons List box,
e. Combo box,
f. Hidden field box

Program :

Note – All the following controls included in the program.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>PHP Form Controls Example</title>
</head>
<body>
<h1>PHP Form Controls Example</h1>

<?php
// Define default values or variables
$textbox_value = '';
$radio_value = '';
$checkbox1_checked = '';
$checkbox2_checked = '';
$button_value = '';
$listbox_selected = '';
$combobox_selected = '';

// Process form submission


if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Retrieve values from form submission
$textbox_value = $_POST["textbox"];
$radio_value = $_POST["radio"];
$checkbox1_checked = isset($_POST["checkbox1"]) ? 'checked' : '';
2
Enrollment No: 226480316029

$checkbox2_checked = isset($_POST["checkbox2"]) ? 'checked' : '';


$button_value = $_POST["button"];
$listbox_selected = $_POST["listbox"];
$combobox_selected = $_POST["combobox"];
$hiddenfield_value = $_POST["hiddenfield"];

// Do something with the form data, such as processing, validation, or storing in a


database
// For demonstration purposes, we'll simply display the values
echo "<h2>Form Data:</h2>";
echo "Text Box: $textbox_value <br>";
echo "Radio Button: $radio_value <br>";
echo "Check Box 1: $checkbox1_checked <br>";
echo "Check Box 2: $checkbox2_checked <br>";
echo "Button: $button_value <br>";
echo "List Box: $listbox_selected <br>";
echo "Combo Box: $combobox_selected <br>";
echo "Hidden Field: $hiddenfield_value <br>";
}
?>

<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>"


method="POST">
<label for="textbox">Text Box:</label><br>
<input type="text" id="textbox" name="textbox" value="<?php echo $textbox_value;
?>"><br><br>

<label>Radio Buttons:</label><br>
<input type="radio" id="radio1" name="radio" value="option1" <?php if ($radio_value
=== 'option1') echo 'checked'; ?>>
<label for="radio1">Option 1</label><br>
<input type="radio" id="radio2" name="radio" value="option2" <?php if ($radio_value
=== 'option2') echo 'checked'; ?>>
<label for="radio2">Option 2</label><br><br>

<label>Check Boxes:</label><br>
<input type="checkbox" id="checkbox1" name="checkbox1" value="check1" <?php
echo $checkbox1_checked; ?>>
<label for="checkbox1">Check 1</label><br>
<input type="checkbox" id="checkbox2" name="checkbox2" value="check2" <?php
echo $checkbox2_checked; ?>>
<label for="checkbox2">Check 2</label><br><br>

3
Enrollment No: 226480316029

<label>Button List:</label><br>
<input type="button" id="button1" name="button" value="Button 1"><br>
<input type="button" id="button2" name="button" value="Button 2"><br><br>

<label for="listbox">List Box:</label><br>


<select id="listbox" name="listbox">
<option value="option1" <?php if ($listbox_selected === 'option1') echo 'selected';
?>>Option 1</option>
<option value="option2" <?php if ($listbox_selected === 'option2') echo 'selected';
?>>Option 2</option>
<option value="option3" <?php if ($listbox_selected === 'option3') echo 'selected';
?>>Option 3</option>
</select><br><br>

<label for="combobox">Combo Box:</label><br>


<select id="combobox" name="combobox">
<option value="option1" <?php if ($combobox_selected === 'option1') echo
'selected'; ?>>Option 1</option>
<option value="option2" <?php if ($combobox_selected === 'option2') echo
'selected'; ?>>Option 2</option>
<option value="option3" <?php if ($combobox_selected === 'option3') echo
'selected'; ?>>Option 3</option>
</select><br><br>

<input type="hidden" id="hiddenfield" name="hiddenfield" value="hiddenvalue">

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


</form>
</body>
</html>

Output :

3
Enrollment No: 226480316029

9/ Write simple PHP program to -


a. Set cookies and read it.
b. Demonstrate session management.

Program :

<?php

#program9a

// Set cookie
$cookie_name = "user";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day

// Read cookie
if(isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
} else {
echo "Cookie named '" . $cookie_name . "' is not set!";
}
?>
<br>

<?php

#program9b

3
Enrollment No: 226480316029

// Start the session


session_start();

// Set session variables


$_SESSION["username"] = "john_doe";
$_SESSION["email"] = "john@example.com";
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Session Management Demo</title>
</head>
<body>
<h1>Session Management Demo</h1>
<?php
// Echo session variables
echo "Username: " . $_SESSION["username"] . "<br>";
echo "Email: " . $_SESSION["email"] . "<br>";
?>

<!-- Unset and destroy the session -->


<?php
session_unset(); // Unset all session variables
session_destroy(); // Destroy the session
?>
</body>
</html>

Output :

3
Enrollment No: 226480316029

10/ Develop web page with data validation

a. Form validation is required to prevent web form abuse by


malicious users. Impropervalidation of form data is one of the
main causes of security vulnerabilities. It exposes your website
to attacks such as header injections, cross-site scripting, and
SQL injections.

Program :

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form Validation</title>
3
Enrollment No: 226480316029

<style>
.error {
color: red;
}
</style>
</head>
<body>
<h2>Contact Form</h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);

3
Enrollment No: 226480316029

$data = trim($data);
$data = stripslashes($data);
$data =
htmlspecialchars($data); return
$data;
}
?>

<div class="error">
<?php
echo $nameErr;
echo "<br>";
echo $emailErr;
echo "<br>";
echo $messageErr;
?>
</div>

<h3>Entered Data:</h3>
<p>Name: <?php echo $name; ?></p>
<p>Email: <?php echo $email; ?></p>
<p>Message: <?php echo $message; ?></p>
</body>
</html>

Output :

3
Enrollment No: 226480316029

3
Enrollment No: 226480316029

b. header injection attacks can be used to send email spam from your
web server.
Program :

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form Validation with Header Injection Protection</title>
<style>
.error {
color: red;
}
</style>
</head>
<body>
<h2>Contact Form</h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);
?>">
Name: <input type="text" name="name"><br>
Email: <input type="text" name="email"><br>
Message: <textarea name="message"></textarea><br>
<input type="submit" name="submit" value="Submit">
</form>

<?php
// Define variables and initialize with empty values
$name = $email = $message = "";
$nameErr = $emailErr = $messageErr = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Validate name
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// Check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/", $name)) {
$nameErr = "Only letters and white space allowed";
3
Enrollment No: 226480316029

}
}

// Validate email
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// Check if email address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}

// Validate message
if (empty($_POST["message"])) {
$messageErr = "Message is required";
} else {
$message = test_input($_POST["message"]);
}

// Check for header injection attempt


if (preg_match("/[\r\n]/", $name) || preg_match("/[\r\n]/", $email) || preg_match("/[\r\n]/",
$message)) {
die("Header injection detected. Please provide valid input.");
}
}

// Function to sanitize data


function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data =
htmlspecialchars($data); return
$data;
}
?>

<div class="error">
<?php
3
Enrollment No: 226480316029
echo $nameErr;
echo "<br>";

4
Enrollment No: 226480316029

echo $emailErr;
echo "<br>";
echo $messageErr;
?>
</div>

<h3>Entered Data:</h3>
<p>Name: <?php echo $name; ?></p>
<p>Email: <?php echo $email; ?></p>
<p>Message: <?php echo $message; ?></p>
</body>
</html>

Output :

c. cross-site scripting may allow an attacker to post any data to your site.

Program :

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

4
Enrollment No: 226480316029

<title>Form Validation with XSS Protection</title>


<style>
.error {
color: red;
}
</style>
</head>
<body>
<h2>Contact Form</h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);
?>">
Name: <input type="text" name="name"><br>
Email: <input type="text" name="email"><br>
Message: <textarea name="message"></textarea><br>
<input type="submit" name="submit" value="Submit">
</form>

<?php
// Define variables and initialize with empty values
$name = $email = $message = "";
$nameErr = $emailErr = $messageErr = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Validate name
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// Check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/", $name)) {
$nameErr = "Only letters and white space allowed";
}
}

// Validate email
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// Check if email address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
4
Enrollment No: 226480316029

$emailErr = "Invalid email format";


}
}

// Validate message
if (empty($_POST["message"])) {
$messageErr = "Message is required";
} else {
// Sanitize message to prevent XSS attacks
$message = htmlspecialchars($_POST["message"]);
}
}

// Function to sanitize data


function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data =
htmlspecialchars($data); return
$data;
}
?>

<div class="error">
<?php
echo $nameErr;
echo "<br>";
echo $emailErr;
echo "<br>";
echo $messageErr;
?>
</div>

<h3>Entered Data:</h3>
<p>Name: <?php echo $name; ?></p>
<p>Email: <?php echo $email; ?></p>
<p>Message: <?php echo $message; ?></p>
</body>
</html>

Output :
4
Enrollment No: 226480316029

d. SQL injection may corrupt your database backend .

Program :

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form Validation with SQL Injection Protection</title>
<style>
.error {
color: red;
}
</style>
</head>
<body>
<h2>Contact Form</h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);
?>">
Name: <input type="text" name="name"><br>
Email: <input type="text" name="email"><br>
Message: <textarea name="message"></textarea><br>
<input type="submit" name="submit" value="Submit">
</form>

<?php
// Define variables and initialize with empty values
$name = $email = $message = "";
$nameErr = $emailErr = $messageErr = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Validate name
if (empty($_POST["name"])) {
$nameErr = "Name is required";

4
Enrollment No: 226480316029

} else {
$name = test_input($_POST["name"]);
// Check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/", $name)) {
$nameErr = "Only letters and white space allowed";
}
}

// Validate email
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// Check if email address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}

// Validate message
if (empty($_POST["message"])) {
$messageErr = "Message is required";
} else {
$message = test_input($_POST["message"]);
}

// Prevent SQL injection


if (!empty($name) && !empty($email) && !empty($message)) {
// Database connection (replace with your own credentials)
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "your_database";

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

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

// Prepare and bind SQL statement using prepared statement


$stmt = $conn->prepare("INSERT INTO messages (name, email, message) VALUES (?,
?, ?)");
$stmt->bind_param("sss", $name, $email, $message);

// Execute SQL statement


$stmt->execute();

// Close connection
$stmt->close();
$conn->close();
}
}

// Function to sanitize data


function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data =
htmlspecialchars($data); return
$data;
}
?>

<div class="error">
<?php

4
Enrollment No: 226480316029

echo $nameErr;
echo "<br>";
echo $emailErr;
echo "<br>";
echo $messageErr;
?>
</div>

<h3>Entered Data:</h3>
<p>Name: <?php echo $name; ?></p>
<p>Email: <?php echo $email; ?></p>
<p>Message: <?php echo $message; ?></p>
</body>
</html>

Output :

4
Enrollment No: 226480316029

11/ Develop a simple application to -


a. Enter data into database.
b. Retrieve and present data from database

Program :
Note : save the php file as an insert_data.php …

<?php
// Database connection (replace with your own credentials)
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";

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

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

// Check if form is submitted


if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get data from the form
$name = $_POST["name"];
$email = $_POST["email"];

// SQL query to insert data into the database


$sql = "INSERT INTO users (name, email) VALUES ('$name', '$email')";

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


echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}

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

4
Enrollment No: 226480316029

?>

CREATE FORM USING HTML AND ATTACH FILE “ insert_data.php “

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Enter Data into Database</title>
</head>
<body>
<h2>Enter User Data</h2>
<form method="post" action="insert_data.php">
<label for="name">Name:</label><br>
<input type="text" id="name" name="name"><br>
<label for="email">Email:</label><br>
<input type="text" id="email" name="email"><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>

Output :

4
Enrollment No: 226480316029

B// Retrieve and present data from database

Program :

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>User Data</title>
<style>
table {
width: 100%;
border-collapse: collapse;
}
table, th, td {
border: 1px solid
black; padding: 8px;
text-align: left;
}

th {
background-color: #f2f2f2;
}
</style>
</head>
<body>
<h2>User Data</h2>
<table>
<tr>
<th>Name</th>
<th>Email</th>
</tr>

<?php
// Database connection
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";

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

5
Enrollment No: 226480316029

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

// SQL query to retrieve data


$sql = "SELECT name, email FROM users";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
// Output data of each row
while($row = $result->fetch_assoc())
{ echo "<tr>";
echo "<td>" . $row["name"] . "</td>";
echo "<td>" . $row["email"] .
"</td>"; echo "</tr>";
}
} else {
echo "<tr><td colspan='2'>0 results</td></tr>";
}

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

5
Enrollment No: 226480316029

12/ Develop a simple application to Update , Delete table data from database.
PHP MySQL Update Query .

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Delete Data</title>
</head>
<body>
<h2>Delete Data</h2>

<?php
// Database connection
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";

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

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

// Check if form is submitted


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

// SQL query to delete data


$sql = "DELETE FROM users WHERE id=$id";

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


echo "Record deleted
successfully";
} else {
echo "Error deleting record: " . $conn->error;
}
}

5
Enrollment No: 226480316029

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

<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?


>"> ID: <input type="text" name="id"><br>
<input type="submit" name="submit" value="Delete">
</form>
</body>
</html>

5
Enrollment No: 226480316029

13/ Write a PHP script for Swapping of Three numbers.


Program :

<?php
$a = 10;
$b = 20;
$c = 30;
echo "a = $a"."<br>"."b = $b"."<br>"."c = $c"."<br>";
$temp = $a;
$a = $b;
$b = $c;
$c = $temp;
echo "<b>After Swapping"."<br>"." a = $a"."<br>"."b = $b"."<br>"."c = $c"."<br><b>";
?>

Output :

5
Enrollment No: 226480316029

14/ Write a PHP script to find maximum number out of three given numbers.
Program :

<?php
$a = 10;
$b = 20;
$c = 30;
echo "a = $a b = $b c = $c"."<br>";
if ($a>$b)
{
if($a>$c)
{echo "a is the greatest";}
else
{echo "c is the greatest";}
}
else
{
if ($b>$c)
{echo "b is the greatest";}
else
{echo "c is the greatest";}
}
?>

5
Enrollment No: 226480316029

Output :

15/ Write a PHP script to Check the given number is Palindrome or Not.

Program :
<?php
$number = 121 ;
$temp = $number; //store it in a temp variable
$sum = 0;
//loop till the quotient is 0
while( $number > 0 )
{
$rem = $number % 10; //find reminder
$sum = $sum*10 + $rem ;
//echo $sum ."<br>";
$number = floor($number / 10); //find quotient. if 0 then loop again
}
//if the entered number and the $sum value matches then it is an Palindrome number
if( $temp == $sum )
{
echo "Palindrome Number";
}else
{
echo "Not Palindrome Number";
}

5
Enrollment No: 226480316029

?>

Output :

Palindrome Number

16/ Write a PHP script to print Fibonacci series.

Program :

<?ph
p
$coun
t=0;
$f1 =
0;
$f2 =
1;
echo
$f1."
".$f2.
" ";
while ($count < 10 )
{
$f3 = $f2 + $f1
; echo $f3." ";
$f1 = $f2 ;
$f2 = $f3 ;
$count = $count + 1;
}
?>

Output :

0 1 1 2 3 5 8 13 21 34 55 89

17/ Write a PHP script to check the given number is prime or not.

5
Enrollment No: 226480316029

Program :

<?php
$num =29;
$flag = false;
for( $i = 2; $i < $num; $i++ )
{
if( $num % $i == 0 )
{
$flag = true;
break;
}
}
if($flag == true)
{
echo "NOT Prime No";
}
else
{
echo "Prime No";
}
?>

Output :

Prime No

5
Enrollment No: 226480316029

18/ Write PHP Script to calculate total marks of student and display grade.

Program :

<?php
$subject1 = 75;
$subject2 = 50;
$subject3 = 50;
$subject4 = 50;
$subject5 = 93;

echo "Subject-1 : $subject1 <br> Subject-2 : $subject2 <br> Subject-3 : $subject3


<br> Subject-4 : $subject4 <br> Subject-5 : $subject5 <br>";
$Total = $subject1 + $subject2 + $subject3 + $subject4 + $subject5;
echo "Total Marks = <b> $Total </b><br />";
$Percentage = ($Total * 100) / 500;
echo "Percentage = <b> $Percentage </b><br />";

if($Percentage > 75)


{
echo "Grage = Distinction";
}
elseif($Percentage > 60)
{
echo "Grage = First Class";

5
Enrollment No: 226480316029

}
elseif($Percentage > 50)
{
echo "Grage = Second Class";
}
elseif($Percentage > 40)
{
echo "Grage = Third Class";}
else
{
echo "Fail";
}
?>

6
Enrollment No: 226480316029

OUTPUT:
Subject-1 : 75
Subject-2 : 50
Subject-3 : 50
Subject-4 : 50
Subject-5 : 93
Total Marks = 318
Percentage = 63.6
Grade = First
Class

6
Enrollment No: 226480316029

19-1.Write a PHP script to get type of variable using gettype().

Program :

<?php
$No = 5;
$Value = 13.5;
$Name = "Bipin Prajapati";
$VAR = true;
$MyArray = array(110, 45, "HELLO", 1.5, true);
echo $No . "<br/>" . $Value . "<br/>" . $Name . "<br/>" . $VAR .
"<br/>"; echo "<b> gettype(var) </b>"."<br>";
echo gettype($No) .
"<br/>";
echo gettype($Value).
"<br/>";
echo gettype($Name).
"<br/>";
echo gettype($VAR).
"<br/>";
echo gettype($MyArray).
"<br/>";
?>

Output :
5
13.5
Bipin Prajapati
1
gettype(var)
integer
double
string
boolean
array

6
Enrollment No: 226480316029

19-2. Write a PHP script to set type of variable using settype().

Program :

<?php
$Var1= "28Bipin"; // string
$Var3= "Bipin28"; // string
$Var4= "Bipin"; // string
$Var5 = 25;
$Var6 = 254.50;
settype($Var1, "integer"); // $Var1 is now 28
(integer) settype($Var3, "integer"); // $Var1 is now 0
(integer) settype($Var4, "integer"); // $Var1 is now 0
(integer) settype($Var5, "float");
settype($Var6, "double");
$Var2= true; // boolean
settype($Var2, "string"); // $Var2 is now "1" (string)
echo $Var1."<br/>";
echo $Var3."<br/>" ;
echo $Var4."<br/>" ;
echo $Var2."<br/>" ;
echo gettype($Var1)."<br/>";
echo gettype($Var3)."<br/>";
echo gettype($Var4)."<br/>";
echo gettype($Var5)."<br/>";
echo gettype($Var6)."<br/>";
echo gettype($Var2);
?>

6
Enrollment No: 226480316029

Output :

20 / A / Write PHP script to demonstrate use of string function- chr() and ord().

Program :

<html>
<body>
<h2> chr() </h2>
<?php
echo chr(77) . "<br>"; // M
echo chr(102) . "<br>"; // f
echo chr(99) . "<br>"; // c
echo chr(46) . "<br>"; // .
echo chr(52) . "<br>"; // Decimal value // 4
echo chr(052) . "<br>"; // Octal value // *
echo chr(0x52) . "<br>"; // Hex value // R
?>
<h2> ord() </h2>
<?php
echo ord("h") . "<br>"; // 104
echo ord("H") . "<br>"; // 72
echo ord("Hello") . "<br>"; // 72

6
Enrollment No: 226480316029

echo ord("99") . "<br>"; // 57

6
Enrollment No: 226480316029

echo ord("Bipin") . "<br>"; // 66


?>
</body>
</html>

Output :

chr()
M
f
c
.
4
*
R
ord()
104
72
72
57
66

20 / B / Write PHP script to demonstrate use of string function-


strtolower () & strtoupper () & strlen().

Program :

<h2>string strtolower(string $str) </h2>


<?php
echo strtolower("hello") . "<br>";
echo strtolower("HEllo") . "<br>";
echo strtolower("HeLLO") . "<br>";
$var = "nbp piludara";
echo strtolower($var) . "<br>";
?>
<h2>string strtoupper(string $str)</h2>
<?php
echo strtoupper("h") . "<br>";
echo strtoupper("H") . "<br>";
echo strtoupper("Hello") . "<br>";

6
Enrollment No: 226480316029

echo strtoupper("Mr. Bipin Prajapati") .


"<br>"; echo strtoupper("Bipin") . "<br>"; //
?>
<h2>int strlen(string $str)</h2>
<?php
$var = "nbp piludara";
echo strlen($var) .
"<br>";
echo strlen("Hello") . "<br>";
echo strlen("Mr. Bipin Prajapati") .
"<br>"; echo strlen("Bipin") . "<br>"; //

?>

Output :

string strtolower(string $str)


hello
hello
hello
nbp piludara

string strtoupper(string $str)


H
H
HELLO
MR. BIPIN
PRAJAPATI BIPIN

int strlen(string $str)


12
5
19
5

6
Enrollment No: 226480316029

20 / C / Write PHP script to demonstrate use of string function-


ltrim() & rtrim() & trim().

Program :

<html>
<head>
<title>
trim() Function!
</title>
</head>
<body>
<pre><h2> string trim(string $str [,string $charlist]) </h2></pre>
<?php
echo strlen(" Hello World ")."<br>"; // 15
echo strlen(ltrim(" Hello World "))."<br>"; //14
echo ltrim(" NBP! ")."<br>";
echo ltrim("Hello World.........! ","H")."<br>";
echo "<br>";
echo strlen(" Hello World ")."<br>";
echo strlen(rtrim(" Hello World "))."<br>";
echo "<br>";
echo strlen(" Hello World ")."<br>";
echo strlen(trim(" Hello World "))."<br>";
?>
</body>
</html>

Output :

string trim(string $str [,string $charlist])


15
14
NBP!
ello World..........!
17
14

17
11

6
Enrollment No: 226480316029

20 / D / Write PHP script to demonstrate use of string function- substr() .


Program :

<html>
<head>
<title>
String Function - substr()
</title>
</head>
<body>
<pre><h1> string substr(string $string , int start [,int $length]) <h1></pre>
<h1>abcdef</h1>
<b> If Start is Non Negative(POSITIVE), the returned string will start at the strat'th
position in string, start form 0. </b> <br/> <br/>
<?php
echo "Substring with Positive Start: " . substr("abcdef",2) . "<br/>";
?> <br/>
<b> If Start is Negative, the returned string will start at the strat'th character from the
end of string</b> <br/> <br/>
<?php
echo "Substring with negative Start: " . substr("abcdef",-2) . "<br/>";
?><br/>
<b> If string is less than or equal to start chararcters long, FALSE will returned </b>
<br/><br/>
<?php
echo " Start is >= string : " . substr("abcdef",7) . "<br/>";
?>
<br/>
</body>
</html>

Output :

6
Enrollment No: 226480316029

7
Enrollment No: 226480316029

20 / E / Write PHP script to demonstrate use of string function- substr().

Program :

<html>
<head>
<title>
String Function
</title>
</head>
<body>
<h1>adcdef</h1> <h3> if LENGTH is GIVEN </h3>
<b> If LENGTH is Non Negative(POSITIVE), the returned string will start at the strat'th position in
string, and count the length beginning from start </b> <br/> <br/>
<?php
echo "Substring :" . substr("abcdef",2,2) . "<br/>";
?> <br/>
<?php
echo "Substring :" . substr("NBPATELPILUDARA",2,4) . "<br/>";
?> <br/>
<?php
echo "Substring :" . substr("abcdef",-3,2) . "<br/>";
?> <br/>
<?php
echo "Substring :" . substr("NBPATELPILUDARA",-5,2) . "<br/>";
?> <br/>
<b> If LENGTH is Negative, the returned string will start at the strat'th position in string, and
REmove(ommited) character from end of string </b> <br/> <br/>
<?php
echo "Substring :" . substr("abcdef",2,-2) . "<br/>";
?> <br/>
<?php
echo "Substring :" . substr("NBPATELPILUDARA",2,-4) . "<br/>";
?> <br/>
<?php
echo "Substring :" . substr("abcdef",-2,-2) . "<br/>";
?> <br/>
<?php
echo "Substring : " . substr("NBPATELPILUDARA",-2,-4) . "<br/>";

7
Enrollment No: 226480316029

?> <br/>
<?php
echo "Substring :" . substr("NBPATELPILUDARA",-4,-2) . "<br/>";
?> <br/>
<?php
echo "Substring :" . substr("NBPATELPILUDARA",-5,-4) . "<br/>";
?> <br/>
</body>
</html>

Output :

7
Enrollment No: 226480316029

20 / F / Write PHP script to demonstrate use of string function- strcmp ().


Program :

<html>
<head>
<title>
String Function - strcmp
</title>
</head>
<body> <h1> int strcmp(string $str1 , string $str1 )</h1>
<h2> 1. if str1 < str2 &nbsp => return < 0 </h2>
<h2> 2. if str1 > str2 &nbsp => return > 0 </h2>
<h2> 3. if str1 = str2 &nbsp => return = 0 </h2> <br/>
<?php
$str1 = 'a' ;
$str2 = 'b';
$string1 = 'b';
$string2 = 'a';
$str3 = 'Bipin' ;
$str4 = 'bipin';
$str5 = 'bipin' ;
$str6 = 'Bipin';
$str7 = 'Bipin' ;
$str8 = 'Bipin';
echo strcmp($str1,$str2) . "<br/>";
echo strcmp($string1,$string2) .
"<br/>"; echo strcmp($str3,$str4) .
"<br/>";
echo strcmp($str5,$str6) .
"<br/>"; echo strcmp($str7,$str8) .
"<br/>";
?>
</body>
</html>

Output :

7
Enrollment No:

7
Enrollment No:

20 / G / Write PHP script to demonstrate use of string function- strcasecmp


().

Program :

<html>
<head>
<title>
String Function - strcasecmp
</title>
<Head>
<body> <h1> int strcasecmp(string $str1 , string $str1 )</h1>
<h2> 1. if str1 < str2 &nbsp => return < 0 </h2>
<h2> 2. if str1 > str2 &nbsp => return > 0 </h2>
<h2> 3. if str1 = str2 &nbsp => return = 0 </h2> <br/>
<?php
$str1 = 'a' ;
$str2 = 'b';
$string1 = 'b';
$string2 = 'a';
$str3 = 'Bipin' ;
$str4 = 'bipin';
$str5 = 'bipin' ;
$str6 = 'Bipin';
$str7 = 'Bipin' ;
$str8 = 'Bipin';
echo strcasecmp($str1,$str2) . "<br/>";
echo
strcasecmp($string1,$string
2) . "<br/>";echo
strcasecmp($str3,$str4) .
"<br/>";
echo
strcasecmp($str5,$str
6) . "<br/>";echo
strcasecmp($str7,$str
8) . "<br/>";
?>
</body>
<

/
7
Enrollment No:

>

7
Enrollment No:

7
Enrollment No:

20 / H / Write PHP script to demonstrate use of string function-


strpos().

Program :

<html>
<head>
<title>
String Function - strpos
</title>
<Head>
<body>
<h1> int strpos(string $str1 , Mixed $Searchstring [,int offset = 0] )</h1>
<?php
echo strpos("Hello How are

7
Enrollment No:

u","u") . "<br/>";echo
strpos("Hello How are u","y")
. "<br/>";
echo strpos("Hello How are u a man", "65") . "<br/>";
echo strpos("Hello How are u a man",
"How ") . "<br/>";echo strpos("Hello How
are u","e",2) . "<br/>";
echo strpos("Hello How are u","H",2) . "<br/>";
?>
</body>
<

html
>O
u

7
Enrollment No:

20 / I / Write PHP script to demonstrate use of string function- -


str_replace ().

Program :

<html>
<head>
<title>
String Function - str_replace()
</title>
<Head>
<body>
<pre>
<h1> str_replace(find , replace , string , count)</h1>
</pre>
<?php
echo str_replace("Hello","Hi","Hello How are u") . "<br/>";
$myarray =
array("blue","black","green","yellow","wh
ite");echo "<pre>";
print_r(str_replace("black","red",$myarra
y,$i));
echo "<pre>";echo "$i";
?>
</body>
<

8
Enrollment No:

>

8
Enrollment No:

20 / K / Write PHP script to demonstrate use of string function-

8
Enrollment No:

strrev ().

Program :

<html>
<head>
<title>
String Function - strrev()
</title>
<Head>
<body>
<pre>
<h1> string strrev(string $string)</h1>
</pre>
<?php
echo strrev("HEllo PHP")."<br>";
echo strrev("Programming")."<br>";
$var1 = "Naman" ;
$var2 = strrev($var1);
if(strcasecmp($var1, $var2)==0)
{echo "Its Palindrome string";
}
else
{
echo "Its NOT Palindrome string";
}
?>
</body>
</html>

Output :

8
Enrollment No:

21/A/ Write PHP script to demonstrate use of date/time functions

- date() .

Program :

<html>
<head>
<title> String Function - Date() </title>
</head>
<body>
<H2> string date (string $format [, int $timestamp]) </h2>
<br/>
<?php
echo date("d/m/y")."<br/>" ;
echo date("d.m.y")."<br/>" ;
echo date("Y/m/d")."<br/>" ;
echo date("D/M/Y")."<br/>" ;
echo date("l-F-y")."<br/>" ;
echo date("d/m/y h:i:s a")."<br/>" ;
echo date("d/m/y h:i:s A")."<br/>" ;
echo date("d/m/y G :i:s a")."<br/>" ;
?>
</body>
</html>
Output :

21/B/ Write PHP script to demonstrate use of date/time functions -


getDate().

8
Enrollment No:

Program :
<html>
<head>
<title> String Function - getDate() </title>
</head>
<body>
<H2> array getdate ([ int $timestamp = time()s])</h2> <br/>
<?php
echo
getdate()."<br/
>" ; // error
echo "<pre>";
print_r(getdate()) . "<br/>" ;
?>
</body>
<

>

u
8
Enrollment No:

8
Enrollment No:

21/C/ Write PHP script to demonstrate use of date/time functions


– Setdate ().

Program :

<html>
<head>
<title> String Function - Setdate() </title>
</head>
<body>
<H2> public DateTime datetime : : setdate( int $year, int $month, int $day )
</h2> <br/>
<h2> Reset the current date of the datetime object to different date .</h2>
<br/>
8
Enrollment No:

<?php
$Date = new DateTime();
$Date-
>setDate(201
0, 3, 11);
echo $Date -
> format('Y-
m-d');
?>
</body>
<

>

8
Enrollment No:

8
Enrollment No:

21/D/ Write PHP script to demonstrate use of date/time functions


– mktime().

Program :

<html>
<head>
<title> String Function - mktime()</title>
</head>
<body>
<H2>mktime(hour,min,sec,month,day,year,dst) (Optional parameter)</h2>
<br/>
<h2> Get the UNIX timestamp for a date.</h2> <br/>
<?php
echo mktime(1,1,1,1,1,2001) . "<br/>";
echo mktime(0,0,0,0,0,2001). "<br/>";
echo mktime(0,0,0,0,0,2012). "<br/>";
?>
<body>
<

9
Enrollment No:

>

9
Enrollment No:

21/E/ Write PHP script to demonstrate use of date/time


functions – time() &checkdate().

Program :

<html>
<head>
<title> String Function - time() and checkdate(month, day, year)</title>
</head>
<body>
<?php
echo time()."<br/>" ;
$nextWeek = time() + (7 * 24 * 60 * 60);
// 7 days; 24 hours;
60 mins; 60 secs
echo 'Now: '.
date('Y-m-d') ."\
n";
echo 'Next Week: '. date('Y-m-d', $nextWeek) ."\n";
// or using strtotime():
echo 'Next Week: '. date('Y-m-d', strtotime('+1 week')) ."\n";

var_dump(checkdate(12, 05, 2012)) ."<br/>";


var_dump(checkdate(32, 10, 2014)) ."<br/>";
var_dump(checkdate(12, 32, 2012)) ."<br/>";
var_dump(checkdate(2, 29, 2001)) ."<br/>";
?>
</body>
</html>

9
Enrollment No:

Output :

9
Enrollment No:

22/A/ Write PHP Script to demonstrate use of Indexed/Numeric


arrays and for FOR EACH loop execution.

Program :

<?php
// NUMERIC / INDEXED ARRAY
// FIRST METHOD
$numbers = array(1,2,3,4,5);
foreach ($numbers as $value)
{ echo "Value is $value"."<br>";
}
$myArray = array("NBP", "MPC", "MEC", "SPIT", "SDP");
foreach ($myArray as $value)
{ echo "College Name is $value"."<br>";
}
// SECOND METHOD
$Friends[0] = "mohan valmiki";
$Friends[1] = "mohit rana";
$Friends[2] = "bhrumin patel";
$Friends[3] = "Akshay shelke";
$Friends[4] = "davendar”;
foreach ($Friends as $value)
{ echo "Friends is $value"."<br>";
}
echo "<br>";
print_r($numbers);
echo "<br>";
print_r($Friends);
?>

9
Enrollment No:

Output :

9
Enrollment No:

22/B/ Write PHP Script to demonstrate use of associative arrays


and for FOR EACH loop execution.
Program :

<html>
<head>
<title>Array Example : ASSOCIATIVE ARRAY</title>
</head>
<body>
<?php
$myArray = array( 'it'=>'Samir',
'me'=>'mohan',
'ee'=>'bhrumin',
'ec'=>'mohit',
'civil'=>'akshay',
'gen'=>'davendar'
);
echo "<h1>" . "List of Head of N. B. Patel Polytechnic" . "</h1>" . "</br>";
echo "<h2>";
echo "Head of Computer Engineering / Information Technology : " .
$myArray['it'] . "</br>";
echo "Head of Mechanical Engineering : " . $myArray['me'] . "</br>";
echo "Head of Electrical Engineering : " . $myArray['ee'] . "</br>";
echo "Head of Electrical & Communications : " . $myArray['ec'] . "</br>";
echo "Head of Civil Engineering : " . $myArray['civil'] . "</br>";
echo "Head of General Department : " . $myArray['gen'] . "</br>";
echo "</h2>";
foreach ($myArray as $key => $value) {
echo "Key is $key value is $value"."<br>";
}
echo "<br>";
echo "<br>";
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
foreach($age as $x=>$x_value) {
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}

9
Enrollment No:

echo "<pre>";
print_r($myArray);
?>
</body>
</html>

Output :

9
Enrollment No:

22/C/ Write PHP Script to demonstrate use of mixed array


indexed +associative arrays and print using prinr_r() function.

Program :

<?php
$myArray =
array('Bipin',28,"Degree"=>"MTECH",'City'=>'Mehsana',"Mehsana");
echo "</h2>";
echo "<pre>";
print_r($myArray);
?>

Output :

9
Enrollment No:

22/D/
i. Write PHP Script to demonstrate use
of multidimensional arrays .
ii. Write PHP Script to demonstrate sorting arrays .

Program (i) :

<html>
<head>
<title>Multidimensional Array Example</title>
</head>
<body>
<?php
$marks = array(
'mohan' => array (
'Maths'=>45,
'Physics'=>40,
'Chemistry'=>42,
),
'bhrumin' => array (
'Maths'=>40,
'Physics'=>40,
'Chemistry'=>40,
),
'mohit' => array (
'Maths'=>50,
'Physics'=>45,
'Chemistry'=>48,
)
);
echo "Marks for mohan in Maths : ";
echo $marks['mohan']['Maths']."</br>";
echo "Marks for bhrumin in Physics : ";
echo $marks['bhrumin']['Physics']."</br>";
echo "Marks for mohit in Chemistry : ";
echo $marks['mohit']['Chemistry']."</br>";
echo "<pre>";
print_r($marks);
?>
</body>
</html>
9
Enrollment No:

Output :

Program (ii) :

<html>
<head>
<title>
Array Function - SORT()
</title>
</head>
<body>
<h1> bool sort (array $array [,int $sort_flags = SORT_REGULR])</h1><br/>
<h3>Sort the elements from Lowest to Highest Position </h3>
<?php
$foo = array("bob","fred","Marry","mark","Alen" ,"arya");
sort($foo);
print_r($foo);
echo "<br/>" ; echo "<br/>";
$Batsman = array('Sachin','Sehwag','Dravid','Dhoni','Virat','Gambhir');
sort($Batsman);
print_r($Batsman);
echo "<br/>";
?>
</body>

1
Enrollment No:

</html>

Output :

You might also like