0% found this document useful (0 votes)
21 views91 pages

Question Bank Answer

The document provides a comprehensive overview of PHP operators, including arithmetic, assignment, bitwise, comparison, incrementing/decrementing, logical, string, array, and execution operators. It also covers control structures in PHP, detailing various conditional statements such as if, if-else, if-elseif, nested if, and switch statements, along with examples. Additionally, it explains the concepts of call by value and call by reference in PHP functions, highlighting the advantages of using functions for code reusability and clarity.
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)
21 views91 pages

Question Bank Answer

The document provides a comprehensive overview of PHP operators, including arithmetic, assignment, bitwise, comparison, incrementing/decrementing, logical, string, array, and execution operators. It also covers control structures in PHP, detailing various conditional statements such as if, if-else, if-elseif, nested if, and switch statements, along with examples. Additionally, it explains the concepts of call by value and call by reference in PHP functions, highlighting the advantages of using functions for code reusability and clarity.
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/ 91

UNIT-1

Long Answer Questions(10M)


1.Discuss different operators available in PHP.
PHP Operators
PHP Operator is a symbol i.e used to perform operations on operands. In simple words, operators are used
to perform operations on variables or values. For example:

PHP Operators can be categorized in following forms:


 Arithmetic Operators
 Assignment Operators
 Bitwise Operators
 Comparison Operators
 Incrementing/Decrementing Operators
 Logical Operators
 String Operators
 Array Operators
 Type Operators

Arithmetic Operators
The PHP arithmetic operators are used to perform common arithmetic operations such as addition,
subtraction, etc. with numeric values.

Operator Name Example Explanation


+ Addition $a + $b Sum of operands
- Subtraction $a - $b Difference of operands
* Multiplication $a * $b Product of operands
/ Division $a / $b Quotient of operands
% Modulus $a % $b Remainder of operands
** Exponentiation $a ** $b $a raised to the power $b The exponentiation (**) operator
has been introduced in PHP 5.6.

Assignment Operators
The assignment operators are used to assign value to different variables. The basic assignment operator is
"=".

Operator Name Example Explanation


= Assign $a = $b The value of right operand is assigned to the
left operand.
+= Add then Assign $a += $b Addition same as $a = $a + $b
-= Subtract then Assign $a -= $b Subtraction same as $a = $a - $b
*= Multiply then Assign $a *= $b Multiplication same as $a = $a * $b
/= Divide then Assign(quotient) $a /= $b Find quotient same as $a = $a / $b
%= Divide then Assign(remainder) $a %= $b Find remainder same as $a = $a % $b

Bitwise Operators
The bitwise operators are used to perform bit-level operations on operands. These operators allow the
evaluation and manipulation of specific bits within the integer.
Operator Name Example Explanation
& And $a & $b Bits that are 1 in both $a and $b are set to 1, otherwise 0.
| Or (Inclusive or) $a | $b Bits that are 1 in either $a or $b are set to 1
^ Xor (Exclusive or) $a ^ $b Bits that are 1 in either $a or $b are set to 0.
~ Not ~$a Bits that are 1 set to 0 and bits that are 0 are set to 1
<< Shift left $a << $b Left shift the bits of operand $a $b steps
>> Shift right $a >> $b Right shift the bits of $a operand by $b number of places

Comparison Operators
Comparison operators allow comparing two values, such as number or string. Below the list of comparison
operators are given:

Operator Name Example Explanation


== Equal $a == $b Return TRUE if $a is equal to $b
=== Identical $a === $b Return TRUE if $a is equal to $b, and they are of same data
type
!== Not identical $a !== $b Return TRUE if $a is not equal to $b, and they are not of same
data type
!= Not equal $a != $b Return TRUE if $a is not equal to $b
<> Not equal $a <> $b Return TRUE if $a is not equal to $b
< Less than $a < $b Return TRUE if $a is less than $b
> Greater than $a > $b Return TRUE if $a is greater than $b
<= Less than or $a <= $b Return TRUE if $a is less than or equal $b
equal to
>= Greater than or $a >= $b Return TRUE if $a is greater than or equal $b
equal to
<=> Spaceship $a <=>$b Return -1 if $a is less than $b
Return 0 if $a is equal $b
Return 1 if $a is greater than $b

Incrementing/Decrementing Operators
The increment and decrement operators are used to increase and decrease the value of a variable.

Operator Name Example Explanation


++ Increment ++$a Increment the value of $a by one, then return $a
$a++ Return $a, then increment the value of $a by one
-- decrement --$a Decrement the value of $a by one, then return $a
$a-- Return $a, then decrement the value of $a by one

Logical Operators
The logical operators are used to perform bit-level operations on operands. These operators allow the
evaluation and manipulation of specific bits within the integer.

Operator Name Example Explanation


and And $a and $b Return TRUE if both $a and $b are true
Or Or $a or $b Return TRUE if either $a or $b is true
xor Xor $a xor $b Return TRUE if either $ or $b is true but not both
! Not ! $a Return TRUE if $a is not true
&& And $a && $b Return TRUE if either $a and $b are true
|| Or $a || $b Return TRUE if either $a or $b is true

String Operators
The string operators are used to perform the operation on strings. There are two string operators in PHP,
which are given below:

Operator Name Example Explanation


. Concatenation $a . $b Concatenate both $a and $b
.= Concatenation and $a .= $b First concatenate $a and $b, then assign the concatenated
Assignment string to $a, e.g. $a = $a . $b

Array Operators
The array operators are used in case of array. Basically, these operators are used to compare the values of
arrays.

Operator Name Example Explanation


+ Union $a + $y Union of $a and $b
== Equality $a == $b Return TRUE if $a and $b have same key/value pair
!= Inequality $a != $b Return TRUE if $a is not equal to $b
=== Identity $a === $b Return TRUE if $a and $b have same key/value pair of same
type in same order
!== Non-Identity $a !== $b Return TRUE if $a is not identical to $b
<> Inequality $a <> $b Return TRUE if $a is not equal to $b

Execution Operators
PHP has an execution operator backticks (``). PHP executes the content of backticks as a shell command.
Execution operator and shell_exec() give the same result.

Operator Name Example Explanation


`` backticks echo `dir`; Execute the shell command and return the result.
2.Explain about the Control Structures in PHP with Example.
PHP - Decision Making/Control Statement
PHP allows us to perform actions based on some type of conditions that may be logical or comparative.
Based on the result of these conditions i.e., either TRUE or FALSE, an action would be performed as asked
by the user. It’s just like a two- way path. If you want something then go this way or else turn that way. To
use this feature, PHP provides us with four conditional statements:
 if statement
 if…else statement
 if…elseif…else statement
 nested if Statement
 switch statement

1.if statement
The if statement allows you to execute a statement if an expression evaluates to true.
PHP evaluates the expression first. If the expression evaluates to true, PHP executes the statement. In case
the expression evaluates to false, PHP ignores the statement.

Syntax:
<?php
if ( expression ) {
statement;
}

Flowchart

Example: uses the if statement to display a message if the $is_admin variable sets to true:
File: if.php
Input:
<?php
$is_admin = true;
if ($is_admin)
echo 'Welcome, admin!';
?>

Output:
Welcome, admin!

2.if else
The if statement allows you to execute one or more statements when an expression is true:

Syntax:
<?php
if ( expression ) {
// code block
} else {
// another code block
}

Flowchart:

Example: uses the if...else statement to show a message based on the value of the $is_authenticated
variable:
File: if-else.php

Input:
<?php
$is_authenticated = false;
if ( $is_authenticated ) {
echo 'Welcome!';
} else {
echo 'You are not authorized to access this page.'
}

Output:
You are not authorized to access this page.

3.if elseif
The if statement evaluates an expression and executes a code block if the expression is true:
The if statement can have one or more optional elseif clauses. The elseif is a combination of if and else:

Syntax:
<?php
if (expression1) {
statement;
} elseif (expression2) {
statement;
} elseif (expression3) {
statement;
}

Alternative Syntax:
<?php
if (expression):
statement;
elseif (expression2):
statement;
elseif (expression3):
statement;
endif;
Flowchart:

Example: uses the if elseif statement to display whether the variable $x is greater than $y:
File: if elseif.php

Input:
<?php
$x = 10;
$y = 20;
if ($x > $y) {
$message = 'x is greater than y';
} elseif ($x < $y) {
$message = 'x is less than y';
} else {
$message = 'x is equal to y';
}
echo $message;

Output:
x is less than y
The script shows the message x is less than y as expected.

4.Nesting if statements
It’s possible to nest an if statement inside another if statement as follows:

Syntax:
if ( expression1 ) {
// do something
if( expression2 ) {
// do other things
}
}

Flowchart:

Example: shows how to nest an if statement in another if statement:


File: nested if.php

Input:
<?php
$is_admin = true;
$can_approve = true;
if ($is_admin) {
echo 'Welcome, admin!';
if ($can_approve) {
echo 'Please approve the pending items';
}
}
5.Switch
PHP executes the switch statement from the matching case label till it encounters the break statement,
you can combine several cases in one.

Syntax:
switch(expression){
case value1:
//code to be executed
break;
case value2:
//code to be executed
break;
......
default:
code to be executed if all cases are not matched;
}

Flowchart:
Example: uses the switch statement and combines the cases of 'editor' and 'author':
File: switch.php

Input:
<?php
$message = '';
$role = 'author';
switch ($role) {
case 'admin':
$message = 'Welcome, admin!';
break;
case 'editor':
case 'author':
$message = 'Welcome! Do you want to create a new article?';
break;
case 'subscriber':
$message = 'Welcome! Check out some new articles.';
break;
default:
$message = 'You are not authorized to access this page';
}
echo $message;

Output:
Welcome! Do you want to create a new article?

nested switch statement


Nested switch statement means switch statement inside another switch statement. Sometimes it leads to
confusion.
Example:
File: nested switch.php

Input:
<?php
$car = "Hyundai";
$model = "Tucson";
switch( $car )
{
case "Honda":
switch( $model )
{
case "Amaze":
echo "Honda Amaze price is 5.93 - 9.79 Lakh.";
break;
case "City":
echo "Honda City price is 9.91 - 14.31 Lakh.";
break;
}
break;
case "Renault":
switch( $model )
{
case "Duster":
echo "Renault Duster price is 9.15 - 14.83 L.";
break;
case "Kwid":
echo "Renault Kwid price is 3.15 - 5.44 L.";
break;
}
break;
case "Hyundai":
switch( $model )
{
case "Creta":
echo "Hyundai Creta price is 11.42 - 18.73 L.";
break;
case "Tucson":
echo "Hyundai Tucson price is 22.39 - 32.07 L.";
break;
case "Xcent":
echo "Hyundai Xcent price is 6.5 - 10.05 L.";
break;
}
break;
}
?>

Output:
Hyundai Tucson price is 22.39 - 32.07 L.
3.Explain Call by value and Call by Reference with Example.

Call By Value
PHP allows you to call function by value and reference both. In case of PHP call by value, actual value is not
modified if it is modified inside the function.
Let's understand the concept of call by value by the help of examples.

In this example, variable $str is passed to the adder function where it is concatenated with 'Call By Value'
string. But, printing $str variable results 'Hello' only. It is because changes are done in the local variable
$str2 only. It doesn't reflect to $str variable.

Example:
File: call by value.php

Input:
<?php
function adder($str2)
{
$str2 .= 'Call By Value';
}
$str = 'Hello ';
adder($str);
echo $str;
?>

Output:
Hello

Call By Reference
In case of PHP call by reference, actual value is modified if it is modified inside the function. In such case,
you need to use & (ampersand) symbol with formal arguments. The & represents reference of the variable.
Let's understand the concept of call by reference by the help of examples.

In this example, variable $str is passed to the adder function where it is concatenated with 'Call By
Reference' string. Here, printing $str variable results 'This is Call By Reference'. It is because changes are
done in the actual variable $str.

Example:
File: call by reference.php

Input:
<?php
function adder(&$str2)
{
$str2 .= 'Call By Reference';
}
$str = 'This is ';
adder($str);
echo $str;
?>

Output:
This is Call By Reference

PHP Functions
PHP function is a piece of code that can be reused many times. It can take input as argument list and return
value. There are thousands of built-in functions in PHP.
In PHP, we can define Conditional function, Function within Function and Recursive function also.

Advantage of PHP Functions


 Code Reusability: PHP functions are defined only once and can be invoked many times, like in other
programming languages.
 Less Code: It saves a lot of code because you don't need to write the logic many times. By the use of
function, you can write the logic only once and reuse it.
 Easy to understand: PHP functions separate the programming logic. So it is easier to understand the
flow of the application because every logic is divided in the form of functions.

PHP User-defined Functions


We can declare and call user-defined functions easily. Let's see the syntax to declare user-defined
functions.

Syntax
function functionname(){
//code to be executed
}

Note: Function name must be start with letter and underscore only like other labels in PHP. It can't be start
with numbers or special symbols.

Example: PHP Functions


File: function1.php

Input:
<?php
function sayHello(){
echo "Hello PHP Function";
}
sayHello();//calling function
?>

Output:
Hello PHP Function

PHP Function Arguments


We can pass the information in PHP function through arguments which is separated by comma.
PHP supports Call by Value (default), Call by Reference, Default argument values and Variable-length
argument list.

Let's see the example to pass single argument in PHP function.


Example:
File: functionarg.php

Input:
<?php
function sayHello($name){
echo "Hello $name<br/>";
}
sayHello("Sonoo");
sayHello("Vimal");
sayHello("John");
?>

Output:
Hello Sonoo
Hello Vimal
Hello John

PHP Call By Reference


Value passed to the function doesn't modify the actual value by default (call by value). But we can do so by
passing value as a reference.
By default, value passed to the function is call by value. To pass value as a reference, you need to use
ampersand (&) symbol before the argument name.

Let's see a simple example of call by reference in PHP.

Example:
File: functionref.php

Input:
<?php
function adder(&$str2)
{
$str2 .= 'Call By Reference';
}
$str = 'Hello ';
adder($str);
echo $str;
?>

Output:
Hello Call By Reference
PHP Function: Default Argument Value
We can specify a default argument value in function. While calling PHP function if you don't specify any
argument, it will take the default argument. Let's see a simple example of using default argument value in
PHP function.

Example:
File: functiondefaultarg.php
Input:
<?php
function sayHello($name="Sonoo"){
echo "Hello $name<br/>";
}
sayHello("Rajesh");
sayHello();//passing no value
sayHello("John");
?>

Output:
Hello Rajesh
Hello Sonoo
Hello John

PHP Function: Returning Value


Let's see an example of PHP function that returns value.
Example:
File: functionreturn.php
Input:
<?php
function cube($n){
return $n*$n*$n;
}
echo "Cube of 3 is: ".cube(3);
?>

Output:
Cube of 3 is: 27
4.Explain the following.
i).Data type ii).Variable iii).Constants iv).Strings v).Comments
1.Data Types
A type specifies the amount of memory that allocates to a value associated with it. A type also determines
the operations that you can perform on it.
PHP data types are used to hold different types of data or values.
PHP has ten primitive types including four scala types, four compound types, and two special types:
1. Scalar Types (predefined)
2. Compound Types (user-defined)
3. Special Types

Scalar Types (predefined)


It holds only single value. There are 4 scalar data types in PHP.
 boolean
 integer
 float
 string

Compound Types (user-defined)


It can hold multiple values. There are 2 compound data types in PHP.
 array
 object
 callable
 iterable

Special Types
There are 2 special data types in PHP.
 resource
 NULL
Boolean
Booleans are the simplest data type works like switch. It holds only two values: TRUE (1) or FALSE (0). It is
often used with conditional statements. If the condition is correct, it returns TRUE otherwise FALSE.
Example:
File: Boolean.php

Input:
<?php
if (TRUE)
echo "This condition is TRUE.";
if (FALSE)
echo "This condition is FALSE.";
?>

Output:
This condition is TRUE.

Integer
Integer means numeric data with a negative or positive sign. It holds only whole numbers, i.e., numbers
without fractional part or decimal points.

Rules for integer:


 An integer can be either positive or negative.
 An integer must not contain decimal point.
 Integer can be decimal (base 10), octal (base 8), or hexadecimal (base 16).
 The range of an integer must be lie between 2,147,483,648 and 2,147,483,647 i.e., -2^31 to 2^31.

Example:
File: integer.php

Input:
<?php
$dec1 = 34;
$oct1 = 0243;
$hexa1 = 0x45;
echo "Decimal number: " .$dec1. "</br>";
echo "Octal number: " .$oct1. "</br>";
echo "HexaDecimal number: " .$hexa1. "</br>";
?>

Output:
Decimal number: 34
Octal number: 163
HexaDecimal number: 69
Float
A floating-point number is a number with a decimal point. Unlike integer, it can hold numbers with a
fractional or decimal point, including a negative or positive sign.
Example:
File: float.php

Input:
<?php
$n1 = 19.34;
$n2 = 54.472;
$sum = $n1 + $n2;
echo "Addition of floating numbers: " .$sum;
?>

Output:
Addition of floating numbers: 73.812

String
A string is a non-numeric data type. It holds letters or any alphabets, numbers, and even special characters.

String values must be enclosed either within single quotes or in double quotes. But both are treated
differently. To clarify this, see the example below:
Example:
File: string.php

Input:
<?php
$company = "Javatpoint";
//both single and double quote statements will treat different
echo "Hello $company";
echo "</br>";
echo 'Hello $company';
?>

Output:
Hello Javatpoint
Hello $company

Array
An array is a compound data type. It can store multiple values of same data type in a single variable.
Example:
File: array.php

Input:
<?php
$bikes = array ("Royal Enfield", "Yamaha", "KTM");
var_dump($bikes); //the var_dump() function returns the datatype and values
echo "</br>";
echo "Array Element1: $bikes[0] </br>";
echo "Array Element2: $bikes[1] </br>";
echo "Array Element3: $bikes[2] </br>";
?>

Output:
array(3) { [0]=> string(13) "Royal Enfield" [1]=> string(6) "Yamaha" [2]=> string(3) "KTM" }
Array Element1: Royal Enfield
Array Element2: Yamaha
Array Element3: KTM
You will learn more about array in later chapters of this tutorial.

Object
Objects are the instances of user-defined classes that can store both values and functions. They must be
explicitly declared.
Example:
File: object.php

Input:
<?php
class bike {
function model() {
$model_name = "Royal Enfield";
echo "Bike Model: " .$model_name;
}
}
$obj = new bike();
$obj -> model();
?>

Output:
Bike Model: Royal Enfield
This is an advanced topic of PHP, which we will discuss later in detail.

Resource
Resources are not the exact data type in PHP. Basically, these are used to store some function calls or
references to external PHP resources. For example - a database call. It is an external resource.

This is an advanced topic of PHP, so we will discuss it later in detail with examples.

Null
Null is a special data type that has only one value: NULL. There is a convention of writing it in capital letters
as it is case sensitive.
The special type of data type NULL defined a variable with no value.
Example:
File: Null.php

Input:
<?php
$nl = NULL;
echo $nl; //it will not give any output
?>

Output:

2.Variables
Variables are "containers" for storing information.
A variable is a special container that you can define, which then “holds” a value, such as a number, string,
object, array, or a Boolean. Variables are fundamental to programming.

Creating (Declaring) PHP Variables


In PHP, a variable is declared using a $ sign followed by the variable name. Here, some important points to
know about variables:
 As PHP is a loosely typed language, so we do not need to declare the data types of the variables. It
automatically analyzes the values and makes conversions to its correct datatype.
 After declaring a variable, it can be reused throughout the code.
 Assignment Operator (=) is used to assign the value to a variable.

Rules for declaring PHP variable:


 A variable must start with a dollar ($) sign, followed by the variable name.
 A variable name cannot start with a number.
 A variable can have long descriptive names (like $factorial, $even_nos) or short names (like $n or $f or
$x)
 It can only contain alpha-numeric character and underscore (A-z, 0-9, _).
 A variable name must start with a letter or underscore (_) character and variable name cannot contain
spaces.
 One thing to be kept in mind that the variable name cannot start with a number or special symbols.
 Variable names are case-sensitive, so $name and $NAME both are treated as different variable.
 There is no size limit for variables.
 The value of a variable is the value of its most recent assignment.
 Variables are assigned with the = operator, with the variable on the left-hand side and the expression
to be evaluated on the right.
 Variables can, but do not need, to be declared before assignment.
 Variables in PHP do not have intrinsic types - a variable does not know in advance whether it will be
used to store a number or a string of characters.
 Variables used before they are assigned have default values.
 PHP does a good job of automatically converting types from one to another when necessary.
 PHP variables are Perl-like.

Syntax of declaring a variable


$variablename=value;

Example: declaring a variable


File: declaring a variable.php

Input:
<?php
$name = "Pavan Kumar";
echo $name;
?>

Output:
Pavan Kumar

Variable Scope
The scope of a variable is defined as its extent (or) range in the program under which it can be accessed. In
other words, "The scope of a variable is the portion of the program within which it is defined and can be
accessed."

In PHP, variables can be declared anywhere in the script.

The scope of a variable is the part of the script where the variable can be referenced/used.

PHP has three different variable scopes:


1. Local variable
2. Global variable
3. Static variable

1.Local variable
The variables that are declared within a function are called local variables for that function. These local
variables have their scope only in that particular function in which they are declared. This means that these
variables cannot be accessed outside the function, as they have local scope.
A variable declaration outside the function with the same name is completely different from the variable
declared inside the function.
Example:
File: local_variable1.php

Input:
<?php
function local_var()
{
$num = 45; //local variable
echo "Local variable declared inside the function is: ". $num;
}
local_var();
?>

Output:
Local variable declared inside the function is: 45

2.Global variable
The global variables are the variables that are declared outside the function. These variables can be
accessed anywhere in the program. To access the global variable within a function, use the GLOBAL
keyword before the variable. However, these variables can be directly accessed or used outside the
function without any keyword. Therefore there is no need to use any keyword to access a global variable
outside the function.
Example:
File: global_variable1.php

Input:
<?php
$num = 20;
// function to demonstrate use of global variable
function global_var()
{
// we have to use global keyword before
// the variable $num to access within
// the function
global $num;
echo "Variable num inside function : $num \n";
}
global_var();
echo "Variable num outside function : $num \n";
?>

Output:
Variable num inside function : 20
Variable num outside function : 20

3.Static variable
It is a feature of PHP to delete the variable, once it completes its execution and memory is freed.
Sometimes we need to store a variable even after completion of function execution. Therefore, another
important feature of variable scoping is static variable. We use the static keyword before the variable to
define a variable, and this variable is called as static variable.
Static variables exist only in a local function, but it does not free its memory after the program execution
leaves the scope. Understand it with the help of an example:

Example:
File: static_variable.php

Input:
<?php
function static_var()
{
static $num1 = 3; //static variable
$num2 = 6; //Non-static variable
//increment in non-static variable
$num1++;
//increment in static variable
$num2++;
echo "Static: " .$num1 ."</br>";
echo "Non-static: " .$num2 ."</br>";
}

//first function call


static_var();

//second function call


static_var();
?>

Output:
Static: 4
Non-static: 7
Static: 5
Non-static: 7

You have to notice that $num1 regularly increments after each function call, whereas $num2 does not. This
is why because $num1 is not a static variable, so it freed its memory after the execution of each function
call.

2.2Superglobal Variables
In addition to global variables of your own creation, PHP has several predefined variables called
superglobals.These variables are always present, and their values are available to all your scripts. Each of
the following superglobals is actually an array of other variables:
 $GLOBALS
 $_SERVER
 $_REQUEST
 $_GET
 $_POST
 $_SESSION
 $_COOKIE
 $_FILES
 $_ENV
 $_PHP_SELF
 $php_errormsg$php_errormsg

3.Constants
PHP constants are name or identifier that can't be changed during the execution of the script except for
magic constants, which are not really constants. PHP constants can be defined by 2 ways:
Using define() function
Using const keyword

define()
Use the define() function to create a constant. It defines constant at run time. Let's see the syntax of
define() function in PHP.

Syntax:
define(name, value, case-insensitive)
name: It specifies the constant name.
value: It specifies the constant value.
case-insensitive: Specifies whether a constant is case-insensitive. Default value is false. It means it is case
sensitive by default.

Example: to define PHP constant using define().


File: constant1.php

Input:
<?php
define("MESSAGE","Hello JavaTpoint PHP");
echo MESSAGE;
?>

Output:
Hello JavaTpoint PHP
Create a constant with case-insensitive name:

Constant() function
There is another way to print the value of constants using constant() function instead of using the echo
statement.

Syntax:
The syntax for the following constant function:
constant (name)
Example:
File: constant5.php

Input:
<?php
define("MSG", "JavaTpoint");
echo MSG, "</br>";
echo constant("MSG");
//both are similar
?>

Output:
JavaTpoint
JavaTpoint

5.Comments
PHP comments can be used to describe any line of code so that other developer can understand the code
easily. It can also be used to hide any code.
PHP supports single line and multi line comments.

Single Line Comments


There are two ways to use single line comments in PHP.
Example:
File: comment.php

Input:
// (C++ style single line comment)
# (Unix Shell style single line comment)
<?php
// this is C++ style single line comment
# this is Unix Shell style single line comment
echo "Welcome to PHP single line comments";
?>

Output:
Welcome to PHP single line comments

PHP Multi Line Comments


In PHP, we can comments multiple lines also. To do so, we need to enclose all lines within /* */. Let's see a
simple example of PHP multiple line comment.
Example:
File: multi comments.php

Input:
<?php
/*
Anything placed
within comment
will not be displayed
on the browser;
*/
echo "Welcome to PHP multi line comment";
?>
Output:

Welcome to PHP multi line comment


Very Short Answer Questions(2M)
1.How to define PHP Variable.
1.Variables are "containers" for storing information.
2.A variable is a special container that you can define, which then “holds” a value, such as a number, string,
object, array, or a Boolean. Variables are fundamental to programming.

Syntax of declaring a variable


$variablename=value;

Example: declaring a variable


File: declaring a variable.php

Input:
<?php
$name = "Pavan Kumar";
echo $name;
?>

Output:
Pavan Kumar

2.Define default parameters.


The default parameter concept comes from C++ style default argument values, same as in PHP you can
provide default parameters so that when a parameter is not passed to the function. Then it is still available
within the function with a pre-defined value. This function also can be called optional parameter.
Syntax:
function greeting($name=" parameter_value ")

Parameter: This function accepts a single parameter that is $name here, holds the parameter value. Below
examples illustrate the procedure to create and use the default function parameter: Example 1:

Example: parameter
File: parameter.php

Input:
<?php
function greeting($name="GeeksforGeeks")
{
echo "Welcome to $name ";
echo("\n");
}
greeting("Gfg");

// Passing no value
greeting();
greeting("A Computer Science Portal");
?>
Output:
Welcome to Gfg
Welcome to GeeksforGeeks
Welcome to A Computer Science Portal

3.How to define a Constant.


PHP constants are name or identifier that can't be changed during the execution of the script except for
magic constants, which are not really constants. PHP constants can be defined by 2 ways:
1. Using define() function
2. Using const keyword

4.Define Static Scope of a Variable.


Static variable
It is a feature of PHP to delete the variable, once it completes its execution and memory is freed.
Sometimes we need to store a variable even after completion of function execution. Therefore, another
important feature of variable scoping is static variable. We use the static keyword before the variable to
define a variable, and this variable is called as static variable.

Static variables exist only in a local function, but it does not free its memory after the program execution
leaves the scope.
UNIT-II
Long Answer Questions(10M)
1.Define Array.Write about Array related functions with examples.
PHP Arrays
PHP array is an ordered map (contains value on the basis of key). It is used to hold multiple values of
similar type in a single variable.

Advantage of PHP Array


 Less Code: We don't need to define multiple variables.
 Easy to traverse: By the help of single loop, we can traverse all the elements of an array.
 Sorting: We can sort the elements of array.

PHP Array Types


There are 3 types of array in PHP.
1. Indexed Array
2. Associative Array
3. Multidimensional Array

PHP Indexed Array


PHP index is represented by number which starts from 0. We can store number, string and object in the
PHP array. All PHP array elements are assigned to an index number by default.

There are two ways to define indexed array:

Definition
1st way:
$season=array(“summer”,”winter”,”spring”,”autumn”);
2nd way:
$season[0]=”summer”;
$season[1]=”winter”;
$season[2]=”spring”;
$season[3]=”autumn”;

Example
File: array1.php
Input:
<?php
$season=array(“summer”,”winter”,”spring”,”autumn”);
echo “Season are: $season[0], $season[1], $season[2] and $season[3]”;
?>

Output:
Season are: summer, winter, spring and autumn

PHP Associative Array


We can associate name with each array elements in PHP using => symbol.
There are two ways to define associative array:

Definition
1st way:
$salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");
2nd way:
$salary["Sonoo"]="350000";
$salary["John"]="450000";
$salary["Kartik"]="200000";

Example
File: arrayassociative1.php
Input:
<?php
$salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");
echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";
echo "John salary: ".$salary["John"]."<br/>";
echo "Kartik salary: ".$salary["Kartik"]."<br/>";
?>

Output:
Sonoo salary: 350000
John salary: 450000
Kartik salary: 200000

PHP Multidimensional Array


PHP multidimensional array is also known as array of arrays. It allows you to store tabular data in an array.
PHP multidimensional array can be represented in the form of matrix which is represented by row *
column.

Definition
$emp = array
(
array(1,"sonoo",400000),
array(2,"john",500000),
array(3,"rahul",300000)
);

Example
File: multiarray.php
Input:
<?php
$emp = array
(
array(1,"sonoo",400000),
array(2,"john",500000),
array(3,"rahul",300000)
);

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


for ($col = 0; $col < 3; $col++) {
echo $emp[$row][$col]." ";
}
echo "<br/>";
}
?>

Output:
1 sonoo 400000
2 john 500000
3 rahul 300000

Array-Related Constructs and Functions


More than 70 array-related functions are built in to PHP,Some of the more common (and useful) functions
are described

. count() and sizeof()—Each of these functions counts the number of elements in an array; they are aliases
of each other. Given the following array
$colors = array(“blue”, “black”, “red”, “green”);
both count($colors); and sizeof($colors); return a value of 4.

. each() and list()—These functions (well, list() is a language construct that looks like a function) usually
appear together, in the context of stepping through an array and returning its keys and values.
You saw an example of this previously, where we stepped through the $c array and printed its contents.

. foreach()—This control structure (that looks like a function) is used to step through an array, assigning
the value of an element to a given variable, as you saw in the previous section.
Some Array-Related Constructs and Functions 145

. reset()—This function rewinds the pointer to the beginning of an array, as in this example:
reset($character);
This function proves useful when you are performing multiple manipulations on an array, such as sorting,
extracting values, and so forth.

. array_push()—This function adds one or more elements to the end of an existing array, as in this
example:
array_push($existingArray, “element 1”, “element 2”, “element 3”);

. array_pop()—This function removes (and returns) the last element of an existing array, as in this
example:
$last_element = array_pop($existingArray);

. array_unshift()—This function adds one or more elements to the beginning of an existing array, as in this
example:
array_unshift($existingArray, “element 1”, “element 2”, “element 3”);

. array_shift()—This function removes (and returns) the first element of an existing array, as in this
example, where the value of the element in the first position of $existingArray is assigned to the variable
$first_element:
$first_element = array_shift($existingArray);

. array_merge()—This function combines two or more existing arrays, as in this example:


$newArray = array_merge($array1, $array2);

. array_keys()—This function returns an array containing all the key names within a given array, as in this
example:
$keysArray = array_keys($existingArray);

. array_values()—This function returns an array containing all the values within a given array, as in this
example:
$valuesArray = array_values($existingArray);

. shuffle()—This function randomizes the elements of a given array. The syntax of this function is simply as
follows:
shuffle($existingArray);

2.What is String.Discuss about String Functions used in PHP.


PHP String
PHP string is a sequence of characters i.e., used to store and manipulate text. PHP supports only 256-
character set and so that it does not offer native Unicode support. There are 4 ways to specify a string
literal in PHP.
1. single quoted
2. double quoted
3. heredoc syntax
4. newdoc syntax (since PHP 5.3)

Single Quoted
We can create a string in PHP by enclosing the text in a single-quote. It is the easiest way to specify string
in PHP.

For specifying a literal single quote, escape it with a backslash (\) and to specify a literal backslash (\) use
double backslash (\\). All the other instances with backslash such as \r or \n, will be output same as they
specified instead of having any special meaning.

Following some examples are given to understand the single quoted PHP String in a better way:
Example
1. File: single quoted.php
Input:
<?php
$str='Hello text within single quote';
echo $str;
?>

Output:
Hello text within single quote
We can store multiple line text, special characters, and escape sequences in a single-quoted PHP string.

Double Quoted
In PHP, we can specify string through enclosing text within double quote also. But escape sequences and
variables will be interpreted using double quote PHP strings.

Example
File: double quote.php
Input:
<?php
$str="Hello text within double quote";
echo $str;
?>

Output:
Hello text within double quote
Now, you can't use double quote directly inside double quoted string.

Heredoc
Heredoc syntax (<<<) is the third way to delimit strings. In Heredoc syntax, an identifier is provided after
this heredoc <<< operator, and immediately a new line is started to write any text. To close the quotation,
the string follows itself and then again that same identifier is provided. That closing identifier must begin
from the new line without any whitespace or tab.

Naming Rules
The identifier should follow the naming rule that it must contain only alphanumeric characters and
underscores, and must start with an underscore or a non-digit character.

Valid Example
Example
File: Valid.php
Input:
<?php
$str = <<<Demo
It is a valid example
Demo; //Valid code as whitespace or tab is not valid before closing identifier
echo $str;
?>

Output:
It is a valid example

Invalid Example
We cannot use any whitespace or tab before and after the identifier and semicolon, which means identifier
must not be indented. The identifier must begin from the new line.
Example
File: Invalid.php
Input:
<?php
$str = <<<Demo
It is Invalid example
Demo; //Invalid code as whitespace or tab is not valid before closing identifier
echo $str;
?>
This code will generate an error.

Output:
Parse error: syntax error, unexpected end of file in C:\xampp\htdocs\xampp\PMA\heredoc.php on line 7
Heredoc is similar to the double-quoted string, without the double quote, means that quote in a heredoc
are not required. It can also print the variable's value.

Newdoc
Newdoc is similar to the heredoc, but in newdoc parsing is not done. It is also identified with three less
than symbols <<< followed by an identifier. But here identifier is enclosed in single-quote, e.g. <<<'EXP'.
Newdoc follows the same rule as heredocs.
The difference between newdoc and heredoc is that - Newdoc is a single-quoted string whereas heredoc is
a double-quoted string.

Note: Newdoc works as single quotes.

Example
File: Newdoc.php
Input:
<?php
$str = <<<'DEMO'
Welcome to javaTpoint.
Learn with newdoc example.
DEMO;
echo $str;
echo '</br>';

echo <<< 'Demo' // Here we are not storing string content in variable str.
Welcome to javaTpoint.
Learn with newdoc example.
Demo;
?>

Output:
Welcome to javaTpoint. Learn with newdoc example.
Welcome to javaTpoint. Learn with newdoc example.
Go to view page source and see the source of the program.

String Functions
In this chapter we will look at some commonly used functions to manipulate strings.
1) PHP strtolower() function
The strtolower() function returns string in lowercase letter.

Syntax
string strtolower ( string $string )

Example
File: strtolower.php
Input:
<?php
$str="My name is KHAN";
$str=strtolower($str);
echo $str;
?>

Output:
my name is khan
2) PHP strtoupper() function
The strtoupper() function returns string in uppercase letter.

Syntax
string strtoupper ( string $string )

Example
File: strtoupper.php
Input:
<?php
$str="My name is KHAN";
$str=strtoupper($str);
echo $str;
?>

Output:
MY NAME IS KHAN

3) PHP ucfirst() function


The ucfirst() function returns string converting first character into uppercase. It doesn't change the case of
other characters.

Syntax
string ucfirst ( string $str )

Example
File: ucfirst.php
Input:
<?php
$str="my name is KHAN";
$str=ucfirst($str);
echo $str;
?>

Output:
My name is KHAN

4) PHP lcfirst() function


The lcfirst() function returns string converting first character into lowercase. It doesn't change the case of
other characters.

Syntax
string lcfirst ( string $str )

Example
File: lcfirst.php
Input:
<?php
$str="MY name IS KHAN";
$str=lcfirst($str);
echo $str;
?>

Output:
mY name IS KHAN

5) PHP ucwords() function


The ucwords() function returns string converting first character of each word into uppercase.

Syntax
string ucwords ( string $str )

Example
File: ucwords.php
Input:
<?php
$str="my name is Sonoo jaiswal";
$str=ucwords($str);
echo $str;
?>

Output:
My Name Is Sonoo Jaiswal

6) PHP strrev() function


The strrev() function returns reversed string.

Syntax
string strrev ( string $string )

Example
File: strrev.php
Input:
<?php
$str="my name is Sonoo jaiswal";
$str=strrev($str);
echo $str;
?>
Output:
lawsiaj oonoS si eman ym

7) PHP strlen() function


The strlen() function returns length of the string.
Syntax
int strlen ( string $string )

Example
File: strlen.php
Input:
<?php
$str="my name is Sonoo jaiswal";
$str=strlen($str);
echo $str;
?>
Output:
24

8)str_word_count() - Count Words in a String


The PHP str_word_count() function counts the number of words in a string.

Example
File: str_word_count.php
Input:
<?php
echo str_word_count("Hello world!"); // outputs 2
?>

9)strpos() - Search For a Text Within a String


The PHP strpos() function searches for a specific text within a string. If a match is found, the function
returns the character position of the first match. If no match is found, it will return FALSE.

Example
File: strpos.php
Input:
<?php
echo strpos("Hello world!", "world"); // outputs 6
?>
Tip: The first character position in a string is 0 (not 1).

10)str_replace() - Replace Text Within a String


The PHP str_replace() function replaces some characters with some other characters in a string.

Example
File: str_replace.php
Input:
<?php
echo str_replace("world", "Dolly", "Hello world!"); // outputs Hello Dolly!
?>

3.State/List various Date and Time functions in PHP with Example.


PHP Date and Time
The PHP date() function is used to format a date and/or a time.

The PHP Date() Function


The PHP date() function formats a timestamp to a more readable date and time.

Syntax
date(format,timestamp)
Parameter Description
format Required. Specifies the format of the timestamp
timestamp Optional. Specifies a timestamp. Default is the current date and time
A timestamp is a sequence of characters, denoting the date and/or time at which a certain event occurred.

Get a Date
The required format parameter of the date() function specifies how to format the date (or time).

Here are some characters that are commonly used for dates:
d - Represents the day of the month (01 to 31)
m - Represents a month (01 to 12)
Y - Represents a year (in four digits)
l (lowercase 'L') - Represents the day of the week
Other characters, like"/", ".", or "-" can also be inserted between the characters to add additional
formatting.

The example below formats today's date in three different ways:


Example
File: today's date.php
Input:
<?php
echo "Today is " . date("Y/m/d") . "<br>";
echo "Today is " . date("Y.m.d") . "<br>";
echo "Today is " . date("Y-m-d") . "<br>";
echo "Today is " . date("l");
?>

PHP Tip - Automatic Copyright Year


Use the date() function to automatically update the copyright year on your website:

Example
File: automatically update the copyright year.php
Input:
&copy; 2010-<?php echo date("Y");?>

Get a Time
Here are some characters that are commonly used for times:
H - 24-hour format of an hour (00 to 23)
h - 12-hour format of an hour with leading zeros (01 to 12)
i - Minutes with leading zeros (00 to 59)
s - Seconds with leading zeros (00 to 59)
a - Lowercase Ante meridiem and Post meridiem (am or pm)

The example below outputs the current time in the specified format:
Example
File: current time.php
Input:
<?php
echo "The time is " . date("h:i:sa");
?>

Note that the PHP date() function will return the current date/time of the server!

Get Your Time Zone


If the time you got back from the code is not correct, it's probably because your server is in another
country or set up for a different timezone.
So, if you need the time to be correct according to a specific location, you can set the timezone you want
to use.

The example below sets the timezone to "America/New_York", then outputs the current time in the
specified format:
Example
File: timezone.php
Input:
<?php
date_default_timezone_set("America/New_York");
echo "The time is " . date("h:i:sa");
?>

Create a Date With mktime()


The optional timestamp parameter in the date() function specifies a timestamp. If omitted, the current
date and time will be used (as in the examples above).
The PHP mktime() function returns the Unix timestamp for a date. The Unix timestamp contains the
number of seconds between the Unix Epoch (January 1 1970 00:00:00 GMT) and the time specified.

Syntax
mktime(hour, minute, second, month, day, year)

The example below creates a date and time with the date() function from a number of parameters in the
mktime() function:
Example
File: mktime.php
Input:
<?php
$d=mktime(11, 14, 54, 8, 12, 2014);
echo "Created date is " . date("Y-m-d h:i:sa", $d);
?>

Create a Date From a String With strtotime()


The PHP strtotime() function is used to convert a human readable date string into a Unix timestamp (the
number of seconds since January 1 1970 00:00:00 GMT).

Syntax
strtotime(time, now)

The example below creates a date and time from the strtotime() function:
Example
File: strtotime.php
Input:
<?php
$d=strtotime("10:30pm April 15 2014");
echo "Created date is " . date("Y-m-d h:i:sa", $d);
?>

PHP is quite clever about converting a string to a date, so you can put in various values:
Example
File: string to a date.php
Input:
<?php
$d=strtotime("tomorrow");
echo date("Y-m-d h:i:sa", $d) . "<br>";

$d=strtotime("next Saturday");
echo date("Y-m-d h:i:sa", $d) . "<br>";

$d=strtotime("+3 Months");
echo date("Y-m-d h:i:sa", $d) . "<br>";
?>

However, strtotime() is not perfect, so remember to check the strings you put in there.

4.How to implement Object Orientation in PHP.


We can imagine our universe made of different objects like sun, earth, moon etc. Similarly we can imagine
our car made of different objects like wheel, steering, gear etc. Same way there is object oriented
programming concepts which assume everything as an object and implement a software using different
objects.

Object Oriented Concepts


Before we go in detail, lets define important terms related to Object Oriented Programming.

Class − This is a programmer-defined data type, which includes local functions as well as local data. You can
think of a class as a template for making many instances of the same kind (or class) of object.

Object − An individual instance of the data structure defined by a class. You define a class once and then
make many objects that belong to it. Objects are also known as instance.

Member Variable − These are the variables defined inside a class. This data will be invisible to the outside
of the class and can be accessed via member functions. These variables are called attribute of the object
once an object is created.

Member function − These are the function defined inside a class and are used to access object data.

Inheritance − When a class is defined by inheriting existing function of a parent class then it is called
inheritance. Here child class will inherit all or few member functions and variables of a parent class.

Parent class − A class that is inherited from by another class. This is also called a base class or super class.

Child Class − A class that inherits from another class. This is also called a subclass or derived class.

Polymorphism − This is an object oriented concept where same function can be used for different
purposes. For example function name will remain same but it take different number of arguments and can
do different task.

Overloading − a type of polymorphism in which some or all of operators have different implementations
depending on the types of their arguments. Similarly functions can also be overloaded with different
implementation.

Data Abstraction − Any representation of data in which the implementation details are hidden
(abstracted).

Encapsulation − refers to a concept where we encapsulate all the data and member functions together to
form an object.

Constructor − refers to a special type of function which will be called automatically whenever there is an
object formation from a class.

Destructor − refers to a special type of function which will be called automatically whenever an object is
deleted or goes out of scope.
Defining PHP Classes
The general form for defining a new class in PHP is as follows −

Example
File: class.php
Input:
<?php
class phpClass {
var $var1;
var $var2 = "constant string";

function myfunc ($arg1, $arg2) {


[..]
}
[..]
}
?>

Here is the description of each line −


 The special form class, followed by the name of the class that you want to define.
 A set of braces enclosing any number of variable declarations and function definitions.
 Variable declarations start with the special form var, which is followed by a conventional $ variable
name; they may also have an initial assignment to a constant value.
 Function definitions look much like standalone PHP functions but are local to the class and will be
used to set and access object data.

Here is an example which defines a class of Books type −


Example
File: class.php
Input:
<?php
class Books {
/* Member variables */
var $price;
var $title;

/* Member functions */
function setPrice($par){
$this->price = $par;
}

function getPrice(){
echo $this->price ."<br/>";
}

function setTitle($par){
$this->title = $par;
}

function getTitle(){
echo $this->title ." <br/>";
}
}
?>
The variable $this is a special variable and it refers to the same object ie. itself.

Creating Objects in PHP


Once you defined your class, then you can create as many objects as you like of that class type. Following is
an example of how to create object using new operator.

Example
File: class.php
Input:
$physics = new Books;
$maths = new Books;
$chemistry = new Books;

Here we have created three objects and these objects are independent of each other and they will have
their existence separately. Next we will see how to access member function and process member
variables.

Calling Member Functions


After creating your objects, you will be able to call member functions related to that object. One member
function will be able to process member variable of related object only.

Following example shows how to set title and prices for the three books by calling member functions.
Example
File: class.php
Input:
$physics->setTitle( "Physics for High School" );
$chemistry->setTitle( "Advanced Chemistry" );
$maths->setTitle( "Algebra" );

$physics->setPrice( 10 );
$chemistry->setPrice( 15 );
$maths->setPrice( 7 );

Now you call another member functions to get the values set by in above example −
$physics->getTitle();
$chemistry->getTitle();
$maths->getTitle();
$physics->getPrice();
$chemistry->getPrice();
$maths->getPrice();
This will produce the following result −
Physics for High School
Advanced Chemistry
Algebra
10
15
7

Constructor Functions
Constructor Functions are special type of functions which are called automatically whenever an object is
created. So we take full advantage of this behaviour, by initializing many things through constructor
functions.

PHP provides a special function called __construct() to define a constructor. You can pass as many as
arguments you like into the constructor function.

Following example will create one constructor for Books class and it will initialize price and title for the
book at the time of object creation.

function __construct( $par1, $par2 ) {


$this->title = $par1;
$this->price = $par2;
}

Now we don't need to call set function separately to set price and title. We can initialize these two
member variables at the time of object creation only. Check following example below −
Example
File: class.php
Input:
$physics = new Books( "Physics for High School", 10 );
$maths = new Books ( "Advanced Chemistry", 15 );
$chemistry = new Books ("Algebra", 7 );

/* Get those set values */


$physics->getTitle();
$chemistry->getTitle();
$maths->getTitle();

$physics->getPrice();
$chemistry->getPrice();
$maths->getPrice();

This will produce the following result −


Physics for High School
Advanced Chemistry
Algebra
10
15
7

Destructor
Like a constructor function you can define a destructor function using function __destruct(). You can
release all the resources with-in a destructor.

Inheritance
PHP class definitions can optionally inherit from a parent class definition by using the extends clause. The
syntax is as follows −

class Child extends Parent {


<definition body>
}

The effect of inheritance is that the child class (or subclass or derived class) has the following
characteristics −
Automatically has all the member variable declarations of the parent class.
Automatically has all the same member functions as the parent, which (by default) will work the same way
as those functions do in the parent.

Following example inherit Books class and adds more functionality based on the requirement.
Example
File: class.php
Input:
class Novel extends Books {
var $publisher;

function setPublisher($par){
$this->publisher = $par;
}

function getPublisher(){
echo $this->publisher. "<br />";
}
}
Now apart from inherited functions, class Novel keeps two additional member functions.

Function Overriding
Function definitions in child classes override definitions with the same name in parent classes. In a child
class, we can modify the definition of a function inherited from parent class.

In the following example getPrice and getTitle functions are overridden to return some values.
Example
File: class.php
Input:
function getPrice() {
echo $this->price . "<br/>";
return $this->price;
}

function getTitle(){
echo $this->title . "<br/>";
return $this->title;
}

Public Members
Unless you specify otherwise, properties and methods of a class are public. That is to say, they may be
accessed in three possible situations −
From outside the class in which it is declared
From within the class in which it is declared
From within another class that implements the class in which it is declared
Till now we have seen all members as public members. If you wish to limit the accessibility of the members
of a class then you define class members as private or protected.

Private members
By designating a member private, you limit its accessibility to the class in which it is declared. The private
member cannot be referred to from classes that inherit the class in which it is declared and cannot be
accessed from outside the class.

A class member can be made private by using private keyword infront of the member.
Example
File: class.php
Input:
class MyClass {
private $car = "skoda";
$driver = "SRK";

function __construct($par) {
// Statements here run every time
// an instance of the class
// is created.
}

function myPublicFunction() {
return("I'm visible!");
}

private function myPrivateFunction() {


return("I'm not visible outside!");
}
}
When MyClass class is inherited by another class using extends, myPublicFunction() will be visible, as will
$driver. The extending class will not have any awareness of or access to myPrivateFunction and $car,
because they are declared private.

Protected members
A protected property or method is accessible in the class in which it is declared, as well as in classes that
extend that class. Protected members are not available outside of those two kinds of classes. A class
member can be made protected by using protected keyword in front of the member.

Here is different version of MyClass −


Example
File: class.php
Input:
class MyClass {
protected $car = "skoda";
$driver = "SRK";

function __construct($par) {
// Statements here run every time
// an instance of the class
// is created.
}

function myPublicFunction() {
return("I'm visible!");
}

protected function myPrivateFunction() {


return("I'm visible in child class!");
}
}

Interfaces
Interfaces are defined to provide a common function names to the implementers. Different implementors
can implement those interfaces according to their requirements. You can say, interfaces are skeletons
which are implemented by developers.

As of PHP5, it is possible to define an interface, like this −

interface Mail {
public function sendMail();
}
Then, if another class implemented that interface, like this −

class Report implements Mail {


// sendMail() Definition goes here
}
Constants
A constant is somewhat like a variable, in that it holds a value, but is really more like a function because a
constant is immutable. Once you declare a constant, it does not change.

Declaring one constant is easy, as is done in this version of MyClass −


Example
File: class.php
Input:
class MyClass {
const requiredMargin = 1.7;

function __construct($incomingValue) {
// Statements here run every time
// an instance of the class
// is created.
}
}

In this class, requiredMargin is a constant. It is declared with the keyword const, and under no
circumstances can it be changed to anything other than 1.7. Note that the constant's name does not have a
leading $, as variable names do.

Abstract Classes
An abstract class is one that cannot be instantiated, only inherited. You declare an abstract class with the
keyword abstract, like this −

When inheriting from an abstract class, all methods marked abstract in the parent's class declaration must
be defined by the child; additionally, these methods must be defined with the same visibility.

abstract class MyAbstractClass {


abstract function myAbstractFunction() {
}
}

Note that function definitions inside an abstract class must also be preceded by the keyword abstract. It is
not legal to have abstract function definitions inside a non-abstract class.

Static Keyword
Declaring class members or methods as static makes them accessible without needing an instantiation of
the class. A member declared as static can not be accessed with an instantiated class object (though a
static method can).

Try out following example −


Example
File: class.php
Input:
<?php
class Foo {
public static $my_static = 'foo';

public function staticValue() {


return self::$my_static;
}
}

print Foo::$my_static . "\n";


$foo = new Foo();

print $foo->staticValue() . "\n";


?>

Final Keyword
PHP 5 introduces the final keyword, which prevents child classes from overriding a method by prefixing the
definition with final. If the class itself is being defined final then it cannot be extended.

Following example results in Fatal error: Cannot override final method BaseClass::moreTesting()
Example
File: class.php
Input:
<?php

class BaseClass {
public function test() {
echo "BaseClass::test() called<br>";
}

final public function moreTesting() {


echo "BaseClass::moreTesting() called<br>";
}
}

class ChildClass extends BaseClass {


public function moreTesting() {
echo "ChildClass::moreTesting() called<br>";
}
}
?>

Calling parent constructors


Instead of writing an entirely new constructor for the subclass, let's write it by calling the parent's
constructor explicitly and then doing whatever is necessary in addition for instantiation of the subclass.
Here's a simple example −
Example
File: class.php
Input:
class Name {
var $_firstName;
var $_lastName;

function Name($first_name, $last_name) {


$this->_firstName = $first_name;
$this->_lastName = $last_name;
}

function toString() {
return($this->_lastName .", " .$this->_firstName);
}
}
class NameSub1 extends Name {
var $_middleInitial;

function NameSub1($first_name, $middle_initial, $last_name) {


Name::Name($first_name, $last_name);
$this->_middleInitial = $middle_initial;
}

function toString() {
return(Name::toString() . " " . $this->_middleInitial);
}
}

In this example, we have a parent class (Name), which has a two-argument constructor, and a subclass
(NameSub1), which has a three-argument constructor. The constructor of NameSub1 functions by calling
its parent constructor explicitly using the :: syntax (passing two of its arguments along) and then setting an
additional field. Similarly, NameSub1 defines its non constructor toString() function in terms of the parent
function that it overrides.

NOTE − A constructor can be defined with the same name as the name of a class. It is defined in above
example.

Very Short Answer Questions(2M)


1.What is an Associated Array.
PHP Associative Array
PHP allows you to associate name/label with each array elements in PHP using => symbol. Such way, you
can easily remember the element because each element is represented by label than an incremented
number.

Definition
There are two ways to define associative array:

1st way:
$salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");

2nd way:
$salary["Sonoo"]="550000";
$salary["Vimal"]="250000";
$salary["Ratan"]="200000";

2.How to Objects in PHP.


Object:
1. A class defines an individual instance of the data structure. We define a class once and then make
many objects that belong to it. Objects are also known as an instance.
2. An object is something that can perform a set of related activities.

Syntax:
<?php
class MyClass
{
// Class properties and methods go here
}
$obj = new MyClass;
var_dump($obj);
?>

3.List different type specifiers in Printf function.


PHP Print
Like PHP echo, PHP print is a language construct, so you don't need to use parenthesis with the argument
list. Print statement can be used with or without parentheses: print and print(). Unlike echo, it always
returns 1.

Syntax of PHP print is given below:


int print(string $arg)

PHP print statement can be used to print the string, multi-line strings, escaping characters, variable, array,
etc. Some important points that you must know about the echo statement are:
 print is a statement, used as an alternative to echo at many times to display the output.
 print can be used with or without parentheses.
 print always returns an integer value, which is 1.
 Using print, we cannot pass multiple arguments.
 print is slower than the echo statement.
4.How to Create a Class in PHP.
Class:
1. A class is an entity that determines how an object will behave and what the object will contain. In other
words, it is a blueprint or a set of instruction to build a specific type of object.
2. In PHP, declare a class using the class keyword, followed by the name of the class and a
set of curly braces ({}).

Syntax to Create Class in PHP


<?php
class MyClass
{
// Class properties and methods go here
}
?>

UNIT-III
Long Answer Questions(10M)
1.Explain how to access information in form fields.
Dynamic Websites
The Websites provide the functionalities that can use to store, update, retrieve, and delete the data in a
database.

What is the Form?


A Document that containing black fields, that the user can fill the data or user can select the data.Casually
the data will store in the data base

PHP Form Handling


We can create and use forms in PHP. To get form data, we need to use PHP superglobals $_GET and
$_POST.
There are two ways the browser client can send information to the web server.
 The GET Method
 The POST Method
Before the browser sends the information, it encodes it using a scheme called URL encoding. In this
scheme, name/value pairs are joined with equal signs and different pairs are separated by the ampersand.

name1=value1&name2=value2&name3=value3

Spaces are removed and replaced with the + character and any other nonalphanumeric characters are
replaced with a hexadecimal values. After the information is encoded it is sent to the server.

The GET Method


The GET method sends the encoded user information appended to the page request. The page and the
encoded information are separated by the ? character.

http://www.test.com/index.htm?name1=value1&name2=value2

 The GET method produces a long string that appears in your server logs, in the browser's Location:
box.
 The GET method is restricted to send upto 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 data sent by GET method can be accessed using QUERY_STRING environment variable.
 The PHP provides $_GET associative array to access all the sent information using GET method.

Example:
File: GET.php

Input:
<?php
if( $_GET["name"] || $_GET["age"] ) {
echo "Welcome ". $_GET['name']. "<br />";
echo "You are ". $_GET['age']. " years old.";
exit();
}
?>
<html>
<body>
<form action = "<?php $_PHP_SELF ?>" method = "GET">
Name: <input type = "text" name = "name" />
Age: <input type = "text" name = "age" />
<input type = "submit" />
</form>
</body>
</html>

Output:

The POST Method


The POST method transfers information via HTTP headers. The information is encoded as described in case
of GET method and put into a header called QUERY_STRING.

 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.

Example:
File: POST.php

Input:
<?php
if( $_POST["name"] || $_POST["age"] ) {
if (preg_match("/[^A-Za-z'-]/",$_POST['name'] )) {
die ("invalid name and name should be alpha");
}
echo "Welcome ". $_POST['name']. "<br />";
echo "You are ". $_POST['age']. " years old.";
exit();
}
?>

<html>
<body>
<form action = "<?php $_PHP_SELF ?>" method = "POST">
Name: <input type = "text" name = "name" />
Age: <input type = "text" name = "age" />
<input type = "submit" />
</form>
</body>
</html>
Output:

The $_REQUEST variable


The PHP $_REQUEST variable contains the contents of both $_GET, $_POST, and $_COOKIE. We will discuss
$_COOKIE variable when we will explain about cookies.

The PHP $_REQUEST variable can be used to get the result from form data sent with both the GET and
POST methods.

Example:
File: REQUEST.php

Input:
<?php
if( $_REQUEST["name"] || $_REQUEST["age"] ) {
echo "Welcome ". $_REQUEST['name']. "<br />";
echo "You are ". $_REQUEST['age']. " years old.";
exit();
}
?>
<html>
<body>
<form action = "<?php $_PHP_SELF ?>" method = "POST">
Name: <input type = "text" name = "name" />
Age: <input type = "text" name = "age" />
<input type = "submit" />
</form>
</body>
</html>
Here $_PHP_SELF variable contains the name of self script in which it is being called.

Output:

2.i).Explain how cookies are set, view and deleted.


ii).Explain how variables are handled in session.
Cookies
PHP cookie is a small piece of information which is stored at client browser. It is used to recognize the user.
Cookie is created at server side and saved to client browser. Each time when client sends request to the
server, cookie is embedded with request. Such way, cookie can be received at the server side.

In short, cookie can be created, sent and received at server end.


There are three steps involved in identifying returning users −
 Server script sends a set of cookies to the browser. For example name, age, or identification
number etc.
 Browser stores this information on local machine for future use.
 When next time browser sends any request to web server then it sends those cookies information
to the server and server uses that information to identify the user.

Note: PHP Cookie must be used before <html> tag.

Setting Cookies with PHP


PHP provided setcookie() function to set a cookie. This function requires upto six arguments and should be
called before <html> tag. For each cookie this function has to be called separately.
setcookie() function
PHP setcookie() function is used to set cookie with HTTP response. Once cookie is set, you can access it by
$_COOKIE superglobal variable.

Syntax
setcookie(name, value, expire, path, domain, security);

Here is the detail of all the arguments −


 Name − This sets the name of the cookie and is stored in an environment variable called
HTTP_COOKIE_VARS. This variable is used while accessing cookies.
 Value − This sets the value of the named variable and is the content that you actually want to store.
 Expiry − This specify a future time in seconds since 00:00:00 GMT on 1st Jan 1970. After this time
cookie will become inaccessible. If this parameter is not set then cookie will automatically expire
when the Web Browser is closed.
 Path − This specifies the directories for which the cookie is valid. A single forward slash character
permits the cookie to be valid for all directories.
 Domain − This can be used to specify the domain name in very large domains and must contain at
least two periods to be valid. All cookies are only valid for the host and domain which created them.
 Security − This can be set to 1 to specify that the cookie should only be sent by secure transmission
using HTTPS otherwise set to 0 which mean cookie can be sent by regular HTTP.

Syntax
setcookie("CookieName", "CookieValue");/* defining name and value only*/
setcookie("CookieName", "CookieValue", time()+1*60*60);//using expiry in 1 hour(1*60*60 seconds or
3600 seconds)
setcookie("CookieName", "CookieValue", time()+1*60*60, "/mypath/", "mydomain.com", 1);

Accessing Cookies with PHP


PHP provides many ways to access cookies. Simplest way is to use either $_COOKIE or
$HTTP_COOKIE_VARS variables.

PHP $_COOKIE
PHP $_COOKIE superglobal variable is used to get cookie.

Syntax
$value=$_COOKIE["CookieName"];//returns cookie value

Example:
File: COOKIE.php

Input:
<?php
setcookie("user", "Sonoo");
?>
<html>
<body>
<?php
if(!isset($_COOKIE["user"])) {
echo "Sorry, cookie is not found!";
} else {
echo "<br/>Cookie Value: " . $_COOKIE["user"];
}
?>
</body>
</html>

Output:
Sorry, cookie is not found!

Firstly cookie is not set. But, if you refresh the page, you will see cookie is set now.
Output:
Cookie Value: Sonoo

PHP Delete Cookie


If you set the expiration date in past, cookie will be deleted.

Example:
File: COOKIE1.php

Input:
<?php
setcookie ("CookieName", "", time() - 3600);// set the expiration date to one hour ago
?>

Sessions
PHP session is used to store and pass information from one page to another temporarily (until user close
the website).

PHP session technique is widely used in shopping websites where we need to store and pass cart
information e.g. username, product code, product name, product price etc from one page to another.

PHP session creates unique user id for each browser to recognize the user and avoid conflict between
multiple browsers.

When a session is started following things happen −


 PHP first creates a unique identifier for that particular session which is a random string of 32
hexadecimal numbers such as 3c7foj34c3jj973hjkop2fc937e3443.
 A cookie called PHPSESSID is automatically sent to the user's computer to store unique session
identification string.
 A file is automatically created on the server in the designated temporary directory and bears the
name of the unique identifier prefixed by sess_ ie sess_3c7foj34c3jj973hjkop2fc937e3443.
 When a PHP script wants to retrieve the value from a session variable, PHP automatically gets the
unique session identifier string from the PHPSESSID cookie and then looks in its temporary directory
for the file bearing that name and a validation can be done by comparing both values.
 A session ends when the user loses the browser or after leaving the site, the server will terminate
the session after a predetermined period of time, commonly 30 minutes duration.

Starting a PHP Session


A PHP session is easily started by making a call to the session_start() function.This function first checks if a
session is already started and if none is started then it starts one. It is recommended to put the call to
session_start() at the beginning of the page.
Session variables are stored in associative array called $_SESSION[]. These variables can be accessed during
lifetime of a session.
The following example starts a session then register a variable called counter that is incremented each
time the page is visited during the session.
Make use of isset() function to check if session variable is already set or not.
Put this code in a test.php file and load this file many times to see the result −

session_start() function
PHP session_start() function is used to start the session. It starts a new or resumes existing session. It
returns existing session if session is created already. If session is not available, it creates and returns new
session.

Syntax
bool session_start ( void )
session_start();

PHP $_SESSION
PHP $_SESSION is an associative array that contains all session variables. It is used to set and get session
variable values.

Example: Store information


$_SESSION["user"] = "Sachin";

Example: Get information


echo $_SESSION["user"];

Example:
File: session1.php

Input:
<?php
session_start();
?>
<html>
<body>
<?php
$_SESSION["user"] = "Sachin";
echo "Session information are set successfully.<br/>";
?>
<a href="session2.php">Visit next page</a>
</body>
</html>

Example:
File: session2.php

Input:
<?php
session_start();
?>
<html>
<body>
<?php
echo "User is: ".$_SESSION["user"];
?>
</body>
</html>
PHP Session Counter Example
File: sessioncounter.php
<?php
session_start();

if (!isset($_SESSION['counter'])) {
$_SESSION['counter'] = 1;
} else {
$_SESSION['counter']++;
}
echo ("Page Views: ".$_SESSION['counter']);
?>

Destroying a PHP Session


A PHP session can be destroyed by session_destroy() function. This function does not need any argument
and a single call can destroy all the session variables. If you want to destroy a single session variable then
you can use unset() function to unset a session variable.
PHP session_destroy() function is used to destroy all session variables completely.

Example:
File: session3.php

Input:
<?php
session_start();
session_destroy();
?>

Sessions without cookies


There may be a case when a user does not allow to store cookies on their machine. So there is another
method to send session ID to the browser.

Alternatively, you can use the constant SID which is defined if the session started. If the client did not send
an appropriate session cookie, it has the form session_name=session_id. Otherwise, it expands to an
empty string. Thus, you can embed it unconditionally into URLs.

The following example demonstrates how to register a variable, and how to link correctly to another page
using SID.

Example:
File: session4.php

Input:
<?php
session_start();

if (isset($_SESSION['counter'])) {
$_SESSION['counter'] = 1;
}else {
$_SESSION['counter']++;
}

$msg = "You have visited this page ". $_SESSION['counter'];


$msg .= "in this session.";

echo ( $msg );
?>

<p>
To continue click following link <br />

<a href = "nextpage.php?<?php echo htmlspecialchars(SID); ?>">


</p>
It will produce the following result −

You have visited this page 1in this session.


To continue click following link
The htmlspecialchars() may be used when printing the SID in order to prevent XSS related attacks.

3.How to redirect the user to a new page.


Redirection from one page to another in PHP is commonly achieved using the following two ways:
Using Header Function in PHP:
The header() function is an inbuilt function in PHP which is used to send the raw HTTP (Hyper Text Transfer
Protocol) header to the client.

Syntax:
header( $header, $replace, $http_response_code )

Parameters: This function accepts three parameters as mentioned above and described below:

 $header: This parameter is used to hold the header string.


 $replace: This parameter is used to hold the replace parameter which indicates the header should
replace a previous similar header, or add a second header of the same type. It is optional
parameter.
 $http_response_code: This parameter hold the HTTP response code.

Example:
File: illustrates the header.php

Input:
<?php

// Redirect browser
header("Location: https://www.geeksforgeeks.org");

exit;
?>

Note: The die() or exit() function after header is mandatory. If die() or exit() is not put after the
header(‘Location: ….’) then script may continue resulting in unexpected behavior. For example, result in
content being disclosed that actually wanted to prevent with the redirect (HTTP 301).

Using JavaScript via PHP:


The windows.location object in JavaScript is used to get the current page address(URL) and to redirect the
browser to a new page. The window.location object contains the crucial information about a page such as
hostname, href, pathname, port etc.

Example:
File: illustrates the header java.php

Input:
<html>
<head>
<title>window.location function</title>
</head>
<body>
<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML =
"URL: " + window.location.href +"</br>";
document.getElementById("demo").innerHTML =
document.getElementById("demo").innerHTML +
"Hostname: " + window.location.hostname + "</br>";
document.getElementById("demo").innerHTML =
document.getElementById("demo").innerHTML +
"Protocol: " + window.location.protocol + "</br>";
</script>
</body>
</html>
Output:

URL: https://ide.geeksforgeeks.org/tryit.php
Hostname: ide.geeksforgeeks.org
Protocol: https:

4.How to build HTML forms and PHP code that send mail.
Sending Emails using PHP
PHP must be configured correctly in the php.ini file with the details of how your system sends email. Open
php.ini file available in /etc/ directory and find the section headed [mail function].
Windows users should ensure that two directives are supplied. The first is called SMTP that defines your
email server address. The second is called sendmail_from which defines your own email address.

The configuration for Windows should look something like this −


[mail function]
; For Win32 only.
SMTP = smtp.secureserver.net

; For win32 only


sendmail_from = [email protected]
Linux users simply need to let PHP know the location of their sendmail application. The path and any
desired switches should be specified to the sendmail_path directive.

The configuration for Linux should look something like this −


[mail function]
; For Win32 only.
SMTP =

; For win32 only


sendmail_from =

; For Unix only


sendmail_path = /usr/sbin/sendmail -t -i
Now you are ready to go −

Sending plain text email


PHP makes use of mail() function to send an email. This function requires three mandatory arguments that
specify the recipient's email address, the subject of the the message and the actual message additionally
there are other two optional parameters.

Syntax:
mail( to, subject, message, headers, parameters );

Here is the description for each parameters.

Sr.No Parameter & Description


1 To
Required. Specifies the receiver / receivers of the email
2 Subject
Required. Specifies the subject of the email. This parameter cannot contain any newline
characters
3 Message
Required. Defines the message to be sent. Each line should be separated with a LF (\n). Lines
should not exceed 70 characters
4 Headers
Optional. Specifies additional headers, like From, Cc, and Bcc. The additional headers should be
separated with a CRLF (\r\n)
5 Parameters
Optional. Specifies an additional parameter to the send mail program

As soon as the mail function is called PHP will attempt to send the email then it will return true if successful
or false if it is failed.

Multiple recipients can be specified as the first argument to the mail() function in a comma separated list.
Sending HTML email
When you send a text message using PHP then all the content will be treated as simple text. Even if you
will include HTML tags in a text message, it will be displayed as simple text and HTML tags will not be
formatted according to HTML syntax. But PHP provides option to send an HTML message as actual HTML
message.

While sending an email message you can specify a Mime version, content type and character set to send an
HTML email.

Example:
File: sending an email message.php

Input:
Following example will send an HTML email message to [email protected] copying it to
[email protected]. You can code this program in such a way that it should receive all content from
the user and then it should send an email.

<html>

<head>
<title>Sending HTML email using PHP</title>
</head>

<body>

<?php
$to = "[email protected]";
$subject = "This is subject";

$message = "<b>This is HTML message.</b>";


$message .= "<h1>This is headline.</h1>";

$header = "From:[email protected] \r\n";


$header .= "Cc:[email protected] \r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-type: text/html\r\n";

$retval = mail ($to,$subject,$message,$header);

if( $retval == true ) {


echo "Message sent successfully...";
}else {
echo "Message could not be sent...";
}
?>

</body>
</html>
Very Short Answer Questions(2M)
1.what function starts the session in PHP.
Starting a PHP Session
A PHP session is easily started by making a call to the session_start() function.This function first checks if a
session is already started and if none is started then it starts one. It is recommended to put the call to
session_start() at the beginning of the page.
Session variables are stored in associative array called $_SESSION[]. These variables can be accessed during
lifetime of a session.

session_start() function
PHP session_start() function is used to start the session. It starts a new or resumes existing session. It
returns existing session if session is created already. If session is not available, it creates and returns new
session.

Syntax
bool session_start ( void )
session_start();
2.Define Cookie.
Cookies
PHP cookie is a small piece of information which is stored at client browser. It is used to recognize the user.

Cookie is created at server side and saved to client browser. Each time when client sends request to the
server, cookie is embedded with request. Such way, cookie can be received at the server side.

In short, cookie can be created, sent and received at server end.


There are three steps involved in identifying returning users −
 Server script sends a set of cookies to the browser. For example name, age, or identification
number etc.
 Browser stores this information on local machine for future use.
 When next time browser sends any request to web server then it sends those cookies information
to the server and server uses that information to identify the user.

Note: PHP Cookie must be used before <html> tag.

3.write the function name to find current Session ID.


PHP - session_id() Function
Sessions or session handling is a way to make the data available across various pages of a web application.
The session_id() function is used to set or retrieve a custom id to the current.

Syntax
session_id([$id]);

Example:
File: sending an email message.php

Input:
<html>
<head>
<title>Setting up a PHP session</title>
</head>
<body>
<?php
//Starting the session
session_start();
$id = session_id();
print("Session Id: ".$id);
?>
</body>
</html>

Output:
Session Id: b9t3gprjtl35ms4sm937hj7s30

4.How to Combine HTML with PHP code on a single page.


Combining HTML and PHP Code on a Single Page
 Write PHP code with HTML code on a single page as on hard copy.
 More flexibility to write the entire page dynamically.
 For this use a PHP_SELF variable is in the action field of the <form> tag.
 The action field of the FORM instructs where to submit the form data when the user presses the
“submit” button.
 The same PHP page as the handler for the form as well.
 The action field of form use to switch to control to other page but Using PHP_SELF variable do not
need to edit the action field.

UNIT-IV
Long Answer Questions(10M)
1.Explain about file handling function in PHP with an example.
File Handling In PHP
PHP File System allows us to create a file, read file line by line, read file character by character, write a file,
append file, delete a file and close file.
PHP Open File - fopen()
The PHP fopen() function is used to open a file.

Syntax
fopen(filename,mode,include_path,context)

Example
File: Open File.php
Input:
<?php
$handle = fopen("c:foldermyfile.txt", "r");
?>
click for more details

PHP Close File - fclose()


The PHP fclose() function is used to close an open file pointer.

Syntax
fclose(file)

Example
File: fclose.php
Input:
<?php
$file = fopen("mytest.txt","r");
//some code to be executed
fclose($file);
?>
PHP Read File - fread()
The PHP fread() function is used to read the content of the file. It accepts two arguments: resource and file
size.

Syntax
fread(file,length)

Parameter Description
file Required. Specifies the open file to read from
length Required. Specifies the maximum number of bytes to read

Example
File: Read 10 bytes from file.php
Input:
<?php
$file = fopen("test.txt","r");
fread($file,"10");
fclose($file);
?>
Output :
hello php file

Example 2
File: Read entire file.php
Input:
<?php
$file = fopen("test.txt","r");
fread($file,filesize("test.txt"));
fclose($file);
?>

PHP Write File - fwrite()


The PHP fwrite() function is used to write content of the string into file.

Syntax
fwrite(file,string,length)

Example
File: fwrite.php
Input:
<?php
$fp = fopen("data.txt", "w");//open file in write mode
fwrite($fp, "hello");
fwrite($fp, "php file");
fclose($fp);
echo "File written successfully";
?>
Output :
File written successfully

PHP Delete File - unlink()


The PHP unlink() function is used to delete the file.

Syntax
unlink(filename,context)

Parameter Description
filename Required. Specifies the file to delete
context Optional. Specifies the context of the filehandle. Context is a set of options that can modify
the behavior of a stream

Example
File: unlink.php
Input:
<?php
unlink("data.txt");
echo "File deleted successfully";
?>
click for more details

PHP rename() Function


The rename() function renames a file or directory.
This function returns TRUE on success or FALSE on failure.

Syntax
rename(oldname,newname,context)

Parameter Description
oldname Required. Specifies the file or directory to be renamed
newname Required. Specifies the new name of the file or directory
context Optional. Specifies the context of the filehandle. Context is a set of options that can modify
the behavior of a stream

Example
File: rename.php
Input:
<?php
rename("images","pictures");
?>
2.Write a PHP Program to create a Pie-Chart.
Getting Fancy with Pie Charts
The previous examples were a little boring, but they introduced you to the basic process of creating
images: defining the canvas, defining the colors, and then drawing and filling. You can use this same
sequence of events to expand your scripts to create charts and graphs, using either static or dynamic data
for the data points.Listing 14.3 draws a basic pie chart. Lines 1–10 look similar to the previous listings
because they just set up the canvas size and colors to be used.

A Basic Pie Chart


1: <?php
2: //create the canvas
3: $myImage = ImageCreate(300,300);
4:
5: //set up some colors for use on the canvas
6: $white = ImageColorAllocate($myImage, 255, 255, 255);
7: $red = ImageColorAllocate($myImage, 255, 0, 0);
8: $green = ImageColorAllocate($myImage, 0, 255, 0);
9: $blue = ImageColorAllocate($myImage, 0, 0, 255);
10:
11: //draw a pie
12: ImageFilledArc($myImage, 100, 100, 200, 150, 0, 90, $red, IMG_ARC_PIE);
13: ImageFilledArc($myImage, 100, 100, 200, 150, 90, 180 , $green,IMG_ARC_PIE);
14: ImageFilledArc($myImage, 100, 100, 200, 150, 180, 360 , $blue,
IMG_ARC_PIE);
15:
16: //output the image to the browser
17: header (“Content-type: image/png”);
18: ImagePng($myImage);
19:
20: //clean up after yourself
21: ImageDestroy($myImage);
22: ?>

Because the first defined color is white, the color of the canvas will be white.Lines 12–14 use the
ImageFilledArc() function, which has several attributes:
. The image identifier
. The partial ellipse centered at x
. The partial ellipse centered at y
. The partial ellipse width
. The partial ellipse height
. The partial ellipse start point
. The partial ellipse end point
. Color
. Style

Look at line 14 from Listing 14.3:


14: ImageFilledArc($myImage, 100, 100, 200, 150, 180, 360 , $blue,IMG_ARC_PIE);

The arc should be filled with the defined color $blue and should use the
IMG_ARC_PIE style. The IMG_ARC_PIE style is one of several built-in styles (actually,defined constants)
used in the display; this one says to create a rounded edge.You can learn about all the predefined image-
related constants in the PHPManual, at http://us2.php.net/manual/en/image.constants.php.Save this
listing as imagecreatepie.php and place it in the document root of your web server. When accessed, it
should look something like Figure 14.3, but in color.
You can extend the code in Listing 14.3 and give your pie a 3D appearance. To do so, define three more
colors for the edge. These colors can be either lighter or darker than the base colors, as long as they
provide some contrast. The following examples define lighter colors:
$lt_red = ImageColorAllocate($myImage, 255, 150, 150);
$lt_green = ImageColorAllocate($myImage, 150, 255, 150);
$lt_blue = ImageColorAllocate($myImage, 150, 150, 255);
To create the shading effect, you use a for loop to add a series of small arcs at the points (100,110) to
(100,101), using the lighter colors as fill colors:
for ($i = 110;$i > 100;$i--) {
ImageFilledArc ($myImage, 100, $i, 200, 150, 0, 90, $lt_red, IMG_ARC_PIE);
ImageFilledArc ($myImage, 100, $i, 200, 150, 90, 180, $lt_green,
IMG_ARC_PIE);
ImageFilledArc ($myImage, 100, $i, 200, 150, 180, 360, $lt_blue,
IMG_ARC_PIE);
}
Listing 14.4 shows the code used for a 3D pie.
LISTING 14.4 A 3D Pie Chart
1: <?php
2: //create the canvas
3: $myImage = ImageCreate(300,300);
4:
5: //set up some colors for use on the canvas
6: $white = ImageColorAllocate($myImage, 255, 255, 255);
7: $red = ImageColorAllocate($myImage, 255, 0, 0);
8: $green = ImageColorAllocate($myImage, 0, 255, 0);
9: $blue = ImageColorAllocate($myImage, 0,0, 255);
10: $lt_red = ImageColorAllocate($myImage, 255, 150, 150); 11:$lt_green=ImageColorAllocate($myImage,
150, 255, 150);
12: $lt_blue = ImageColorAllocate($myImage, 150,150, 255); 13: 14: //draw the shaded area
15: for ($i = 110;$i > 100;$i--) {
16: ImageFilledArc ($myImage,100,$i,200,150,0,90,$lt_red,IMG_ARC_PIE);
17: ImageFilledArc ($myImage,100,$i,200,150,90,180,$lt_green,IMG_ARC_PIE);
18: ImageFilledArc ($myImage,100,$i,200,150,180,360,$lt_blue,IMG_ARC_PIE);
19: }
20:
21: //draw a pie
22: ImageFilledArc($myImage, 100, 100, 200, 150, 0, 90, $red, IMG_ARC_PIE);
23: ImageFilledArc($myImage, 100, 100, 200, 150, 90, 180 , $green, IMG_ARC_PIE);
24: ImageFilledArc($myImage, 100, 100, 200, 150, 180, 360 , $blue, IMG_ARC_PIE);
25:
26: //output the image to the browser
27: header (“Content-type: image/png”);
28: ImagePng($myImage);
29:
30: //clean up after yourself
31: ImageDestroy($myImage);
32: ?>
Save this listing as imagecreate3dpie.php and place it in the document root of your web server. When
accessed, it should look something like Figure 14.4, but in color.
3.Explain the following using files in PHP.
i).Read ii).Write or append iii).Lock
PHP Open File
PHP fopen() function is used to open file or URL and returns resource. The fopen() function accepts two
arguments: $filename and $mode. The $filename represents the file to be opended and $mode represents
the file mode for example read-only, read-write, write-only etc.

Syntax
resource fopen ( string $filename , string $mode [, bool $use_include_path = false [, resource $context ]] )

PHP Open File Mode


Mode Description
r Opens file in read-only mode. It places the file pointer at the beginning of the file.
r+ Opens file in read-write mode. It places the file pointer at the beginning of the file.
w Opens file in write-only mode. It places the file pointer to the beginning of the file and truncates
the file to zero length. If file is not found, it creates a new file.
w+ Opens file in read-write mode. It places the file pointer to the beginning of the file and truncates
the file to zero length. If file is not found, it creates a new file.
a Opens file in write-only mode. It places the file pointer to the end of the file. If file is not found,
it creates a new file.
a+ Opens file in read-write mode. It places the file pointer to the end of the file. If file is not found,
it creates a new file.
x Creates and opens file in write-only mode. It places the file pointer at the beginning of the file. If
file is found, fopen() function returns FALSE.
x+ It is same as x but it creates and opens file in read-write mode.
c Opens file in write-only mode. If the file does not exist, it is created. If it exists, it is neither
truncated (as opposed to 'w'), nor the call to this function fails (as is the case with 'x'). The file
pointer is positioned on the beginning of the file
c+ It is same as c but it opens file in read-write mode.

Example
File: fopen.php
Input:
<?php
$handle = fopen("c:\\folder\\file.txt", "r");
?>

PHP Read File


PHP provides various functions to read data from file. There are different functions that allow you to read
all file data, read data line by line and read data character by character.

The available PHP file read functions are given below.


 fread()
 fgets()
 fgetc()

PHP Read File - fread()


The PHP fread() function is used to read data of the file. It requires two arguments: file resource and file
size.

Syntax
string fread (resource $handle , int $length )

$handle represents file pointer that is created by fopen() function.


$length represents length of byte to be read.

Example
File: fread.php
Input:
<?php
$filename = "c:\\file1.txt";
$fp = fopen($filename, "r");//open file in read mode

$contents = fread($fp, filesize($filename));//read file

echo "<pre>$contents</pre>";//printing data of file


fclose($fp);//close file
?>

Output
this is first line
this is another line
this is third line

PHP Read File - fgets()


The PHP fgets() function is used to read single line from the file.

Syntax
string fgets ( resource $handle [, int $length ] )

Example
File: fgets.php
Input:
<?php
$fp = fopen(“c:\\file1.txt”, “r”);//open file in read mode
echo fgets($fp);
fclose($fp);
?>

Output
this is first line

PHP Read File - fgetc()


The PHP fgetc() function is used to read single character from the file. To get all data using fgetc() function,
use !feof() function inside the while loop.

Syntax
string fgetc ( resource $handle )

Example
File: fgetc.php
Input:
<?php
$fp = fopen("c:\\file1.txt", "r");//open file in read mode
while(!feof($fp)) {
echo fgetc($fp);
}
fclose($fp);
?>

Output
this is first line this is another line this is third line

PHP Write File


PHP fwrite() and fputs() functions are used to write data into file. To write data into file, you need to use w,
r+, w+, x, x+, c or c+ mode.

PHP Write File - fwrite()


The PHP fwrite() function is used to write content of the string into file.

Syntax
int fwrite ( resource $handle , string $string [, int $length ] )

Example
File: fwrite.php
Input:
<?php
$fp = fopen('data.txt', 'w');//opens file in write-only mode
fwrite($fp, 'welcome ');
fwrite($fp, 'to php file write');
fclose($fp);
echo "File written successfully";
?>

Output: data.txt
welcome to php file write

PHP Overwriting File


If you run the above code again, it will erase the previous data of the file and writes the new data. Let's see
the code that writes only new data into data.txt file.

Example
File: Overwriting File.php
Input:
<?php
$fp = fopen('data.txt', 'w');//opens file in write-only mode
fwrite($fp, 'hello');
fclose($fp);

echo "File written successfully";


?>
Output: data.txt
Hello
PHP Append to File
You can append data into file by using a or a+ mode in fopen() function. Let's see a simple example that
appends data into data.txt file.

Let's see the data of file first.

data.txt
welcome to php file write

PHP Append to File – fwrite()


The PHP fwrite() function is used to write and append data into file.

Example
File: append data.php
Input:
<?php
$fp = fopen('data.txt', 'a');//opens file in append mode
fwrite($fp, ' this is additional text ');
fwrite($fp, 'appending data');
fclose($fp);

echo "File appended successfully";


?>

Output: data.txt
welcome to php file write this is additional text appending data

PHP Delete File


In PHP, we can delete any file using unlink() function. The unlink() function accepts one argument only: file
name. It is similar to UNIX C unlink() function.

PHP unlink() generates E_WARNING level error if file is not deleted. It returns TRUE if file is deleted
successfully otherwise FALSE.

Syntax
bool unlink ( string $filename [, resource $context ] )

$filename represents the name of the file to be deleted.

Example
File: unlink.php
Input:
<?php
$status=unlink('data.txt');
if($status){
echo "File deleted successfully";
}else{
echo "Sorry!";
}
?>

Output
File deleted successfully

flock() function in PHP


PHPProgrammingServer Side Programming
The flock() function locks or releases a file. The function returns TRUE on success and FALSE on failure.

Syntax
flock(file_pointer, operation, block)

Parameters
 file_pointer − A file pointer for open file to lock or release.
 operation − Specifies the lock to use:
o LOCK_SH - Shared lock (reader)
o LOCK_EX - Exclusive lock (writer)
o LOCK_UN - Release a shared or exclusive lock
o block − Set to 1 if the lock would block

Return
The flock() function returns.

TRUE on success
FALSE on failure

Example
File: flock.php
Input:
<?php
$file_pointer = fopen("new.txt","w+");
// shared lock
if (flock($file_pointer,LOCK_SH)) {
fwrite($file_pointer,"Some content");
flock($file_pointer,LOCK_UN);
} else {
echo "Locking of file shows an error!";
}
fclose($file_pointer);
?>
Output
TRUE
4.How do you run Shell commands in PHP.
PHP | shell_exec() vs exec() Function
shell_exec() Function
The shell_exec() function is an inbuilt function in PHP which is used to execute the commands via shell and
return the complete output as a string. The shell_exec is an alias for the backtick operator, for those used
to *nix. If the command fails return NULL and the values are not reliable for error checking.

Syntax:
string shell_exec( $cmd )

Parameters: This function accepts single parameter $cmd which is used to hold the command that will be
executed.

Return Value: This function returns the executed command or NULL if an error occurred.

Note: This function is disabled when PHP is running in safe mode.


Example
File: shell_exec.php
Input:
<?php

// Use ls command to shell_exec


// function
$output = shell_exec('ls');

// Display the list of all file


// and directory
echo "<pre>$output</pre>";
?>

Output:
gfg.php
index.html
geeks.php

exec() Function
The exec() function is an inbuilt function in PHP which is used to execute an external program and returns
the last line of the output. It also returns NULL if no command run properly.

Syntax:
string exec( $command, $output, $return_var )

Parameters: This function accepts three parameters as mentioned above and described below:
$command: This parameter is used to hold the command which will be executed.
$output: This parameter is used to specify the array which will be filled with every line of output from the
command.
$return_var: The $return_var parameter is present along with the output argument, then it returns the
status of the executed command will be written to this variable.
Return Value: This function returns the executed command, be sure to set and use the output parameter.

Example
File: shell_exec2.php
Input:
<?php
// (on a system with the "iamexecfunction" executable in the path)
echo exec('iamexecfunction');
?>

Output:
geeks.php
Very Short Answer Questions(2M)
1.List various include family functions.
2.What function checks existence of a file or Directory.
3.How do you open a directory for reading.
4.How do you determine the size of a file.
UNIT-V
Long Answer Questions(10M)
1.Explain the Procedure to connect MySQL with PHP.
PHP MySQL Connect
PHP provides mysql_connect function to open a database connection. This function takes five parameters
and returns a MySQL link identifier on success, or FALSE on failure.

Syntax
mysqli_connect (server, username, password)

Sr.No Parameter Description


1 servername The host name running database server. If not specified then default value is
localhost:3306.
2 username The username accessing the database. If not specified then default is the name of
the user that owns the server process.
3 Password The password of the user accessing the database. If not specified then default is
an empty password.
4 database
5 new_link If a second call is made to mysql_connect() with the same arguments, no new
connection will be established; instead, the identifier of the already opened
connection will be returned.
6 client_flags A combination of the following constants –
MYSQL_CLIENT_SSL − Use SSL encryption
MYSQL_CLIENT_COMPRESS − Use compression protocol
MYSQL_CLIENT_IGNORE_SPACE − Allow space after function names
MYSQL_CLIENT_INTERACTIVE − Allow interactive timeout seconds of inactivity
before closing the connection

Closing Database Connection


Its simplest function mysql_close PHP provides to close a database connection. This function takes
connection resource returned by mysql_connect function. It returns TRUE on success or FALSE on failure.

Syntax
bool mysql_close ( resource $link_identifier );
If a resource is not specified then last opend database is closed.

Example
File: connect.php
Input:
<?php
$servername="localhost";
$username="root";
$password="";
$conn = mysql_connect($dbhost, $dbuser, $dbpass);

// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo Connected to Database';
mysql_close($conn);
?>
2.Discuss with MYSQL and PHP.
i).Data Insertion ii).Data Deletion iii).Data Retrieving
Example
File: student.php
Input:
<html>
<body>
<form action="insert1.php" method="post">
Enter Roll Number:<input type="text" name="rno"> <br>
Enter Name :<input type="text" name="sname"> <br>
Enter Total :<input type="text" name="total"> <br>
<input type="submit" name="submit" value="Insert">
<input type="submit" formaction="delete.php" name="del" value="Delete">
<input type="submit" formaction="update.php" name="update" value="update">
<input type="submit" formaction="search.php" name="find" value="find">
</form>
</body>
</html>
Creating a Database
To create and delete a database you should have admin privilege. Its very easy to create a new MySQL
database. PHP uses mysql_query function to create a MySQL database. This function takes two parameters
and returns TRUE on success or FALSE on failure.

Syntax
bool mysql_query( sql, connection );

Sr.No Parameter Description


1 sql Required - SQL query to create a database

2 Connection Optional - if not specified then last opend connection by mysql_connect will
be used.

Example
File: Creating a Database.php
Input:
<?php
$servername="localhost";
$username="root";
$password="";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected to Database";
// Create database
$sql="create database mccs";
// Check database created
if ($conn->query($sql) === TRUE) {
echo "Database created successfully";
} else {
echo "Error creating database: " . $conn->error;
}
$conn->close();
?>

Creating Database Tables


To create tables in the new database you need to do the same thing as creating the database. First create
the SQL query to create the tables then execute the query using mysql_query() function.

Example
File: table.php
Input:
<?php
$servername="localhost";
$username="root";
$password="";
$dbname = "mccs"
// Create connection
$conn = new mysqli($servername, $username, $password,$dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected to Database";
// Create table
$sql="create table Marks(rno int(4) primary key,name char(20),total int(3))";

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


echo "Table created successfully";
} else {
echo "Error creating table: " . $conn->error;
}
$conn->close();
?>

i).Data Insertion
Example
File: insert.php
Input:
<?php
$servername="localhost";
$username="root";
$password="";
// Create connection
$conn = new mysqli($servername, $username, $password,"mccs");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected to Database";
$id=$_POST['rno'];
$name=$_POST['sname'];
$tot=$_POST['total'];

$sql="insert into marks values(1209,'Jagathi',687)";

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


echo "New Record added successfully";
} else {
echo "Error in adding new record to table: " . $conn->error;
}
$conn->close();
?>

ii).Data Deletion
Example
File: delete.php
Input:
<?php
$servername="localhost";
$username="root";
$password="";
// Create connection
$conn = new mysqli($servername, $username, $password,"mccs");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected to Database";
$id=(int)$_POST['rno'];
$name=$_POST['sname'];
$tot=(int)$_POST['total'];

$sql="delete from marks where rno=$id";

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


echo "Deleted successfully";
} else {
echo "Error in deletion from table: " . $conn->error;
}

$conn->close();
?>

iii).Data Retrieving
Data can be fetched from MySQL tables by executing SQL SELECT statement through PHP function
mysql_query. You have several options to fetch data from MySQL.

The most frequently used option is to use function mysql_fetch_array(). This function returns row as an
associative array, a numeric array, or both. This function returns FALSE if there are no more rows.

MYSQL_ASSOC is used as the second argument to mysql_fetch_array(), so that it returns the row as an
associative array. With an associative array you can access the field by using their name instead of using
the index.
PHP provides another function called mysql_fetch_assoc() which also returns the row as an associative
array.

3.How to Create an Online Address Book.

Very Short Answer Questions(2M)


1.How will you connect to a MySQL database using PHP.
2.Which PHP Functions counts the number of records in a resultset.
3.What function retrieves the text of a MYSQL error message.

You might also like