Question Bank Answer
Question Bank Answer
Arithmetic Operators
The PHP arithmetic operators are used to perform common arithmetic operations such as addition,
subtraction, etc. with numeric values.
Assignment Operators
The assignment operators are used to assign value to different variables. The basic assignment operator is
"=".
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:
Incrementing/Decrementing Operators
The increment and decrement operators are used to increase and decrease the value of a variable.
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.
String Operators
The string operators are used to perform the operation on strings. There are two string operators in PHP,
which are given below:
Array Operators
The array operators are used in case of array. Basically, these operators are used to compare the values of
arrays.
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.
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:
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?
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.
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.
Input:
<?php
function sayHello(){
echo "Hello PHP Function";
}
sayHello();//calling function
?>
Output:
Hello PHP Function
Input:
<?php
function sayHello($name){
echo "Hello $name<br/>";
}
sayHello("Sonoo");
sayHello("Vimal");
sayHello("John");
?>
Output:
Hello Sonoo
Hello Vimal
Hello John
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
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
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.
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.
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."
The scope of a variable is the part of the script where the variable can be referenced/used.
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>";
}
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.
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.
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
Input:
<?php
/*
Anything placed
within comment
will not be displayed
on the browser;
*/
echo "Welcome to PHP multi line comment";
?>
Output:
Input:
<?php
$name = "Pavan Kumar";
echo $name;
?>
Output:
Pavan Kumar
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
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.
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
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
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)
);
Output:
1 sonoo 400000
2 john 500000
3 rahul 300000
. 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_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);
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.
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
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
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
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
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
Example
File: strlen.php
Input:
<?php
$str="my name is Sonoo jaiswal";
$str=strlen($str);
echo $str;
?>
Output:
24
Example
File: str_word_count.php
Input:
<?php
echo str_word_count("Hello world!"); // outputs 2
?>
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).
Example
File: str_replace.php
Input:
<?php
echo str_replace("world", "Dolly", "Hello world!"); // outputs Hello Dolly!
?>
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.
Example
File: automatically update the copyright year.php
Input:
© 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!
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");
?>
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);
?>
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.
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";
/* 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.
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.
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.
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 );
$physics->getPrice();
$chemistry->getPrice();
$maths->getPrice();
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 −
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!");
}
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.
function __construct($par) {
// Statements here run every time
// an instance of the class
// is created.
}
function myPublicFunction() {
return("I'm visible!");
}
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.
interface Mail {
public function sendMail();
}
Then, if another class implemented that interface, like this −
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.
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).
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>";
}
function toString() {
return($this->_lastName .", " .$this->_firstName);
}
}
class NameSub1 extends Name {
var $_middleInitial;
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.
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";
Syntax:
<?php
class MyClass
{
// Class properties and methods go here
}
$obj = new MyClass;
var_dump($obj);
?>
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 ({}).
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.
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.
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 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 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:
Syntax
setcookie(name, value, expire, path, domain, security);
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);
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
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.
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:
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']);
?>
Example:
File: session3.php
Input:
<?php
session_start();
session_destroy();
?>
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']++;
}
echo ( $msg );
?>
<p>
To continue click following link <br />
Syntax:
header( $header, $replace, $http_response_code )
Parameters: This function accepts three parameters as mentioned above and described below:
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).
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.
Syntax:
mail( to, subject, message, headers, parameters );
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";
</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.
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
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
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);
?>
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
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
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.
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
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 ]] )
Example
File: fopen.php
Input:
<?php
$handle = fopen("c:\\folder\\file.txt", "r");
?>
Syntax
string fread (resource $handle , int $length )
Example
File: fread.php
Input:
<?php
$filename = "c:\\file1.txt";
$fp = fopen($filename, "r");//open file in read mode
Output
this is first line
this is another line
this is third line
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
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
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
Example
File: Overwriting File.php
Input:
<?php
$fp = fopen('data.txt', 'w');//opens file in write-only mode
fwrite($fp, 'hello');
fclose($fp);
data.txt
welcome to php file write
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);
Output: data.txt
welcome to php file write this is additional text appending data
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 ] )
Example
File: unlink.php
Input:
<?php
$status=unlink('data.txt');
if($status){
echo "File deleted successfully";
}else{
echo "Sorry!";
}
?>
Output
File deleted successfully
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.
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)
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 );
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();
?>
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))";
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'];
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'];
$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.