PHP Lab Manual Odd Sem Bca
PHP Lab Manual Odd Sem Bca
Department: BCA
Subject Name: Web Technology Practical
Subject Code : 320C51
Class: III BCA A
Staff:S.Sangeetha
Course Outcomes: (for students: To know what they are going to learn)
1. On the completion of this laboratory course the students ought to
2. Obtain knowledge and develop application programs using Python.
3. Create dynamic Web applications such as content management, user registration, and
ecommerce using PHP and to understand the ability to post and publish a PHP website.
4. Develop a MySQL database and establish connectivity using MySQL
PAGE
S NO. DATE PROGRAM NO. SIGNATURE
Aim:
To write a php program to find the row and column sum of a matrix.
Algorithm:
Step 1: Start
Step 8: Stop.
// 1.PHP program to find the sum of each row and column of a matrix
<?php
// Driver code
$arr= array_fill(0, $m, array_fill(0, $n, NULL));
?>
Output:
Result:
Aim:
To write a php program to find out the sum of first n prime numbers.
Algorithm:
Step 1: start
Step 6: stop.
2. Sum of First n prime numbers
<?php
$max = 105000;
$arr = new SplFixedArray($max + 1); for ($i = 2; $i <= $max; $i++) {
$arr[$i] = 1;
}
for ($i = 2, $len = sqrt($max); $i <= $len; $i++) { if (!$arr[$i]) {
continue;
}
for ($j = $i, $len2 = $max / $i; $j <= $len2; $j++) {
$arr[$i * $j] = 0;
}
}
while (($line = trim(fgets(STDIN))) !== '0') {
$n = (int)$line;
$result = 0;
$cnt = 0;
for ($i = 2; $i <= $max; $i++) { if ($cnt === $n) {
break;
} elseif ($arr[$i]) {
$result += $i;
$cnt++;
}
}
echo "Sum of first ".$n." prime numbers:"; echo $result, PHP_EOL;
}
?>
Output:
Result:
Aim:
To write a php program to find a valid email address from the given list of email address.
Algorithm:
Step 1: Start
Step 3: Filter the trimmed email into its components (user id, server, domain) and invalid it.
<?php
function valid_email($email)
{
$result = trim($email);
if (filter_var($result,FILTER_VALIDATE_EMAIL))
{
return "Valid Email";
}
else
{
echo "Invalid Email";
}
}
echo "abc@example.com\n";
echo valid_email("abc@example.com")."\n"; echo "abc#example.com\n";
echo valid_email("abc#example.com")."\n";
?>
Output:
Result:
Aim:
Algorithm:
Step 1: Start
Step 2: Input the number which in words write elements as word separator.
Step 3: Letter each word in the input using the explode function in php.
Step 5: Using switch construct print the digit corresponding to the value obtained in step 4.
Step 7: Stop.
//4.program to convert a number written in words to digit
<?php
function word_digit($word) {
$warr = explode(';',$word);
$result = ''; foreach($warr as $value){
switch(trim($value)){ case 'zero':
$result .= '0'; break;
case 'one':
$result .= '1'; break;
case 'two':
$result .= '2'; break;
case 'three':
$result .= '3'; break;
case 'four':
$result .= '4'; break;
case 'five':
$result .= '5'; break;
case 'six':
$result .= '6'; break;
case 'seven':
$result .= '7'; break;
case 'eight':
$result .= '8'; break;
case 'nine':
$result .= '9'; break;
}
}
return $result;
}
Result:
Aim:
Algorithm:
Step 1: Start
Step 4: Now display the current time to check for the delay established.
Step 5: stop.
//5. delay the program execution for the given number of seconds
<?php
// current time
echo date('h:i:s') . "\n";
// sleep for 5 seconds sleep(5);
// wake up
echo date('h:i:s')."\n";
?>
Output:
Result:
Aim:
To write a php program to change the colour of the first character of the word.
Algorithm:
Step 1: Start.
Step 3: Search the first character from the input text using preg_replace function.
Step 6: Stop.
//6. PHP script, which changes the colour of the first character of a word
<?php
// Text to replace
$text = "Geeks For Geeks";
Output:
Result:
Aim:
Algorithm:
Step 1: Start
Step 3: Initialize i to 1
Step 5: Increment i by 1
Step 7: Stop.
// 7.HTML program to print multiplication table- (mul.html)
<!DOCTYPE html>
<html>
<body>
<center>
<h1><b>
Program to print multiplication<br> table of any number in PHP
</b></h1>
<form method="POST" action="mul.php"> Enter a number:
<input type="text" name="number">
<input type="Submit"
value="Get Multiplication Table">
</body>
</html>
</form>
</center>
Result:
Aim:
Algorithm:
Step 1: Start.
Step 6: Decrement x by 1.
Step 9: Stop.
// 8. Factorial of given number
<?php
$num = 4;
$factorial = 1;
for ($x=$num; $x>=1; $x--)
{
$factorial = $factorial * $x;
}
echo "Factorial of $num is $factorial";
?>
Output:
Result:
Aim:
Algorithm:
Step 1: Start
Step 3: Open the given file and get its content using file_get_contents function.
Step 5: Append a new content using file_put_contents from its current location.
Step 7: Stop.
// 9 . Reading the file,reversing its content and storing into new file
<?php
$file = 'sample.txt';
$file1='sample1.txt';
Output:
Result:
Aim:
Algorithm:
Step 1: Start
Step 2: Get the directory name & extension of file to be changed through a webpage.
Step 4: Scan the files under the given directory and collect it in an array.
Step 5: Each files in the array, do the steps 6 to 9, if it is not root directory.
Step 8: Find the sub str of the new file starting from first character until ‘.’.
Step 9: Append it with extension to be replaced print the new file name.
<html>
<body>
<h2>Change the Extension of all the files in a directory</h2>
<br>
<form method ="post action="<?php echo $_SERVER['PHP_SELF'];
?>">
Enter the Directory (. for current directory)<input type="text" name="dir" size="50"><br>
Enter the new file extension<input type="text" name="ext" size="20"><br>
<input type="submit" name="submit" value="Submit Form"><br>
</form>
<?php
if (isset($_POST['submit']) && trim($_POST['dir']) != '')
{
$dirname = $_POST['dir'];
$newextension = $_POST['ext'];
$files = scandir($dirname); foreach($files as $file)
{
if(trim($dirname) != ".")
$newfile = $dirname."/".$file; else "<br>";
if(pathinfo ($newfile, PATHINFO_EXTENSION)=="text")
{
echo "<br>Old File:".$newfile;
$file_Woext = substr($newfile, 0,strrpos($newfile, ".")); rename($newfile,$file_Woext.".".$newextension);
echo "<br>New File:".$file_Woext.".".$newextension;
}
}
}
if(isset($_POST['submit']) && trim($_POST['dir']) == '')
{
Result:
Aim:
To write a php program to sort the files in the current directory by its last modification
time.
Algorithm:
Step 1: Start.
Step 4: Get the sub directory and files using glob function in an array by its last modification
time.
Step 7: Stop.
//11. Write a PHP script to read the current directory and //return a file list sorted by last modification
time. (using filemtime())
<html>
<body>
<h2>List the files in the given directory based on the Modification time</h2>
<br>
<form method="post action="<?php echo $_SERVER['PHP_SELF'];?>"> Enter the Directory (.for current
directory)<input type="text" name="dir' size="50"><br>
<input type="submit" name="submit" value="Submit Form"><br>
</form>
<?php
if(isset($_POST['submit'])&& trim($_POST['dir']) !='')
{
$dirname = $_POST['dir']; if($dirname == ".")
{
$dirpath = '*';
}
else
{
$dirpath = $dirname.'/*';
}
foreach (glob($dirpath) as $filename)
{
$filesarrray[filemtime($filename)]=basename($filename);
}
echo "<br>Original Files:<br>"; foreach($filesarray as $modificationtime => $file)
{
Result:
DATABASE CONNECTIVITY
Aim:
To write a php program to connect to a mysql database, insert, view, update & delete the records
from the data base.
Algorithm:
Step 1: Start.
Step 4: Create webpage to display to options for inserting, viewing, editing, deleting the records
from the marksheet table.
Step 5: Write coding for inserting, viewing, editing & deleting records using mysqlite extension
commands in php.
Step 6: Stop.
//12. Students marksheet
// dashboard.php
<?php
//require('db.php');
//include("auth.php"); include("db.php");
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Dashboard - Secured Page</title>
<link rel="stylesheet" href="css/style.css" />
</head>
<body>
<div class="form">
<p>Welcome to Dashboard.</p>
<p><a href="index.php">Home</a><p>
<p><a href="insert.php">Insert New Record</a></p>
<p><a href="view.php">View Records</a><p>
<p><a href="logout.php">Logout</a></p>
</div>
</body>
</html>
// db.php
<?php
$servername = "localhost";
$username = "system";
$password = "tnc";
$db="studentmarks";
// Create connection
$con = new mysqli($servername, $username, $password,$db);
// Check connection
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
echo "Connected successfully to the database ---> ".$db;
?>
//insert.php
<?php require('db.php');
//include("auth.php");
$status = "";
if(isset($_POST['new']) && $_POST['new']==1){
$trn_date = date("Y-m-d H:i:s");
$regno =$_REQUEST['regno'];
$name =$_REQUEST['name'];
$sem = $_REQUEST['sem'];
$web = $_REQUEST['web'];
$weblab= $_REQUEST['weblab'];
$physics = $_REQUEST['physics'];
$submittedby = $_SESSION["username"];
$ins_query="insert into marksheet (`regno`,`name`,`sem`,`web`,`weblab`,`physics`) values
('$regno','$name','$sem','$web','$weblab','$physics')"; mysqli_query($con,$ins_query) or
die(mysql_error());
$status = "New Record Inserted Successfully.
</br></br><a href='view.php'>View Inserted Record</a>";
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Insert New Record</title>
<link rel="stylesheet" href="css/style.css" />
</head>
<body>
<div class="form">
<p><a href="dashboard.php">Dashboard</a>
| <a href="view.php">View Records</a>
| <a href="logout.php">Logout</a></p>
<div>
<h1>Insert New Record</h1>
<form name="form" method="post" action="">
<input type="hidden" name="new" value="1" />
<p><input type="text" name="regno" placeholder="Enter regno" required /></p>
<p><input type="text" name="name" placeholder="Enter name" required
/></p>
<p><input type="text" name="sem" placeholder="Enter sem" required
/></p>
<p><input type="text" name="web" placeholder="Enter web" required
/></p>
<p><input type="text" name="weblab" placeholder="Enter weblab" required /></p>
<p><input type="text" name="physics" placeholder="Enter phy marks" required /></p>
<p><input name="submit" type="submit" value="Submit" /></p>
</form>
<p style="color:#FF0000;"><?php echo $status; ?></p>
</div>
</div>
</body>
</html>
//view.php
<?php require('db.php');
//include("auth.php");
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>View Records</title>
<link rel="stylesheet" href="css/style.css" />
</head>
<body>
<div class="form">
<p><a href="index.php">Home</a>
| <a href="insert.php">Insert New Record</a>
| <a href="logout.php">Logout</a></p>
<h2>View Records</h2>
<table width="100%" border="1" style="border-collapse:collapse;">
<thead>
<tr>
<th><strong>Reg No</strong></th>
<th><strong>Name</strong></th>
<th><strong>Sem</strong></th>
<th><strong>Web</strong></th>
<th><strong>Web Lab</strong></th>
<th><strong>Physics</strong></th>
<th><strong>Edit</strong></th>
<th><strong>Delete</strong></th>
</tr>
</thead>
<tbody>
<?php
$count=1;
$sel_query="Select * from marksheet ORDER BY regno desc;";
$result = mysqli_query($con,$sel_query); while($row = mysqli_fetch_assoc($result)) { ?>
//edit.php
<?php require('db.php');
//include("auth.php");
$regno=$_REQUEST['regno'];
$query = "SELECT * from marksheet where regno='".$regno."'";
$result = mysqli_query($con, $query) or die ( mysqli_error());
$row = mysqli_fetch_assoc($result);
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Update Record</title>
<link rel="stylesheet" href="css/style.css" />
</head>
<body>
<div class="form">
<p><a href="dashboard.php">Dashboard</a>
| <a href="insert.php">Insert New Record</a>
| <a href="logout.php">Logout</a></p>
<h1>Update Record</h1>
<?php
$status = "";
if(isset($_POST['new']) && $_POST['new']==1)
{
$trn_date = date("Y-m-d H:i:s");
$regno=$_REQUEST['regno'];
$name =$_REQUEST['name'];
$sem =$_REQUEST['sem'];
$web =$_REQUEST['web'];
$weblab =$_REQUEST['weblab'];
$physics =$_REQUEST['physics'];
//$submittedby = $_SESSION["username"];
$update="update marksheet set regno='".$regno."',name='".$name."', sem='".$sem."', web='".$web."',
weblab='".$weblab."',physics='".$physics."' where regno='".$regno."'"; mysqli_query($con, $update) or
die(mysqli_error());
$status = "Record Updated Successfully. </br></br>
<a href='view.php'>View Updated Record</a>"; echo '<p style="color:#FF0000;">'.$status.'</p>';
}else {
?>
<div>
<form name="form" method="post" action="">
<input type="hidden" name="new" value="1" />
<p><input type="text" name="regno" placeholder="Enter Regno" required value="<?php echo
$row['regno'];?>" /></p>
<p><input type="text" name="name" placeholder="Enter name" required value="<?php echo
$row['name'];?>" /></p>
<p><input type="text" name="sem" placeholder="Enter Sem" required value="<?php echo
$row['sem'];?>" /></p>
Output:
Result:
Aim:
To write a php program to collect all e-mail address from the given xml file.
Algorithm:
Step 1: Start
Step 2: Create an xml file having employee details including email address of an organization.
Step 3: Local the xml file into php using simple xml_load_file function.
Step 4: If not, generate error message and stop called error_name and email address elements
from the loaded xml file into an array.
Step 6: Stop.
//13. From a XML document (email.xml), write a program to retrieve and print all the e-mail addresses
from the document using XML
//email.xml
<?xml version='1.0'?>
<employees>
<employee >
<empid>101</empid>
<name>John</name>
<email>john@example.com</email>
<address>
<street>3201 Glendale Avenue</street>
<city>Los Angeles</city>
<state>CA</state>
</address>
</employee>
<employee >
<empid>102</empid>
<name>Mike</name>
<email>mike@example.com</email>
<address>
<street>781 Stroop Hill Road</street>
<city>Duluth</city>
<state>GA</state>
</address>
</employee>
</employees>
//email.php
<?php
$xml=simplexml_load_file("email.xml") or die ("Unable to load XML"); echo "There are ".count ($xml-
>employee)." employees working in this company.";
echo "<br>Employee ID and their E-Mail addresses are:"; foreach ($xml->employee as $emp)
{
echo "<br>". $emp->empid; echo "-". $emp->email;
}
?>
output:
Result:
Aim:
To write a php program to retrieving the text value ‘john’ using the dom from the xml file
in 3 different methods.
Algorithm:
Step 1: Start.
Step 3: Load the john xml file into the dom object.
Step 4: Using the tree navigation methods of node method collect the value of ‘john’ by
processing the node one by one and print it.
Step 5: Using the get elements by tag name method retrieve the ‘john’ value and print it.
Step 6: Using the “get elements by tag name” method, retrieve john value using it parent tag.
Step 7: Stop.
//14. From a XML document (tree.xml), suggest three different ways to retrieve the text value 'John'
using the DOM:
//tree.xml
<?xml version='1.0'?>
<tree>
<person type="grandpa" />
<person type="grandma" />
<children>
<person type="pa" />
<person type="ma" />
<children>
<person type="bro">
<name>John</name>
</person>
<person type="sis">
<name>Jane</name>
</person>
</children>
</children>
</tree>
//tree.php
<?php
// initialize new DOMDocument
$doc = new DOMDocument();
// disable whitespace-only text nodes
$doc->preserveWhiteSpace = false;
// read XML file
$doc->load('tree.xml');
// output: 'John'
echo $doc->firstChild->childNodes->item(2)->childNodes
->item(2)->childNodes->item(0)->childNodes->item(0)
->childNodes->item(0)->nodeValue;
// output: 'John'
echo $doc->getElementsByTagName('name')->item(0)->nodeValue;
// output: 'John'
echo $doc->getElementsByTagName('person')->item(4)
->childNodes->item(0)->nodeValue;
?>
Output:
Result:
Aim:
To write a php program to connect to a mysql database of students and retrieve the
student records as xml file using dom.
Algorithm:
Step 1: Start
Step 6: Retrieve the records into the connection object using the mysql_query function
necessary.
Step 8: Start appending field in the records to student element by create element & append child
records.
Step 9: Write the students & values into student xml_files using method of dom object.
<?php
$con=mysqli_connect("localhost","system","tnc","studentmarks"); if (mysqli_connect_errno()) die ("Error
connecting db: ".mysqli_connect_error());
echo "connected to DB";
$domdoc=new DOMDocument();
$domdoc->encoding='utf-8';
$domdoc->xmlVersion='1.0';
$domdoc->formatOutput= true;
$xmlfilename ='students.xml';
$root=$domdoc->createElement('students');
$query="select * from student;";
$result =mysqli_query($con,$query); while ($row=mysqli_fetch_assoc($result))
{
echo "<br>".$row["regno"]." : ".$row["name"]." :".$row["age"]." : ".$row
["doorno"]." : ". $row["street"].": ".$row["city"];
$student=$domdoc->createElement('student');
$root->appendChild($student);
Result: