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

php7 8

The document discusses user defined functions in PHP. It provides examples of functions with parameters, returning values, default arguments, and variable length arguments. It also demonstrates calling functions by value and reference. The practical aims to have students practice writing PHP scripts using different types of user defined functions.

Uploaded by

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

php7 8

The document discusses user defined functions in PHP. It provides examples of functions with parameters, returning values, default arguments, and variable length arguments. It also demonstrates calling functions by value and reference. The practical aims to have students practice writing PHP scripts using different types of user defined functions.

Uploaded by

Hetal Vasava
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

Web Development using PHP (4341604)

Date: _________________
Practical No.6: User defined Functions
a. Write a PHP script to call by reference and call by value.
b. Write a PHP Script for performing function that takes arguments
with default argument and returns value.
c. Write a PHP Script to show the use of variable length argument.

A. Objective:
A function is a block of reusable code that is used to perform a specific task. Functions
enhances the readability of a program, Reduce duplication of the code, reduces the
complexity of a program. User-defined functions help to decompose a large program
into small segments which makes program easy to understand, maintain and debug.
This practical will help student to practice writing PHP scripts using user defined
functions.

B. Expected Program Outcomes (POs)


Basic and Discipline specific knowledge: Apply knowledge of basic mathematics,
science and engineering fundamentals and engineering specialization to solve the
engineering problems.
Problem analysis: Identify and analyse well-defined engineering problems using
codified standard methods.
Design/ development of solutions: Design solutions for engineering well-defined
technical problems and assist with the design of systems components or processes to
meet specified needs.
Engineering Tools, Experimentation and Testing: Apply modern engineering tools
and appropriate technique to conduct standard tests and measurements.
Project Management: Use engineering management principles individually, as a team
member or a leader to manage projects and effectively communicate about well-
defined engineering activities.
Life-long learning: Ability to analyze individual needs and engage in updating in the
context of technological changes in field of engineering.

C. Expected Skills to be developed based on competency:


“Develop a webpage using PHP”
This practical is expected to develop the following skills.
1. Understand the use of calling function by value and by reference.
2. Write PHP script for functions having return value, default argument, variable
length argument etc.
3. Follow coding standards and debug program to fix errors.

226120316067 59 | P a g e
Web Development using PHP (4341604)

D. Expected Course Outcomes(Cos)


CO2: Create User defined functions in PHP programming.

E. Practical Outcome(PRo)
Students will be able to create user defined functions for different tasks.

F. Expected Affective domain Outcome(ADos)


1) Follow safety practices.
2) Follow Coding standards and practices.
3) Demonstrate working as a leader/ a team member.
4) Follow ethical practices.
5) Maintain tools and equipment.

G. Prerequisite Theory:
User defined functions
User-defined functions can be used to group code into reusable blocks and make the
code more modular and easier to maintain.

Syntax:

function function_name(arg1, arg2, ..., argN)


{
code to be executed
}

Here,
- function: This is the keyword that tells PHP that you are defining a
function.
- function_name: This is the name of the function.
- (arg1, arg2, ..., argN): These are the arguments that the function accepts.
Arguments are optional, and you can define as many or as few as you
need.
- code to be executed: This is the code that the function executes when it
is called.

226120316067 60 | P a g e
Web Development using PHP (4341604)

<?php
function test()
{
echo "Welcome Students.";
}

test();
?>
O/P:
Welcome Students.

Function with parameters


<?php
function sum($num1, $num2)
{
$sum = $num1 + $num2;
echo "Sum of the two numbers is: $sum";
}

sum(10,20);
?>
O/P:
Sum of the two numbers is: 30

Function with returning value


<?php
function sum($num1, $num2)
{
$sum = $num1 + $num2;
return $sum;
}
$ret_sum = sum(10,20);
echo "Returned value from function is: $sum";
?>

O/P:
Returned value from function is: 30

226120316067 61 | P a g e
Web Development using PHP (4341604)

Function with default argument


<?php
function sum($num1, $num2 = 5)
{
$sum = $num1 + $num2;
echo "Sum of the two numbers is: $sum <br/>";
}
sum(10);
sum(10,20);
?>

O/P:
Sum of the two numbers is: 15
Sum of the two numbers is: 30

Variable length argument function


Normally when we create function, the number of arguments are created according to
requirement of function. Also we pass argument in function calling according to
argument of the function. But in PHP, we have facility to call function according to
arguments. We can pass arguments to a function that has no argument defined. PHP
allows to access arguments provided in the function call operation without using
argument variable in function declaration.
PHP supports variable-length argument with below basic rules :
- The function call can provide more arguments than the number of arguments
defined in function declaration.
- We can pass arguments to a function that has no argument variable defined.
To support variable length arguments, there are predefined functions :
- func_num_args()
- func_get_args()
- func_get_arg()

func_num_args()
It returns the total number of arguments provided in the function call operation.

226120316067 62 | P a g e
Web Development using PHP (4341604)

<?php
function sum()
{
echo func_num_args();
}
sum(10,20,30,40);
?>
O/P: 4

func_get_args()
It creates and returns an array which contains values of arguments provided in the
function call operation.

<?php
function dept()
{
$arr = func_get_args();
Print_r($arr);
}
dept(“IT”, “CE”, “ME”);
?>
O/P: Array ( [0] => “IT” [1] => “CE” [2] => “ME” )

func_get_arg(int position)
It returns the value of specified argument provided in the function call operation. Here
‘position’ is the position index of specified argument.

<?php

function dept()
{
echo func_get_arg(2);
}
dept(“IT”, “CE”, “ME”);
?>

O/P: ME

226120316067 63 | P a g e
Web Development using PHP (4341604)

Function call by value


In this method, only values of actual parameters are passing to the function. So there
are two addresses stored in memory. Making changes in the passing parameter does
not affect the actual parameter.

<?php
function incr($val)
{
$val = $val + 1;
echo $val . "<br/>";
}
$a = 1;
incr($a);
echo $a;
?>
O/P: 2
1

Function call by reference


In this method, the address of actual parameters is passing to the function. So any
change made by function affects actual parameter value.

<?php
function incr(&$val)
{
$val = $val + 1;
echo $val . "<br/>";
}

$a = 1;
incr($a);
echo $a;
?>
O/P: 2
2

226120316067 64 | P a g e
Web Development using PHP (4341604)

H. Resources/Equipment Required
Sr. Instrument/Equipment/
Specification Quantity
No. Components/Trainer kit
Computer (i3-i5 preferable), RAM
1 Hardware: Computer System
minimum 2 GB and onwards
2 Operating System Windows/ Linux/ MAC
As Per
XAMPP server (PHP, Web server, Batch
3 Software
Database) Size
Notepad, Notepad++, Sublime Text or
4 Text Editor
similar

5 Web Browser Edge, Firefox, Chrome or similar

I. Safety and necessary Precautions followed


NA

J. Source code:

A) Write a PHP script to call by reference and call by value.

<?php
//Call By Value
function increment($var){
$var++;
return $var;
}
$a = 5;
$b = increment($a);
echo "A: $a <br>";
echo "B: $b <br>";

//Call by Reference
function increment1(&$var){
$var++;
return $var;
}
$a1 = 5;
$b1 = increment1($a1);
echo "A1: $a1 <br>";
echo "B1: $b1 <br>";
?>

226120316067 65 | P a g e
Web Development using PHP (4341604)

B) Write a PHP Script for performing function that takes arguments with default
argument and returns value.

<?php
function add($n1=10,$n2=10){
$n3=$n1+$n2;
echo "Addition is: $n3<br/>";
}
add();
add(20);
add(40,40);
?>

Output:

C) Write a PHP Script to show the use of variable length argument.

<?php
function sum(...$numbers) {
$res = 0;
foreach($numbers as $n) {
$res+=$n;
}
return $res;
}

echo("Sum of(12,34,67,9,21) :".sum(12,34,67,9,21)."<br>");


?>

Output:

226120316067 66 | P a g e
Web Development using PHP (4341604)

K. Practical related Quiz.


1) How to define a function in PHP?
a) function {function body}
b) data type functionName(parameters) {function body}
c) functionName(parameters) {function body}
d) function functionName(parameters) {function body}

2) Which type of function call is used in line 8 in the following PHP code?
<?php
function calc($price, $tax)
{
$total = $price + $tax;
}
$pricetag = 15;
$taxtag = 3;
calc($pricetag, $taxtag);
?>
a) Call By Value b) Call By Reference
c) Default Argument Value d) Type Hinting

3) What will be the output of the following PHP code?


<?php
function calc($price, $tax="")
{
$total = $price + ($price * $tax);
echo "$total";
}
calc(42);
?>
a) Error b) 0
c) 42 d) 84

226120316067 67 | P a g e
Web Development using PHP (4341604)

4) A function name cannot start with a

a) Alphabet b) Underscore
c)Number d) Both c and b

5) Function names are case-sensitive.

a) True b) False
c) Only Built-In function d) Only User-defined function.

K. References / Suggestions
1) https://www.w3schools.com/php/default.asp
2) https://www.guru99.com/php-tutorials.html
3) https://www.tutorialspoint.com/php/
4) https://tutorialehtml.com/en/php-tutorial-introduction/
5) www.tizag.com/phpT/
6) https://books.goalkicker.com/PHPBook/
7) https://spoken-tutorial.org/tutorial-
search/?search_foss=PHP+and+MySQL&search_language=English
8) https://codecourse.com/watch/php-basics
9) https://onlinecourses.swayam2.ac.in/aic20_sp32/preview

L. Assessment-Rubrics

Faculty
Marks Obtained Date
Signature
Program Implementation Student’s engagement
Correctness and Presentation in practical activities Total
(4) Methodology (3) (3) (10)
R1 R2 R3

226120316067 68 | P a g e
Web Development using PHP (4341604)

Date: _________________
Practical No.7: Built-In functions
a. Write PHP script to demonstrate the use of various strings handling
function.
b. Write a PHP script to demonstrate the use of Include() and
require() function.
c. Write PHP script to demonstrate the use of Array functions.
d. Write PHP script to demonstrate the use of fopen(), fread(), fwrite()
and fclose() file functions.

A. Objective:
Built-in functions are predefined functions in PHP that exist in the PHP library. These
PHP inbuilt functions make PHP a very efficient and productive scripting language. The
built in functions of PHP classified into many categories. Students will be able to learn
various built-in functions like string functions, array functions, file functions etc.

B. Expected Program Outcomes (POs)


Basic and Discipline specific knowledge: Apply knowledge of basic mathematics,
science and engineering fundamentals and engineering specialization to solve the
engineering problems.
Problem analysis: Identify and analyse well-defined engineering problems using
codified standard methods.
Design/ development of solutions: Design solutions for engineering well-defined
technical problems and assist with the design of systems components or processes to
meet specified needs.
Engineering Tools, Experimentation and Testing: Apply modern engineering tools
and appropriate technique to conduct standard tests and measurements.
Project Management: Use engineering management principles individually, as a team
member or a leader to manage projects and effectively communicate about well-
defined engineering activities.
Life-long learning: Ability to analyze individual needs and engage in updating in the
context of technological changes in field of engineering.

C. Expected Skills to be developed based on competency:


“Develop a webpage using PHP”
This practical is expected to develop the following skills.
1. Write PHP script for various string handling functions.
2. Write PHP script to demonstrate Include() and Require() functions.
3. Write PHP script for various array and file functions.
4. Follow coding standards and debug program to fix errors.

226120316067 69 | P a g e
Web Development using PHP (4341604)

D. Expected Course Outcomes(Cos)


CO2: Create User defined functions in PHP programming.

E. Practical Outcome(PRo)
Students will be able to use different built-in functions of string, file and array.

F. Expected Affective domain Outcome(ADos)


1) Follow safety practices.
2) Follow Coding standards and practices.
3) Demonstrate working as a leader/ a team member.
4) Follow ethical practices.
5) Maintain tools and equipment.

G. Prerequisite Theory:
PHP String Functions
echo
Use: To output/display one or more strings or variables to the screen.
Note: The echo() function is not actually a function, so you are not
required to use parentheses with it. However, if you want to pass more
than one parameter to echo(), using parentheses will generate an error.
Syntax: echo(strings)
Example: <?php
echo "Hello world";
?>
Output: Hello world

print
Use: To output/display one or more strings or variables to the screen.
Note: The print() function is not actually a function, so you are not
required to use parentheses with it.
Syntax: print(strings)
Example: <?php
print "Hello world";
?>
Output: Hello world

strlen()
Use: To find the length of strings.
Return: The length of a string.
Syntax: strlen(String)

226120316067 70 | P a g e
Web Development using PHP (4341604)

Example: <?php
echo strlen("Hello world");
?>
Output: 11

str_word_count()
Use: To count the words of strings.
Return: The number of words in the string.
Syntax: str_word_count(String)
Example: <?php
echo str_word_count("Hello world");
?>
Output: 2

strrev()
Use: To reverse the given strings.
Return: The reversed string.
Syntax: strrev(String)
Example: <?php
echo strrev("Hello world");
?>
Output: dlrow olleH

str_replace()
Use: To replace some of the characters in a string with some other.
Return: The string with replacements.
Syntax: str_replace(search, replace, string)

Here;
Search: Required. This will be the string to search for replacing.
Replace: Required. This will replace the searched string.
String: Required. This will the string which we have to search and
replace.
Example: <?php
echo str_replace("Hello","Hi","Hello world");
?>
Output: Hi world

strstr()
Use: To display the part of the string from the first search occurrence.
Note: This function is case-sensitive. For a case-insensitive search, use
stristr() function.
Return: The rest of the string.
Syntax: strstr(string,search,before_search)

226120316067 71 | P a g e
Web Development using PHP (4341604)

Here;
String: Required. This will be the string to search.
Search: Required. Specifies the string to search for. If this is a number, it
will search for the character matching the ASCII value of the number.
Before_search: Optional. A boolean value whose default is "false". If set to
"true", it returns the part of the string before the first occurrence of the
search parameter.
Example: <?php
echo strstr("Hello world","world") . "<br/>";
echo strstr("Hello world","world",true);
?>
Output: world
Hello

substr()
Use: To extract the string.
Return: The a part of the string.
Syntax: substr(string,start,length)

Here;
String: Required. This will be the string to return a part of.
Start: Required. Specifies where to start in the string
- A positive number - Start at a specified position in the string
- A negative number - Start at a specified position from the end of the
string
- 0 - Start at the first character in string
Length: Optional. Specifies the length of the returned string.
- A positive number - The length to be returned from the start
- Negative number - The length to be returned from the end
- If the length parameter is 0, NULL, or FALSE - returns empty string
Example: <?php
echo substr("Hello world",7) ."<br/>";
echo substr("Hello world",-7) ."<br/>";
echo substr("Hello world",7,2) ."<br/>";
echo substr("Hello world",1,-7) ."<br/>";
echo substr("Hello world",-7,-1);
?>
Output: orld
o world
or
ell
o worl

strtolower()

226120316067 72 | P a g e
Web Development using PHP (4341604)

Use: To extract the string.


Return: String in lower case.
Syntax: strtolower(string)
Example: <?php
echo strtolower("Hello World");
?>
Output: hello world

strtoupper()
Use: To extract the string.
Return: String in upper case.
Syntax: strtoupper(string)
Example: <?php
echo strtoupper("Hello World");
?>
Output: HELLO WORLD

ucwords()
Use: To convert the first character of each word in a string to uppercase.
Return: String with first character of each word in uppercase.
Syntax: ucwords(string, delimiters)

Here;
String: Required. This will be the string to convert.
Delimiters: Optional. Word separator character.
Example: <?php
echo ucwords("hello world") ."<br/>";
echo ucwords("hello-world", "-");
?>
Output: Hello World
Hello-World

strpos()
Use: To find the position of the first occurrence of a string inside another
string.
Note: The strpos() function is case-sensitive.
Return: The position of the first occurrence of a string inside another string, or
FALSE if the string is not found. (String positions start at 0).
Syntax: strpos(string, find, start)

Here;
String: Required. This will be the string to search.
Find: Required. This will be the string to find.
Start: Optional. Specifies where to begin the search. (If start is a negative
number, it counts from the end of the string.)

226120316067 73 | P a g e
Web Development using PHP (4341604)

Example: <?php
echo ucwords("hello world") ."<br/>";
echo ucwords("hello-world", "-");
?>
Output: Hello World
Hello-World

ltrim()
Use: To remove whitespace and other predefined characters from left side of
a string.
Return: String after removing of space/characters.
Syntax: ltrim(string, charlist)

Here;
String: Required. This will be the string to check.
Charlist: Optional. This will be characters to remove from the string.
Example: <?php
echo ltrim("Hello world","Held");
?>
Output: o world

rtrim()
Use: To remove whitespace and other predefined characters from right side
of a string.
Return: String after removing of space/characters.
Syntax: rtrim(string, charlist)

Here;
String: Required. This will be the string to check.
Charlist: Optional. This will be characters to remove from the string.
Example: <?php
echo rtrim("Hello world","Held");
?>
Output: Hello wor

trim()
Use: To remove whitespace and other predefined characters from both sides
of a string.
Return: String after removing of space/characters.
Syntax: trim(string, charlist)

Here;
String: Required. This will be the string to check.
Charlist: Optional. This will be characters to remove from the string.
Example: <?php

226120316067 74 | P a g e
Web Development using PHP (4341604)

echo trim("Hello world","Held");


?>
Output: o wor

implode()
Use: To convert the array to strings. It takes an array and converts those
array to strings by using any separator.
Return: String from elements of an array.
Syntax: implode(separator, array)

Here;
Separator: Optional. This will be the separator to put between the array
elements. Default is "" (an empty string).
Array: Required. This will be an array.
Example: <?php
$arr = array('Hello','World');
echo implode(" ",$arr) ."<br/>";

echo implode("-",$arr);
?>
Output: Hello World
Hello-World

explode()
Use: To break a string into an array.
Return: An array of strings.
Syntax: explode(separator, string, limit)

Here;
Separator: Required. This will be the for where to break the string.
String: Required. This will be string to split.
Limit: This will be the number of array elements to return.
limit can be, >0 - Returns an array with a maximum of limit element(s)
<0 - Returns an array except for the last -limit element(s)
0 - Returns an array with one element
Example: <?php
$str = "Welcome to the PHP world.";
print_r (explode(" ",$str));
echo "<br/>";
print_r (explode(" ",$str,0));
echo "<br/>";
print_r (explode(" ",$str,3));
echo "<br/>";
print_r (explode(" ",$str,-1));
?>

226120316067 75 | P a g e
Web Development using PHP (4341604)

Output: Array ( [0] => Welcome [1] => to [2] => the [3] => PHP [4] => world. )
Array ( [0] => Welcome to the PHP world. )
Array ( [0] => Welcome [1] => to [2] => the PHP world. )
Array ( [0] => Welcome [1] => to [2] => the [3] => PHP )

PHP include() and require() function


In PHP, the include() and require() functions are used to include and execute the
contents of another PHP file within the current PHP file. This is useful when you want
to reuse code across multiple files, or when you want to break up a large PHP file into
smaller, more manageable pieces.
While using include() if there are any kind of errors then this include() function will
pop up a warning but, it will not stop the execution of the script rather the script will
continue its process.
While using require() if there are any kind of errors then this require() function will
pop up a warning along with a fatal error and it will immediately stop the execution of
the script.

Syntax:
include 'filename';
or
require 'filename';

Let’s assume that we have a file named ‘two.php’ and we want to include it in our page
named ‘one.php’.

two.php:
<?php
echo "<p>Thank you for visiting our website.</p>";
?>

one.php:
<html>
<body>

<h1>Welcome to the PHP world!</h1>


<p>This is demo of include/require() functions.</p>
<p>Let’s test it.</p>
<?php include 'two.php';?>

</body>
</html>
Output:

Welcome to the PHP world!


This is demo of include/require() functions..
Let’s test it.

Thank you for visiting our website.

226120316067 76 | P a g e
Web Development using PHP (4341604)

Same way you can use require() function and test it.

PHP Array Functions


in_array()
Use: To search an array for a specific value.
Return: TRUE if the value is found in the array, or FALSE otherwise
Syntax: in_array(search, array, type)

Here;
Search: Required. This will be the what to search for.
Array: Required. This will be array to search.
Type: Optional. If this is set to TRUE, it searches for the search-string and
specific type in the array.
Example: <?php
$dept = array("IT", "CE", "ME", 16);
if (in_array("16", $dept, TRUE)) {
echo "Match found<br>";
}
else {
echo "Match not found<br>";
}
if (in_array("IT",$dept)) {
echo "Match found<br>";
}
else {
echo "Match not found<br>";
}
?>
Output: Match not found
Match found

in_array()
Use: To merge one or more arrays into one array.
Return: Merged array.
Syntax: array_merge(array1, array2, …., arrayN)
Example: <?php
$a1=array("IT","CE");
$a2=array("ME","EE");
print_r(array_merge($a1,$a2));
?>
Output: Array ( [0] => IT [1] => CE [2] => ME [3] => EE )

array_push()
Use: To insert one or more elements to the end of an array.

226120316067 77 | P a g e
Web Development using PHP (4341604)

Return: The new number of elements in the array.


Syntax: array_push(array, value1, value2, ….)
Example: <?php
$a=array("IT","CE");
array_push($a,"CE");
print_r($a);
?>
Output: Array ( [0] => IT [1] => CE [2] => ME )

array_pop()
Use: To delete the last element of an array.
Return: The new array after deletion.
Syntax: array_pop(array)
Example: <?php
$a=array("IT","CE","ME");
array_pop($a);
print_r($a);
?>
Output: Array ( [0] => IT [1] => CE )

array_replace()
Use: To replace the values of the first array with the values from following
arrays.
Return: The replaced array, or NULL if an error occurs.
Syntax: array_replace(array1, array2, …)
Example: <?php
$a1=array("IT","CE");
$a1=array("EE","ME");
print_r(array_replace($a1,$a2));
?>
Output: Array ( [0] => EE [1] => ME )

array_reverse()
Use: To reverse the specified arrays.
Return: The reversed array.
Syntax: array_reverse(array)
Example: <?php
$a=array("IT","CE");
print_r(array_reverse($a));
?>
Output: Array ( [0] => CE [1] => IT )

array_search()
Use: To search an array for a value.
Return: The key of a value if it is found in the array, and FALSE otherwise.

226120316067 78 | P a g e
Web Development using PHP (4341604)

Syntax: array_search(value, array, strict)

Here;
Value: Required. This will be the value to search for.
Array: Required. This will be array to search.
Strict: Optional. If this parameter is set to TRUE, then this function will
search for identical elements in the array. Default is FALSE.
Example: <?php
$a=array("a"=>"IT","b"=>"CE");
echo array_search("IT",$a);
?>
Output: a

count()
Use: To count of elements in an array.
Return: The number of elements in an array.
Syntax: count(array, mode)

Here;
Array: Required. This will be an array.
Mode: Optional. It will be 0 or 1. Default is 0 and it does not count all
elements of multidimensional arrays. If it is 1 then it counts the array
recursively (counts all the elements of multidimensional arrays).
Example: <?php
$a=array("IT","CE");
echo (count($a));
?>
Output: 2

current(), next(), prev(), reset(), end()


Use: To get appropriate element from array (current, next, previous etc).
Return: current() - The current element of an array.
next() - The next element of an array. (internal pointer move to here)
prev() - The previous element of an array. (pointer move to here)
reset() - The first element of an array. (internal pointer move to first)
end() - The last element of an array. (internal pointer move to last)
Syntax: current(array), next(array), prev(array), reset(array), end(array)
Example: <?php
$dept = array("IT", "CE", "ME", "EE");
echo current($dept) . "<br>";
echo next($dept) . "<br>";
echo current($dept) . "<br>";
echo prev($dept) . "<br>";
echo end($dept) . "<br>";
echo prev($dept) . "<br>";

226120316067 79 | P a g e
Web Development using PHP (4341604)

echo current($dept) . "<br>";


echo reset($dept) . "<br>";
echo next($dept);
?>
Output: IT
CE
CE
IT
EE
ME
ME
IT
CE

list()
Use: To assign values to a list of variables in one operation.
Return: The assigned array.
Syntax: list(var1, var2, var3, …)
Example: <?php
$arr = array("IT","CE");
list($a, $b) = $arr;
echo "Our departments are $a and $b.";
?>
Output: Our departments are IT and CE.

sort()
Use: To sort an indexed array in ascending order.
Return: TRUE on success. FALSE on failure
Syntax: sort(array)
Example: <?php
$arr=array("IT","CE","ME","EE");
sort($arr);
$alen=count($arr);
for($x=0;$x<$alen;$x++)
{
echo $arr[$x] . "<br/>”;
}
?>
Output: CE
EE
IT
ME

226120316067 80 | P a g e
Web Development using PHP (4341604)

PHP File Functions


fopen()
Use: To open a file or URL.
Return: A file pointer resource on success, FALSE and an error on failure.
Syntax: fopen(filename, mode)

Here;
Array: Required. This will be file or URL to open.
Mode: Required. This will be the type of access you require to the file.
Modes can be r, r+, w, w+, a, a+, x, x+, c, c+.

fclose()
Use: To close a file.
Return: TRUE on success, FALSE on failure.
Syntax: fclose(filepointer)

fread()
Use: To read from an open file.
Return: A file pointer resource on success, FALSE and an error on failure.
Syntax: fread(file, length)

Here;
File: Required. This will be file to read from.
Length: Required. This will be the maximum number of bytes to read.
Example: <?php
$file = fopen("test.txt","r");
fread($file,"5");
fclose($file);
?>

fwrite()
Use: To write to an open file.
Return: The number of bytes written, FALSE on failure.
Syntax: fwrite(file, string, length)

Here;
File: Required. This will be file to write to.
string: Required. This will be string to write in file.
Length: Optional. This will be maximum number of bytes to write.
Example: <?php
$file = fopen("test.txt","w");
fwrite($file,"Hello World")
fclose($file);
?>
Output: 11

226120316067 81 | P a g e
Web Development using PHP (4341604)

PHP Variable Functions

gettype() gettype(variable name); It accepts variable as an argument and


returns the data type of that variable.
settype() settype(Variable name, It accepts a variable as an argument and set it
Data type); to specific data type passed as an argument.
isset() isset(Variable Name); It accepts a variable as an argument and
determines whether the variable exists and it
is assigned value or not.
unset() unset(Variable Name); It accepts a variable as an argument and
destroys that variable from memory.
strval() strval(variable name); It accepts variable as an argument and
returns the string value of that variable.
floatval() floatval(variable name); It accepts variable as an argument and
returns the Float value of that variable.
intval() intval(variable name); It accepts variable as an argument and
returns the Integer value of that variable.
print_r() print_r(variable name); It accepts variable as an argument and
display it in a human readable format.
PHP Math Functions

abs() abs(Number); Accepts numbers an argument and Returns


the absolute value of a number.
ceil() ceil(Number); Accepts number as an argument and Returns
the number which is rounded upwards to
the nearest integer value.
floor() floor(Number); Accepts number as an argument and Returns
the number which is rounded downwards to
the nearest integer value.
round() round(Number [,Precision Accepts number as an argument and Returns
]); the number rounded to the nearest integer.
fmod() fmod(Number Accepts two numbers as an argument and
1,Number2); divides num1 by num2 and returns
reminder of division.
min() min(Number 1,Number2); Accepts two numbers as an argument and
returns lowest value among them.
max() max(Number 1,Number2); Accepts two numbers as an argument and
returns highest value among them.
pow() pow(Number 1,Number2); Accepts two numbers as an argument and
raises num1 to the power of num2 and
returns result.
sqrt() sqrt(Number); Accepts a number as an argument and
Returns square root of a number.
rand() rand([min],[max]); Generate a random integer between the
ranges of 0 to ROUND_MAX.

226120316067 82 | P a g e
Web Development using PHP (4341604)

H. Resources/Equipment Required
Sr. Instrument/Equipment/
Specification Quantity
No. Components/Trainer kit
Computer (i3-i5 preferable), RAM
1 Hardware: Computer System
minimum 2 GB and onwards
2 Operating System Windows/ Linux/ MAC
XAMPP server (PHP, Web server, As Per
3 Software Batch Size
Database)
Notepad, Notepad++, Sublime Text or
4 Text Editor
similar

5 Web Browser Edge, Firefox, Chrome or similar

I. Safety and necessary Precautions followed


NA

J. Source code:
A) Write PHP script to demonstrate the use of various strings handling function.
<?php
$string = "Hello, World! This is a PHP string.";
$length = strlen($string);
echo "1. String Length: $length <br>";

$uppercase = strtoupper($string);
echo "2. Uppercase: $uppercase <br>";

$lowercase = strtolower($string);
echo "3. Lowercase: $lowercase <br>";

$ucfirst = ucfirst($string);
echo "4. First character uppercase: $ucfirst <br>";

$lcfirst = lcfirst($string);
echo "5. First character lowercase: $lcfirst <br>";

$substring = substr($string, 7, 5); // Starting from the 7th character, take 5 characters
echo "6. Substring: $substring <br>";

$newString = str_replace("PHP", "JavaScript", $string);


echo "7. String after replacement: $newString <br>";

$position = strpos($string, "World");


echo "8. Position of 'World': $position <br>";
?>

226120316067 83 | P a g e
Web Development using PHP (4341604)

Output:

B) Write a PHP script to demonstrate the use of Include() and require() function.

<?php
// Including another PHP file using include()
echo "<h2>Using include()</h2>";
include 'include.php';
?>

<?php
// Requiring another PHP file using require()
echo "<h2>Using require()</h2>";
require 'required.php';
?>

Included file:
<?php
echo "<p>This is included content using include()
function.</p>";
?>

Required file: <?php


echo "<p>This is required content using require()
function.</p>";
?>

Output:

226120316067 84 | P a g e
Web Development using PHP (4341604)

C) Write PHP script to demonstrate the use of Array functions.


<?php
$fruits = array("Apple", "Banana", "Orange", "Mango", "Pineapple");
$numberOfFruits = count($fruits);
echo "1. Number of fruits: $numberOfFruits<br>";
echo "2. Fruits array: <pre>";
print_r($fruits);
echo"</pre>";
array_push($fruits, "Grapes", "Watermelon");
echo "3. After pushing new fruits: ";
print_r($fruits);
echo "<br>";
$poppedFruit = array_pop($fruits);
echo "4. Popped fruit: $poppedFruit <br>";
echo " After popping: ";
print_r($fruits);
echo "<br>";
$slicedArray = array_slice($fruits, 2, 3);
echo "5. Sliced array: ";
print_r($slicedArray);
echo "<br>";
$reversedArray = array_reverse($fruits);
echo "6. Reversed array:";
print_r($reversedArray);
echo "<br>";
$searchKey = array_search("Orange", $fruits);
echo "7. Key of 'Orange': $searchKey <br>";
$exists = in_array("Mango", $fruits);
echo "8. 'Mango' exists in the array: ";
echo $exists ? "Yes" : "No";
echo "<br>";
?>

226120316067 85 | P a g e
Web Development using PHP (4341604)

D) Write PHP script to demonstrate the use of fopen(), fread(), fwrite() and
fclose() file functions.

<?php
$filenm= "Hello.txt";

$file_Open = fopen($filenm, "w");


if ($file_Open) {
$Pere = "Hello World!!";
fwrite($file_Open, $Pere);
fclose($file_Open);
echo "this is also some content of file <br>";

} else {
echo "Error opening the file for writing.";
}

$file_Open= fopen($filenm, "r");


if ($file_Open) {
$file_content = fread($file_Open, filesize($filenm));
fclose($file_Open);
echo "Welcome to The New Program:<br>";
echo $file_content . "<br>";

} else {
echo "Error opening the file for reading.";
}
?>

Output:

K. Practical related Quiz.

1. Write difference between echo and print.

______________________________________________________________________________________________________
______________________________________________________________________________________________________
______________________________________________________________________________________________________
______________________________________________________________________________________________________
______________________________________________________________________________________________________
______________________________________________________________________________________________________
______________________________________________________________________________________________________
___________________________________________________
226120316067 86 | P a g e
Web Development using PHP (4341604)

2. function is used for replacing the whole string with an alternate string.

3. A function that capitalizes the first letter of each word in a string, is a .

4. in-built function will add a element to the end of an array.

5. function is used to get the value of the previous element in an array.

6. What will be the output of following code? __

<?php

$a=array("a"=>"IT","b"=>array("CE"));

echo (count($a,1));

?>

L. References / Suggestions
1) https://www.w3schools.com/php/default.asp
2) https://www.guru99.com/php-tutorials.html
3) https://www.tutorialspoint.com/php/
4) https://tutorialehtml.com/en/php-tutorial-introduction/
5) www.tizag.com/phpT/
6) https://books.goalkicker.com/PHPBook/
7) https://spoken-tutorial.org/tutorial-
search/?search_foss=PHP+and+MySQL&search_language=English
8) https://codecourse.com/watch/php-basics
9) https://onlinecourses.swayam2.ac.in/aic20_sp32/preview

M. Assessment-Rubrics

Faculty
Marks Obtained Date
Signature
Program Implementation Student’s engagement
Correctness and Presentation in practical activities Total
(4) Methodology (3) (3) (10)
R1 R2 R3

226120316067 87 | P a g e
Web Development using PHP (4341604)

Date: _________________
Practical No.8: Form Handling
a. Create student registration form using text box, check box, radio
button, select, submit button. And display user inserted value in
new PHP page using GET or POST Method.
b. Write a PHP script to explain the concept of $_REQUEST.

A. Objective:

Forms are important component of the web application that allows to collect
information from the users. Forms are used for various tasks such as login,
registration, contact us, and application specific information collection. This practical
will help students to design a form and to collect data entered in form input by users
using PHP.

B. Expected Program Outcomes (POs)

Basic and Discipline specific knowledge: Apply knowledge of basic mathematics,


science and engineering fundamentals and engineering specialization to solve the
engineering problems.
Problem analysis: Identify and analyse well-defined engineering problems using
codified standard methods.
Design/ development of solutions: Design solutions for engineering well-defined
technical problems and assist with the design of systems components or processes to
meet specified needs.
Engineering Tools, Experimentation and Testing: Apply modern engineering tools
and appropriate technique to conduct standard tests and measurements.
Project Management: Use engineering management principles individually, as a team
member or a leader to manage projects and effectively communicate about well-
defined engineering activities.
Life-long learning: Ability to analyze individual needs and engage in updating in the
context of technological changes in field of engineering.

C. Expected Skills to be developed based on competency:

“Develop a webpage using PHP”


This practical is expected to develop the following skills.
Create student registration form using tags.
1) Understand the use of Get and Post method of form.
2) Apply $_GET[], $_POST[] and $_REQUEST for collecting user inputs.
3) Follow coding standards and debug program to fix errors.

226120316067 88 | P a g e
Web Development using PHP (4341604)

D. Expected Course Outcomes(Cos)

CO3: Design and develop a Web site using form controls for presenting web-based
content.

E. Practical Outcome(PRo)

Students will be able to use a form and to collect data entered in form input by users
using PHP.

F. Expected Affective domain Outcome(ADos)

1) Follow safety practices.


2) Follow Coding standards and practices.
3) Demonstrate working as a leader/ a team member.
4) Follow ethical practices.
5) Maintain tools and equipment.

G. Prerequisite Theory:

From Tag

It is used to design form which contains various input controls that allows user to
input information.

Input Element

It allows you to place various controls in the form to accept input from user.

Sr. No. Type Control


1 Text Textbox
2 Hidden Hidden Textbox
3 Password Textbox with Password
4 Submit Submit Button
5 Checkbox Check Box
6 Radio Radio Button
7 Reset Reset Button
8 File File Upload
9 Button Button
10 Image Image button

226120316067 89 | P a g e
Web Development using PHP (4341604)

 Textbox Syntax:-
<input type=“text” name=“Text Name” value=“Default value”>
 Hidden field Syntax:-
<input type=“hidden” name=“field Name” value=“Default value”>
 Password Syntax:-
<input type=“password” name=“psw Name” value=“Default value”>
 TextArea Syntax:-
<textarea name =“Text name” rows=“rowsize” cols=“columnsize”>
 checkbox Syntax:-
<input type=“checkbox” name=“checkBoxName” value=“Default value”
checked> TextToDisplay </input>
 radio Button Syntax:-
<input type=“radio” name=“radioname” value=“Default value”
checked> TextToDisplay </input>
 List box Syntax:-
<select name=“List name” size=“value”>
<option>Value1</option>
<option>Value1</option>
</select>
 Submit Button Syntax:-
<input type=“submit” >
 Image Button Syntax:-
<input type=“image” SRC=“URL”>

Submit form using GET method:


 It will pass variable through URL.
 In this Method Information will be sent to destination file through URL using
concept of Query String.
 The GET method is restricted to send up to 1024 characters only.
 Never use GET method if you have password or other sensitive information to be
sent to the server.
 GET can't be used to send binary data, like images or word documents, to the
server.
 The PHP provides $_GET associative array to access all the sent information using
GET method.

Syntax:

$VariableName = $_GET[“fieldname”];

226120316067 90 | P a g e
Web Development using PHP (4341604)

Disadvantages:-
 Information trying to pass to destination file is visible in URL so it is Insecure.
 Transfer limited amount of Information.
 GET can't be used to send binary data, like images or word documents, to the
server.
 The GET method is restricted to send up to 1024 characters only.
Submit form using POST method:
 The POST method transfers information via HTTP headers.
 It will transfer Information between pages through FORM body.
 The POST method does not have any restriction on data size to be sent.
 The POST method can be used to send ASCII as well as binary data.
 The data sent by POST method goes through HTTP header so security depends on
HTTP protocol. By using Secure HTTP you can make sure that your information is
secure.
 The PHP provides $_POST associative array to access all the sent information using
POST method
 Information is transferred through FORM body, not visible to everyone. Hence
secure method.
 It allows you to transfer larger amount of data.

Syntax:

$VariableName = $_POST[“fieldname”];

Using $_Request method:


 $_REQUEST is a super global variable which is widely used to collect data after
submitting html forms.
 $_REQUEST method is used to retrieve value from URL as well as FORM collection.
 It is used to get the result from form data sent with both the GET and the POST
methods.
 PHP provides the super global variable $_REQUEST that contains the contents of
both the $_GET and $_POST variables as well as the values of
the $_COOKIE variable.

Syntax:

$VariableName = $_REQUEST[“fieldname”];

226120316067 91 | P a g e
Web Development using PHP (4341604)

H. Resources/Equipment Required

Sr. Instrument/Equipment/
Specification Quantity
No. Components/Trainer kit
Computer (i3-i5 preferable), RAM
1 Hardware: Computer System
minimum 2 GB and onwards
2 Operating System Windows/ Linux/ MAC
XAMPP server (PHP, Web server, As Per
3 Software Batch Size
Database)
Notepad, Notepad++, Sublime Text or
4 Text Editor
similar

5 Web Browser Edge, Firefox, Chrome or similar

I. Safety and necessary Precautions followed

NA

J. Source code:

A) Create student registration form using text box, check box, radio button, select,
submit button. And display user inserted value in new PHP page using GET or POST
Method.
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST["name"];
$enrollment = $_POST["enroll"];
$mobile = $_POST["mono"];
$gender = $_POST["gender"];
$language = $_POST["language"];
$courses = isset($_POST["Course"]) ? $_POST["Course"] : array();
echo "<p>Name: $name</p>";
echo "<p>Enrollment No: $enrollment</p>";
echo "<p>Mobile No: $mobile</p>";
echo "<p>Gender: $gender</p>";
echo "<p>Language: $language</p>";
if (!empty($courses)) {
echo "<p>Courses:</p>";
echo "<ul>";
foreach ($courses as $course) {
echo "<li>$course</li>";
}echo "</ul>";
} else {
echo "<p>No courses selected</p>";
}else {
echo "<p>No data submitted.</p>";
}
?>

226120316067 92 | P a g e
Web Development using PHP (4341604)

<html>
<head>
<title>Student Registration Form</title>
</head>
<body>
<h2>Student Registration Form</h2>
<form action="pr8.php" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required><br><br>
<label for="Enroll">Enrollment No:</label>
<input type="text" id="enroll" name="enroll" required><br><br>
<label for="mono">Mobile No:</label>
<input type="text" id="mono" name="mono" required><br><br>
<label for="gender">Gender:</label>
<input type="radio" id="male" name="gender" value="male">
<label for="male">Male</label>
<input type="radio" id="female" name="gender" value="female">
<label for="female">Female</label><br><br>
<label for="language">Select language:</label>
<select id="language" name="language">
<option value="Gujarati">Gujarati</option>
<option value="Hindi">Hindi</option>
<option value="Marathi">Marathi</option>
<option value="English">English</option>
</select><br><br>
<label for="course">Course:</label><br>
<input type="checkbox" id="IT" name="Course[]" value="IT">
<label for="IT"> IT</label><br>
<input type="checkbox" id="Computer" name="Course[]"
value="Computer">
<label for="Computer">Computer</label><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>

226120316067 93 | P a g e
Web Development using PHP (4341604)

B) Write a PHP script to explain the concept of $_REQUEST.

<!DOCTYPE html>
<html lang="en">
<head>

<title>Favorite Programming languages</title>


</head>
<body>
<h2>Favorite programming languages</h2>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<label>Select your favorite Coding languages:</label><br>
<input type="checkbox" id="php" name="languages[]" value="PHP">
<label for="php">PHP</label><br>
<input type="checkbox" id="HTML" name="languages[]" value="HTML">
<label for="HTML">HTML</label><br>
<input type="checkbox" id="Css" name="languages[]" value="CSS">
<label for="Css">CSS</label><br>
<input type="checkbox" id="java" name="languages[]" value="JAVA">
<label for="nick">JAVA</label><br>
<input type="checkbox" id="py" name="languages[]" value="PYTHON">
<label for="py">PYTHON</label><br>
<input type="submit" value="Submit">
</form>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (isset($_REQUEST["languages"])) {
echo "<h3>Your favorite Coding Languages:</h3>";
echo "<ul>";
foreach ($_REQUEST["languages"] as $language) {
echo "<li>$language</li>";
}
echo "</ul>";
} else {
echo "<p>No programming languages selected.</p>";
}
}
?>

</body>
</html>

226120316067 94 | P a g e
Web Development using PHP (4341604)

OUTPUT:

K. Practical related Quiz.

1. variable is used to collect form data sent with both the GET and POSTmethods.

2. should not be used while sending passwords or other sensitive


information.

3. Write any one difference between get and post method.

4. Write attributes of <form> tag.

5. For password input in form, you should use attribute and value
of <input> tag.

226120316067 95 | P a g e
Web Development using PHP (4341604)

A. References / Suggestions

1) https://www.w3schools.com/php/default.asp
2) https://www.guru99.com/php-tutorials.html
3) https://www.tutorialspoint.com/php/
4) https://tutorialehtml.com/en/php-tutorial-introduction/
5) www.tizag.com/phpT/
6) https://books.goalkicker.com/PHPBook/
7) https://spoken-tutorial.org/tutorial-
search/?search_foss=PHP+and+MySQL&search_language=English
8) https://codecourse.com/watch/php-basics
9) https://onlinecourses.swayam2.ac.in/aic20_sp32/preview

B. Assessment-Rubrics

Faculty
Marks Obtained Date
Signature
Program Implementation Student’s engagement
Correctness and Presentation in practical activities Total
(4) Methodology (3) (3) (10)
R1 R2 R3

226120316067 96 | P a g e

You might also like