ECS751N Lab Manual
ECS751N Lab Manual
LAB MANUAL
CONCEPT: Controls statements are used to control are used to control the flow of execution of
program based on certain conditions. These are used to cause the flow of execution to advance and branch
based on changes to the state of program.
1. if statement
2. if-else statement
3. If..elseif..else statement
1. if: if statement is simple decision making statement. It is used to decide whether a certain
statement or block of statements will be executed or not. i.e. if a certain condition is true then the block
will be executed otherwise not.
Syntax:
if(condition)
{
//Statement to execute if the condition is true.
}
2. if-else statement: The if statement alone tells us that if a condition is true it will execute a block of
statements and if the condition false, else block will be executed.
if( condition)
{
//Statement to execute if the condition is true
}
else
{
//Statement to execute if the condition is false
}
3. switch statement
The switch statement is used to perform different actions based on different conditions. Use the switch
statement to select one of many blocks of code to be executed.
switch(n)
{
case label1:
//code to be executed if n=label1; break;
case label2:
//code to be executed if n=label2; break;
case label3:
//code to be executed if n=label3; break;
...
default:
//code to be executed if n is different from all labels;
Source Code:
If Statement:
<html>
<head>
<title> Basic If Statements </title>
</head>
<body>
<h1>Day Report</h1>
<?php
$day = 'sunday';
if ($day == 'sunday') {
echo '<p>today is sunday.go to sleep.</p>';
}?>
</body>
</html>
If Else
<html>
<head>
<title> If Else</title>
</head>
<body>
<h1>Day Report</h1>
<?php
$day = 'monday';
if ($day == 'sunday') {
echo '<p>Today is sunday. go to sleep.</p>';
} else {
echo '<p>today is Monday the student are ready to go school.</p>';
}?>
</body>
</html>
Switch Case:
<html>
<body>
<?php
$favcolor = "red";
switch ($favcolor) {
case "red":
echo "Your favorite color is red!";
break;
case "blue":
echo "Your favorite color is blue!";
break;
case "green":
echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither red, blue, nor green!";
}?>
</body></html>
Experiment - 2
Do..While loop
do
{
//code to be executed;
} while (condition is true);
For loop
for (init counter; test counter; increment counter)
{
//code to be executed for each iteration;
}
Source Code:
Do While Loop:
<html>
<body>
<?php
$a = 1;
do {
echo "The number is: $a <br>";
$a++;
} while ($a <= 10);
?>
</body>
</html>
While Loop
<html>
<body>
<?php
$s = 1;
while($s <= 7)
{
echo "The number is: $s <br>";
$s++;
}
?>
</body>
</html>
For Loop:
<html>
<body>
<?php
$d = 0;
$e = 0;
for( $i = 0; $i<5; $i++ )
{
$d += 10;
$e += 5;
}
echo ("At the end of the loop d = $d and e = $e" );
?>
</body>
</html>
Experiment - 3
Objective: Write a PHP program for creating and manipulating- a) Indexed array
b) Associative array c) Multidimensional array
CONCEPT:
There are basically three types of arrays in PHP:
Indexed or Numeric Arrays: An array with a numeric index where values are stored linearly.
Associative Arrays: An array with a string index where instead of linear storage, each value can
be assigned a specific key.
Multidimensional Arrays: An array which contains single or multiple array within it and can be
accessed via multiple indices.
Indexed or Numeric Arrays:
These type of arrays can be used to store any type of elements, but an index is always a number.
By default, the index starts at zero.
$cars = array(“Volvo”,”BMW”,”Toyota”); OR
The index can be assigned manually:
$cars[0] = “Volvo”;
$cars[1] = “BMW”;
$cars[2] = “Toyota”;
Associative Arrays:
Associative arrays are arrays that use named keys that you assign to them. There are two ways
to create an associative array:
$total = array(“fyif”=> “58”, “syif” => “61”, “tyif”=> “46”);
OR
$total[‘fyif’]= “58”;
$total[‘syif’]= “61”;
$total[‘tyif’]= “46”;
Multidimensional Arrays:
A two-dimensional array is an array of arrays (a three-dimensional array is an array of arrays of arrays).
Example:
$student = array (
array("xyz",3401,86.45),
array("abc",3402,87.42),
array("pqr",3403,85.43),
);
Source Code:
Indexed or Numeric Arrays:
<html>
<body>
<?php
$cars= array("Volvo", "BMW", "Toyota");
$arrlength=count($cars);
for($x= 0;$x<$arrlength;$x++)
{
echo $cars[$x]; echo "<br>";
}
?>
</body>
</html>
Associative Arrays:
<html>
<body>
<?php
$total = array("fyif"=>"58", "syif"=>"61", "tyif"=>"46"); foreach($total as $x => $x_value)
{
echo "Key=" . $x . ", Value=" . $x_value; echo "<br>";
}
?>
</body>
</html>
Multidimensional Arrays:
<html>
<body>
<?php
$student = array (
array("XYZ",3401,86.45),
array("PQR",3402,87.42),
array("ABC",3403,85.43),
);
for ($row = 0; $row < 3; $row++) {
echo "<p><b>Row number $row</b></p>"; echo "<ul>";
for ($col = 0; $col < 3; $col++) {
echo "<li>".$student[$row][$col]."</li>";
}
echo "</ul>";
}
?>
</body>
</html>
Experiment - 4
Objective: A. Write a PHP program to- • Calculate length of string. • Count the
number of words in string without using string functions
B. Write a simple PHP program to demonstrate use of various built-in string
functions
CONCEPT:
Sr.
PHP function Use Example
No.
The PHP strlen() function returns the length of a
1 strlen() echo strlen("Hello world!");
string.
The PHP str_word_count() function counts the echo str_word_count("Hello
2 str_word_count()
number of words in a string. world!");
3 strrev() The PHP strrev() function reverses a string. echo strrev("Hello world!");
function function_name()
{
//body of function.
}
Function Types
1. Simple function
2. Function with parameter
3. Anonymous function.
Source Code:
Noraml Function:
<html>
<body>
<?php
function myMessage() {
echo "Hello world!";
}
myMessage();
?>
</body>
</html>
Function with Return Type:
<html>
<body>
<?php
function sum($x, $y) {
$z = $x + $y;
return $z;
}
echo "5 + 10 = " . sum(5,10) . "<br>";
echo "7 + 13 = " . sum(7,13) . "<br>";
echo "2 + 4 = " . sum(2,4);
?>
</body>
</html>
</html>
Function with default argument value
<html>
<body>
<?php
function setHeight($minheight = 50) {
echo "The height is : $minheight <br>";
}
setHeight(350);
setHeight();
setHeight(135);
setHeight(80);
?>
</body>
</html>
Function with variable number of arguments
<html>
<body>
<?php
function sumMyNumbers(...$x) {
$n = 0;
$len = count($x);
for($i = 0; $i < $len; $i++) {
$n += $x[$i];
}
return $n;
}
$a = sumMyNumbers(5, 2, 6, 2, 7, 7);
echo $a;
?>
</body>
</html>
Anonymous Function
<html>
<body>
<?php
//Defining Anonymous function
$a=function() {
echo "Anonymous function";
};
//Calling Anonymous function
$a();
?>
</body>
</html>
Experiment - 6
Objective: Write a simple PHP program to create PDF document buy using
graphics concepts
CONCEPT:
PHP uses a standard code to display the pdf file in web browser. The process of displaying pdf
involves location of the PDF file on the server and it uses various types of headers to define
content composition in form of type, Disposition, Transfer-Encoding etc. PHP passes the PDF
files to read it on the browser. Browser either shows it or download it from local host server then
display pdf.
Note: PHP is not actually reading the PDF file. It does not recognize File as pdf. It only passes
the PDF file to the browser to be read there. If copy the pdf file inside htdocs folder of XAMPP
then it does not need to specify the file path.
FPDF is a PHP class which allows to generate PDF files with pure PHP, that is to say without
using the PDFlib library. F from FPDF stands for Free: you may use it for any kind of usage and
modify it to suit your needs.
FPDF has other advantages: high level functions. Here is a list of its main features:
1) Choice of measure unit, page format and margins
2) Page header and footer management
3) Automatic page break
4) Automatic line break and text justification
5) Image support (JPEG, PNG and GIF)
6) Colors
7) Links
8) TrueType, Type1 and encoding support
9) Page compression
Source Code:
<?php
require('fpdf/fpdf.php');
// Page header
function Header() {
// Header
$this->Cell(50,10,'Heading',1,0,'C');
// Line break
$this->Ln(20);
}
// Page footer
function Footer() {
// Arial italic 8
$this->SetFont('Arial','I',8);
// Page number
$this->Cell(0,10,'Page ' .
$this->PageNo() . '/{nb}',0,0,'C');
}
}
?>
Experiment - 7
{
// The class can use the parent’s class code
}
Constructor:
Constructors are special member functions for initialize variables on the newly created object
instances from a class.
When creating a new object, it’s useful to setup certain aspects of the object at the same time.
For example, you might want to set some properties to initial values fetch some information
from a database to populate the object, or register the object in some way.
Constructor are of two types Default and parameterized constructor.
Source Code:
<html>
<body>
<?php
class Fruit {
public $name;
public $color;
public function __construct($name, $color) {
$this->name = $name;
$this->color = $color;
}
public function intro() {
echo "The fruit is {$this->name} and the color is {$this->color}.";
}
}
PHP provides some inbuilt function, using these functions that input data can be validated.
empty() function will ensure that text field is not blank it is with some data, function
accepts a variable as an argument and returns. It TRUE when the text field have filled
with some data otherwise it return FALSE.
is_numeric() function will ensure that data entered in a text field is a numeric
value, the function accepts a variable as an argument and returns TRUE when the
text field is submitted with numeric value otherwise it return FALSE.
preg_match() function is specifically used to performed validation for entering text in
the text field, function accepts a “regular expression” argument and a variable as an
argument which has to be in specific pattern. Typically it is for validating email, IP
address and Pin code information in a form.
Source Code:
<html>
<head>
</head>
<body>
<?php
// define variables and set to empty values
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = test_input($_POST["name"]);
$email = test_input($_POST["email"]);
$website = test_input($_POST["website"]);
$comment = test_input($_POST["comment"]);
$gender = test_input($_POST["gender"]);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>
</body>
</html>
Experiment - 9
<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>
</body>
</html>
Get PHP Session Variable Values
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Echo session variables that were set on previous page
echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";
echo "Favorite animal is " . $_SESSION["favanimal"] . ".";
?>
</body>
</html>
Modify a PHP Session Variable
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// to change a session variable, just overwrite it
$_SESSION["favcolor"] = "yellow";
print_r($_SESSION);
?>
</body>
</html>
Destroy a PHP Session
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// remove all session variables
session_unset();
</body>
</html>