0% found this document useful (0 votes)
73 views48 pages

PHP Programming Q&A Bank

PHP- Part B Only - University Questions & Answers Bank

Uploaded by

scotpep
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
73 views48 pages

PHP Programming Q&A Bank

PHP- Part B Only - University Questions & Answers Bank

Uploaded by

scotpep
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 48

Programming in PHP – University Questions & Answers Bank ((BCA, Nov’18);

(BSc, Apr’17); (BCA, Apr’17); (BCA, Apr’16); (BSc, Apr’16); (BSc, Apr’15);
(BCA, Nov’13):

PART-B

1) Explain the for loop and while loop with example (or) Write short notes on
while loop with example (or) Explain if, else and else if statements in PHP.
(or) Explain PHP conditional statements with example.
The for loop statement is used when you know how many times we want to execute
a statement or a block of statements.

Syntax:
for (initialization; condition; increment){
code to be executed;
}
The initializer is used to set the start value for the counter of the number of loop
iterations. A variable may be declared here for this purpose and it is traditional to
name it $i.
Example:
<html>
<body>

<?php
$a = 0;
$b = 0;

for( $i = 0; $i<5; $i++ ) {


$a += 10;
$b += 5;
}

echo ("At the end of the loop a = $a and b = $b" );


?>

</body>
</html>
Output: At the end of the loop a = 50 and b = 25
The while statement will execute a block of code if and as long as a test expression
is true.
If the test expression is true then the code block will be executed. After the code has
executed the test expression will again be evaluated and the loop will continue until
the test expression is found to be false.

Syntax
while (condition) {
code to be executed;
}
Example:
<html>
<body>

<?php
$i = 0;
$num = 50;

while( $i < 10) {


$num--;
$i++;
}

echo ("Loop stopped at i = $i and num = $num" );


?>

</body>
</html>
Output: Loop stopped at i = 10 and num = 40

The if, elseif ...else and switch statements are used to take decision based on the
different condition. We can use conditional statements in our code to make our
decisions. PHP supports following three decision making statements
• if...else statement − use this statement if you want to execute a set of code when
a condition is true and another if the condition is not true
• elseif statement − is used with the if...else statement to execute a set of code
if one of the several condition is true
• switch statement − is used if you want to select one of many blocks of code to be
executed, use the Switch statement. The switch statement is used to avoid long
blocks of if..elseif..else code.

2) Explain any five string functions in PHP (or) write any ten string functions
with example.
PHP string functions are used to manipulate string values. We are now going to look
at some of the commonly used string functions in PHP.

Function Description Example Output


Strtolower Used to convert all string echo strtolower( outputs benjamin
characters to lower case 'Benjamin');
letters
strtoupper Used to convert all string echo outputs GEORGE W
characters to upper case strtoupper('george BUSH
letters w bush');
strlen The string length function is echo strlen('united 24
used to count the number of states of america');
character in a string.
Spaces in between
characters are also counted
explode Used to convert strings into $settings = Array ( [0] =>
an array variable explode(';', host=localhost [1] =>
"host=localhost; db=sales [2] =>
db=sales; uid=root; uid=root [3] =>
pwd=demo"); pwd=demo )
print_r($settings);
substr Used to return part of the $my_var = 'This is a This is a re...
string. It accepts three (3) really long sentence
basic parameters. The first that I wish to cut
one is the string to be short';echo
shortened, the second substr($my_var,0,
parameter is the position of 12).'...';
the starting point, and the
third parameter is the
number of characters to be
returned.
str_replace Used to locate and replace echo str_replace that laptop is very
specified string values in a ('the', 'that', 'the expensive
given string. The function laptop is very
accepts three arguments. expensive');
The first argument is the
text to be replaced, the
second argument is the
replacement text and the
third argument is the text
that is analyzed.
strpos Used to locate the and echo strpos('PHP 4
return the position of a Programing','Pro');
character(s) within a string.
This function accepts two
arguments
sha1 Used to calculate the SHA-1 echo 5baa61e4c 9b93f3f0
hash of a string value sha1('password'); 682250b6cf8331b
7ee68fd8
md5 Used to calculate the md5 echo 9f961034ee 4de758
hash of a string value md5('password'); baf4de09ceeb1a75
str_word_count Used to count the number echo 12
of words in a string. str_word_count
('This is a really
long sentence that I
wish to cut short');
ucfirst Make the first character of a echo Outputs Respect
string value upper case ucfirst('respect');
lcfirst Make the first character of a echo Outputs rESPECT
string value lower case lcfirst('RESPECT');

3) Explain how to pass an array to a function? (or) Give the suitable example
for arrays in PHP. (or) Write a short note on usage of arrays in PHP. (or)
Discuss array.
From a function we can get back a set of variables by using an array. A function returns
any variable to the main script by using return statement. Here we will try to return a
set of variables by using an array.
We will break a string and create an array. This created array we will pass as input to
the function. To test the array inside the function we will display it by using while each
command.

Here is the implementation code.

funcion test($my_array){
while (list ($key, $val) = each ($my_array)) {
echo "$key -> $val <br>";
}

}
$collect_array=split(" ","Hello welcome to the world of PHP");
test($collect_array);

Output: “Hello welcome to the world of PHP”


An array is a data structure that stores one or more similar type of values in a single
value. For example if you want to store 100 numbers then instead of defining 100
variables its easy to define an array of 100 length.
There are three different kind of arrays and each array value is accessed using an ID
c which is called array index.
• Numeric array − An array with a numeric index. Values are stored and
accessed in linear fashion.
• Associative array − An array with strings as index. This stores element values
in association with key values rather than in a strict linear index order.
• Multidimensional array − An array containing one or more arrays and values
are accessed using multiple indices

Numeric array example:


<html>
<body>

<?php
/* First method to create array. */
$numbers = array( 1, 2, 3, 4, 5);

foreach( $numbers as $value ) {


echo "Value is $value <br />";
}

/* Second method to create array. */


$numbers[0] = "one";
$numbers[1] = "two";
$numbers[2] = "three";
$numbers[3] = "four";
$numbers[4] = "five";

foreach( $numbers as $value ) {


echo "Value is $value <br />";
}
?>

</body>
</html>
This will produce the following result −
Value is 1
Value is 2
Value is 3
Value is 4
Value is 5
Value is one
Value is two
Value is three
Value is four
Value is five

Associate array example:


<html>
<body>

<?php
/* First method to associate create array. */
$salaries = array("mohammad" => 20000, "qadir" => 10000, "zara" =>
5000);

echo "Salary of mohammad is ". $salaries['mohammad'] . "<br />";


echo "Salary of qadir is ". $salaries['qadir']. "<br />";
echo "Salary of zara is ". $salaries['zara']. "<br />";

/* Second method to create array. */


$salaries['mohammad'] = "high";
$salaries['qadir'] = "medium";
$salaries['zara'] = "low";

echo "Salary of mohammad is ". $salaries['mohammad'] . "<br />";


echo "Salary of qadir is ". $salaries['qadir']. "<br />";
echo "Salary of zara is ". $salaries['zara']. "<br />";
?>

</body>
</html>
This will produce the following result −
Salary of mohammad is 20000
Salary of qadir is 10000
Salary of zara is 5000
Salary of mohammad is high
Salary of qadir is medium
Salary of zara is low

Multidimensional array example:


<html>
<body>

<?php
$marks = array(
"mohammad" => array (
"physics" => 35,
"maths" => 30,
"chemistry" => 39
),

"qadir" => array (


"physics" => 30,
"maths" => 32,
"chemistry" => 29
),

"zara" => array (


"physics" => 31,
"maths" => 22,
"chemistry" => 39
)
);

/* Accessing multi-dimensional array values */


echo "Marks for mohammad in physics : " ;
echo $marks['mohammad']['physics'] . "<br />";

echo "Marks for qadir in maths : ";


echo $marks['qadir']['maths'] . "<br />";

echo "Marks for zara in chemistry : " ;


echo $marks['zara']['chemistry'] . "<br />";
?>

</body>
</html>
This will produce the following result −
Marks for mohammad in physics : 35
Marks for qadir in maths : 32
Marks for zara in chemistry : 39

4) Explain about HTTP headers. State any three HTTP server variables.
The header() function is an inbuilt function in PHP which is used to send a raw HTTP
header. The HTTP functions are those functions which manipulate information sent to
the client or browser by the Web server, before any other output has been sent. The
PHP header() function send a HTTP header to a client or browser in raw form. Before
HTML, XML, JSON or other output has been sent to a browser or client, a raw data is
sent with request (especially HTTP Request) made by the server as header
information. HTTP header provide required information about the object sent in the
message body more precisely about the request and response.
Syntax:
void header( $header, $replace = TRUE, $http_response_code )

<?php
// PHP program to describes header function

// Redirect the browser


header("Location: www.google.com");

// The below code does not get executed


// while redirecting
exit;

?>
Output:
This will change location of header, i.e. redirect to the URL

HTTP Server Variables in PHP:


PHP $_SERVER
$_SERVER is a PHP super global variable which holds information about headers,
paths, and script locations.
The example below shows how to use some of the elements in $_SERVER:
<?php
echo $_SERVER['PHP_SELF'];
echo "<br>";
echo $_SERVER['SERVER_NAME'];
echo "<br>";
echo $_SERVER['HTTP_HOST'];
echo "<br>";
echo $_SERVER['HTTP_REFERER'];
echo "<br>";
echo $_SERVER['HTTP_USER_AGENT'];
echo "<br>";
echo $_SERVER['SCRIPT_NAME'];
?>

Element/Code Description
$_SERVER['PHP_SELF'] Returns the filename of
the currently executing
script

$_SERVER['GATEWAY_INTERFACE'] Returns the version of the


Common Gateway
Interface (CGI) the server
is using

$_SERVER['SERVER_ADDR'] Returns the IP address of


the host server

$_SERVER['SERVER_NAME'] Returns the name of the


host server (such as
www.w3schools.com)

$_SERVER['SERVER_SOFTWARE'] Returns the server


identification string (such
as Apache/2.2.24)

$_SERVER['SERVER_PROTOCOL'] Returns the name and


revision of the information
protocol (such as
HTTP/1.1)

$_SERVER['REQUEST_METHOD'] Returns the request


method used to access
the page (such as POST)

$_SERVER['REQUEST_TIME'] Returns the timestamp of


the start of the request
(such as 1377687496)

$_SERVER['QUERY_STRING'] Returns the query string if


the page is accessed via a
query string

5) What is class? Explain how to create classes with suitable example. (or)
Discuss various type of class visibility. (or) Explain about cloning objects.
(or) How to create an object in PHP? (or) Write notes on PHP objects and
properties. (or) How will you set access to properties and methods?

PHP also supports object oriented programming. Classes are the blueprints of objects.
One of the big differences between functions and classes is that a class contains both
data (variables) and functions that form a package called an: ‘object’. Class is a
programmer-defined data type, which includes local methods and local variables.
Class is a collection of objects. Object has properties and behavior.
Syntax: We define our own class by starting with the keyword ‘class’ followed by the
name you want to give your new class:
<?php
class person {

}
?>
We enclose a class using curly braces ( { } ) … just like you do with functions.

Example:
<?php
class Google
{
// Constructor
public function __construct(){
echo 'The class "' . __CLASS__ . '" was initiated!<br>';
}

// Create a new object


$obj = new Google;
?>
Output:
The class "Google" was initiated.

Class visibility:
The visibility of a property, a method or a constant can be defined by prefixing the
declaration with the keywords public, protected or private. Class members declared
public can be accessed everywhere. Members declared protected can be accessed
only within the class itself and by inheriting and parent classes. Members declared as
private may only be accessed by the class that defines the member.
Property Visibility
Class properties must be defined as public, private, or protected. If declared using var,
the property will be defined as public.
Method Visibility
Class methods may be defined as public, private, or protected. Methods declared
without any explicit visibility keyword are defined as public.
Constant Visibility
As of PHP, class constants may be defined as public, private, or protected. Constants
declared without any explicit visibility keyword are defined as public.
Visibility from other objects
Objects of the same type will have access to each other’s private and protected
members even though they are not the same instances. This is because the
implementation specific details are already known when inside those objects.
Cloning objects in php:
Creating a copy of an object with fully replicated properties is not always the wanted
behavior. A good example of the need for copy constructors, is if you have an object
which represents a GTK window and the object holds the resource of this GTK
window, when you create a duplicate you might want to create a new window with the
same properties and have the new object hold the resource of the new window.
Another example is if your object holds a reference to another object which it uses and
when you replicate the parent object you want to create a new instance of this other
object so that the replica has its own separate copy.
An object copy is created by using the clone keyword (which calls the
object's __clone() method if possible). An object's __clone() method cannot be called
directly.
$copy_of_object = clone $object;
When an object is cloned, PHP will perform a shallow copy of all of the object's
properties. Any properties that are references to other variables will remain
references.
__clone ( void ) : void
Once the cloning is complete, if a __clone() method is defined, then the newly created
object's __clone() method will be called, to allow any necessary properties that need
to be changed.
Example: Cloning an object
<?php
class SubObject
{
static $instances = 0;
public $instance;

public function __construct() {


$this->instance = ++self::$instances;
}

public function __clone() {


$this->instance = ++self::$instances;
}
}
class MyCloneable
{
public $object1;
public $object2;

function __clone()
{
// Force a copy of this->object, otherwise
// it will point to same object.
$this->object1 = clone $this->object1;
}
}

$obj = new MyCloneable();

$obj->object1 = new SubObject();


$obj->object2 = new SubObject();

$obj2 = clone $obj;

print("Original Object:\n");
print_r($obj);

print("Cloned Object:\n");
print_r($obj2);

?>

The above example will output:


Original Object:
MyCloneable Object
(
[object1] => SubObject Object
(
[instance] => 1
)

[object2] => SubObject Object


(
[instance] => 2
)

)
Cloned Object:
MyCloneable Object
(
[object1] => SubObject Object
(
[instance] => 3
)

[object2] => SubObject Object


(
[instance] => 2
)

Properties of object in PHP:


Class member variables are called "properties". You may also see them referred to
using other terms such as "attributes" or "fields", but for the purposes of this reference
we will use "properties". They are defined by using one of the keywords public,
protected, or private, optionally followed by a type declaration, followed by a normal
variable declaration. This declaration may include an initialization, but this initialization
must be a constant value--that is, it must be able to be evaluated at compile time and
must not depend on run-time information in order to be evaluated.

Within class methods non-static properties may be accessed by using -> (Object
Operator): $this->property(where property is the name of the property). Static
properties are accessed by using the :: (Double Colon):self::$property. The pseudo-
variable $this is available inside any class method when that method is called from
within an object context. $this is a reference to the calling object (usually the object to
which the method belongs, but possibly another object, if the method is called statically
from the context of a secondary object).

Example on property declarations:


<?php
class SimpleClass
{
// valid as of PHP 5.6.0:
public $var1 = 'hello ' . 'world';
// valid as of PHP 5.3.0:
public $var2 = <<<EOD
hello world
EOD;
// valid as of PHP 5.6.0:
public $var3 = 1+2;
// invalid property declarations:
public $var4 = self::myStaticMethod();
public $var5 = $myVar;

// valid property declarations:


public $var6 = myConstant;
public $var7 = array(true, false);
// valid as of PHP 5.3.0:
public $var8 = <<<'EOD'
hello world
EOD;
}
?>

6) Write a short note on unlink. (or) Discusss about unlink command.


The unlink() function is an inbuilt function in PHP which is used to delete files. It is
similar to UNIX unlink() function. The $filename is sent as a parameter which needs
to be deleted and the function returns True on success and false on failure.

Syntax:
unlink( $filename, $context )

Parameters: This function accepts two parameters as mentioned above and described
below:
$filename: It is mandatory parameter which specifies the filename of the file which has
to be deleted.
$context: It is optional parameter which specifies the context of the file handle which
can be used to modify the nature of the stream.
Return Value: It returns True on success and False on failure.

Errors And Exception:


The unlink() function generates an E_WARNING level error on failure.
The web server user must have write permissions to the directory for using the unlink()
function.
The unlink() function returns Boolean False but many times it happens that it returns
a non-Boolean value which evaluates to False.

Example: Delete a file:


<?php
$file = fopen("test.txt","w");
echo fwrite($file,"Hello World. Testing!");
fclose($file);

unlink("test.txt");
?>

7) Explain the steps to creating mysql database.


Database is a collection of inter-related data which helps in efficient retrieval, insertion
and deletion of data from database and organizes the data in the form of tables, views,
schemas, reports etc.,

We know that in MySQL to create a database we need to execute a query.


The basic steps to create MySQL database using PHP are:
• Establish a connection to MySQL server from your PHP script as described
in this article.
• If the connection is successful, write a SQL query to create a database and store
it in a string variable.
• Execute the query.

Example: Using MySQLi Object-oriented procedure: If the MySQL connection is


established using Object-oriented procedure then we can use the query() function of
mysqli class to execute our query as described in the below syntax.
Syntax:
<?php
$servername = "localhost";
$username = "username";
$password = "password";

// Creating a connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Creating a database named newDB
$sql = "CREATE DATABASE newDB";
if ($conn->query($sql) === TRUE) {
echo "Database created successfully with the name newDB";
} else {
echo "Error creating database: " . $conn->error;
}

// closing connection
$conn->close();
?>
Note:Specify the three arguments servername, username and password to the mysqli
object whenever creating a database.
Output:

8) Write a PHP code to draw Ellipses. (or) How to draw rectangles in PHP? (or)
How to draw ellipses in PHP?
The imagefilledellipse() function is an inbuilt function in PHP which is used to draw the
filled ellipse. It draws the ellipse with specified center coordinate.

Syntax:
bool imagefilledellipse( $image, $cx, $cy, $width, $height, $color )

Parameters: This function accepts six parameters as mentioned above and described
below:
• $image: The imagecreatetruecolor() function is used to create a blank image in
a given size.
• $cx: x-coordinate of the center.
• $cy: y-coordinate of the center.
• $width: The ellipse width.
• $height: The ellipse height.
• $color: The fill color. A color identifier created with imagecolorallocate().
Return Value: This function returns TRUE on success or FALSE on failure.
Below programs illustrate the imagefilledellipse() function in PHP.

Example Program:
<?php
// It create the size of image or blank image.
$image = imagecreatetruecolor(500, 300);
// Set the background color of image.
$bg = imagecolorallocate($image, 205, 220, 200);
// Fill background with above selected color.
imagefill($image, 0, 0, $bg);
// Set the color of an ellipse.
$col_ellipse = imagecolorallocate($image, 0, 102, 0);
// Function to draw the filled ellipse.
imagefilledellipse($image, 250, 150, 400, 250, $col_ellipse);
// Output of the image.
header("Content-type: image/png");
imagepng($image);
?>
Output:

Draw Rectangle:
The function ImageRectangle ($image, $x1, $y1, $x2, $y2, $color) can be used to
draw a rectangle. Image resource is specified by $image, the top left corner is
specified by ($x1, $y1) and the down right corner is ($x2, $y2), $color is color identifier.
Example:
<?php
$image = ImageCreate(130, 170);
$white = ImageColorAllocate($image, 255, 255, 255);
$black = ImageColorAllocate($image, 0, 0, 0);
ImageFill($image, 0, 0, $white);
ImageRectangle($image, 10,10,80,60,$black);
ImagePng($image, "flag.png");
ImageDestroy($image);
?>
Output:

Fill Rectangle:
The function ImageRectangle ($image, $x1, $y1, $x2, $y2, $color) can be used to
draw and fill a rectangle. Image resource is specified by $image, the top left corner is
specified by ($x1, $y1) and the down right corner is ($x2, $y2), $color is color
identifier.
Example:
<?php
$image = ImageCreate(130, 170);
$white = ImageColorAllocate($image, 255, 255, 255);
$blue = ImageColorAllocate($image, 0, 0, 255);
ImageFill($image, 0, 0, $white);
ImageFilledRectangle($image, 10,10,80,60,$blue);
ImagePng($image, "flag.png");
ImageDestroy($image);
?>
Output:

9) Discuss the use of ‘here’ document.


For those cases where you need to set in your PHP script a string containing big chunk
of text data (for example, HTML code), it is easier to use "here document" style. This
special way allows you to set multiline strings, with all included variables expanded as
it is done in double quotes style.
Code syntax:

$str = <<<HERE_NAME
Example of here document
style for setting big chunks of text data
in your script
HERE_NAME;
The label HERE_NAME that stands after <<< is called "here document" label. After
"here document" line, all text will be set into the string including space and carriage
return symbols. The output ends when the single line with "here document" label is
found. In the example above, output ends on the line with HERE_NAME label.

If your code with heredoc lines does not work, you should look for these most common
mistakes:
· HERE_NAME label must contain only alphanumeric characters and underscores,
and it should not start with a digit character or underscore.
· After ending HERE_NAME label there should be only ; and \n symbols as they can
be written in UNIX text editors
This style of output is very useful for writing CGI scripts.

Example of PHP Here document


<?php
$name = "Google";
$occupation = "Programmer";
$lognText = <<<EOF
This is a heredoc section.
For more information talk to $name, your local $occupation.
EOF;
echo strtolower($lognText);
?>

Output:
This is a heredoc section.
For more information talk to Google, your local Programmer.

10) Briefly explain the function in PHP (or) Describe nested functions in detail.
(or) Write short notes on fgets functions. (or) Discuss about the functions in
PHP. (or) Write short notes on fgets functions (or) Write a program to
calculate the factorial of a given number implementing it using function
concept
A function is a block of code written in a program to perform some specific task. We
can relate functions in programs to employees in a office in real life for a better
understanding of how functions work. Suppose the boss wants his employee to
calculate the annual budget. So how will this process complete? The employee will
take information about the statics from the boss, performs calculations and calculate
the budget and shows the result to his boss. Functions works in a similar manner.
They take information as parameter, executes a block of statements or perform
operations on this parameters and returns the result.
PHP provides us with two major types of functions:
• Built-in functions : PHP provides us with huge collection of built-in library functions.
These functions are already coded and stored in form of functions. To use those
we just need to call them as per our requirement like, var_dump, fopen(), print_r(),
gettype() and so on.
• User Defined Functions : Apart from the built-in functions, PHP allows us to create
our own customised functions called the user-defined functions.
Using this we can create our own packages of code and use it wherever necessary
by simply calling it.
While creating a user defined function we need to keep few things in mind:
1. Any name ending with an open and closed parenthesis is a function.
2. A function name always begins with the keyword function.
3. To call a function we just need to write its name followed by the parenthesis
4. A function name cannot start with a number. It can start with an alphabet or
underscore.
5. A function name is not case-sensitive.

Syntax:
function function_name(){
executable code;
}

Example:
function funcGeek()
{
echo "Hello World!";
}
// Calling the function
funcGeek();
?>
Output:
Hello World!

Nested Functions:
When a function is defined inside a parent function, we will first have to call the parent
function before the child function becomes available. Once the parent has been called,
child functions will be available globally in your PHP script, and not just in the parent.
If we still want to get your hands dirty with nested functions, we should check out the
below example:
function MyFunc() {
// The Nested Functions
function DoThis() {
return 'Yeah!';
}
function DoThat() {
return 'Nah!';
}
}
// The Main Script
$string = 'Yes yes';
MyFunc();
echo DoThis();

We may also use the nested functions inside of the parent:


function MyFunc($content) {
// The Nested Functions
function DoThis() {
return 'Yeah!';
}
function DoThat() {
return 'Nah!';
}
// The Main Function Script
if ($content == 'Yes yes') {
return DoThis();
} else {
return DoThat();
}
}
// The Main Script
$string = 'Yes yes';
echo MyFunc($string);

fgets function:
The fgets() function in PHP is an inbuilt function which is used to return a line from an
open file.
• It is used to return a line from a file pointer and it stops returning at a specified
length, on end of file(EOF) or on a new line, whichever comes first.
• The file to be read and the number of bytes to be read are sent as parameters to
the fgets() function and it returns a string of length -1 bytes from the file pointed by
the user.
• It returns False on failure.
Syntax:
fgets(file, length)

Parameters Used:
The fgets() function in PHP accepts two parameters.
file : It specifies the file from which characters have
to be extracted.
length : It specifies the number of bytes to be
read by the fgets() function. The default value
is 1024 bytes.
Return Value : It returns a string of length -1 bytes from the file pointed by the user or
False on failure.

Factorial of a number using PHP function:


In this method, we simply used the for loop to iterate over the sequence of numbers
to get the factorial.
<?php
// PHP code to get the factorial of a number
// function to get factorial in iterative way
function Factorial($number){
$factorial = 1;
for ($i = 1; $i <= $number; $i++){
$factorial = $factorial * $i;
}
return $factorial;
}
// Driver Code
$number = 10;
$fact = Factorial($number);
echo "Factorial = $fact";
?>
Input: 5 Output: 120.

11) Explain various internal data types in PHP


The values assigned to a PHP variable may be of different data types including simple
string and numeric types to more complex data types like arrays and objects. PHP
supports total eight primitive data types: Integer, Floating point number or Float, String,
Booleans, Array, Object, resource and NULL. These data types are used to construct
variables. Now let's discuss each one of them in detail.

Integers are whole numbers, without a decimal point (..., -2, -1, 0, 1, 2, ...). Integers
can be specified in decimal (base 10), hexadecimal (base 16 - prefixed with 0x) or
octal (base 8 - prefixed with 0) notation, optionally preceded by a sign (- or +).

$a = 123; // decimal number


var_dump($a);
echo "<br>";
$b = -123; // a negative number
var_dump($b);
echo "<br>";
$c = 0x1A; // hexadecimal number
var_dump($c);
echo "<br>";
$d = 0123; // octal number
var_dump($d);

Strings are sequences of characters, where every character is the same as a byte. A
string can hold letters, numbers, and special characters and it can be as large as up
to 2GB (2147483647 bytes maximum). The simplest way to specify a string is to
enclose it in single quotes (e.g. 'Hello world!'), however we can also use double quotes
("Hello world!").

$a = 'Hello world!';
echo $a;

Floating point numbers (also known as "floats", "doubles", or "real numbers") are
decimal or fractional numbers, like demonstrated in the example below.
$a = 1.234;
var_dump($a);
echo "<br>";
$b = 10.2e3;
var_dump($b);
echo "<br>";
$c = 4E-10;
var_dump($c);

Booleans are like a switch it has only two possible values either 1 (true) or 0 (false).

$show_error = true;
var_dump($show_error);

An array is a variable that can hold more than one value at a time. It is useful to
aggregate a series of related items together, for example a set of country or city
names. An array is formally defined as an indexed collection of data values. Each
index (also known as the key) of an array is unique and references a corresponding
value.

$colors = array("Red", "Green", "Blue");


var_dump($colors);
echo "<br>";
$color_codes = array(
"Red" => "#ff0000",
"Green" => "#00ff00",
"Blue" => "#0000ff"
);
var_dump($color_codes);

An object is a data type that not only allows storing data but also information on, how
to process that data. An object is a specific instance of a class which serve as
templates for objects. Objects are created based on this template via the new keyword.
Every object has properties and methods corresponding to those of its parent class.
Every object instance is completely independent, with its own properties and methods,
and can thus be manipulated independently of other objects of the same class.

class greeting{
// properties
public $str = "Hello World!";
// methods function
show_greeting(){ return $this->str; } }
// Create object from class
$message = new greeting;
The special NULL value is used to represent empty variables in PHP. A variable of
type NULL is a variable without any data. NULL is the only possible value of type null.

$a = NULL;
var_dump($a);
echo "<br>";

A resource is a special variable, holding a reference to an external resource. Resource


variables typically hold special handlers to opened files and database connections.

$handle = fopen("note.txt", "r");


var_dump($handle);
echo "<br>";

12) Explain the process of reading data from a webpage. (or) How to read the
data in PHP web pages? (or) Write a short note on file_get_contents (or)
Describe about file handing concepts in PHP. (or) Explain in brief about
reading a whole file at once.
Using file_get_contents we can read an entire file into a string.

Syntax:
file_get_contents ( string $filename [, bool $use_include_path = FALSE [, resource
$context [, int $offset = 0 [, int $maxlen ]]]] ) : string

This function is similar to file(), except that file_get_contents() returns the file in a
string, starting at the specified offset up to maxlen bytes. On failure, file_get_contents()
will return FALSE.

file_get_contents() is the preferred way to read the contents of a file into a string. It will
use memory mapping techniques if supported by our OS to enhance performance.

The function returns the read data or FALSE on failure.

The following example code demonstrates how a section of a file can be read:
<?php
// Read 14 characters starting from the 21st character
$section = file_get_contents('./people.txt', FALSE, NULL, 20, 14);
var_dump($section);
?>

We can also use stream contexts to read data from a file:


<?php
// Create a stream
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"Accept-language: en\r\n" .
"Cookie: foo=bar\r\n"
)
);
$context = stream_context_create($opts);
// Open the file using the HTTP headers set above
$file = file_get_contents('http://www.example.com/', false, $context);
?>

The file() function reads entire file into an array


Syntax:
file ( string $filename [, int $flags = 0 [, resource $context ]] ) : array
Code:
<?php
// Get a file into an array. In this example we'll go through HTTP to get
// the HTML source of a URL.
$lines = file('http://www.example.com/');

// Loop through our array, show HTML source as HTML source; and line num
bers too.
foreach ($lines as $line_num => $line) {
echo "Line #<b>{$line_num}</b> : " . htmlspecialchars($line) . "<br />\n";
}

// Another example, let's get a web page into a string. See also file_get_conte
nts().
$html = implode('', file('http://www.example.com/'));

// Using the optional flags parameter since PHP 5


$trimmed = file('somefile.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMP
TY_LINES);
?>
Output: A file is read as a string into an object.

13) Differentiate abstract class and interface in PHP.


14) What is SQL? List its categories.
SQL is a domain-specific language used in programming and designed for managing
data held in a relational database management system, or for stream processing in a
relational data stream management system.

Type of SQL statements are divided into five different categories: Data definition
language (DDL), Data manipulation language (DML), Data Control Language (DCL),
Transaction Control Statement (TCS), Session Control Statements (SCS).
Data Definition Language (DDL)
Data definition statement are use to define the database structure or table.
Statement Description
CREATE Create new database/table.
ALTER Modifies the structure of database/table.
DROP Deletes a database/table.
TRUNCATE Remove all table records including allocated table spaces.
RENAME Rename the database/table.
Data Manipulation Language (DML)
Data manipulation statement are use for managing data within table object.
Statement Description
SELECT Retrieve data from the table.
INSERT Insert data into a table.
UPDATE Updates existing data with new data within a table.
DELETE Deletes the records rows from the table.
MERGE MERGE (also called UPSERT) statements to INSERT new
records or UPDATE existing records depending on condition
matches or not.
LOCK TABLE LOCK TABLE statement to lock one or more tables in a specified
mode. Table access denied to a other users for the duration of
your table operation.
CALL Statements are supported in PL/SQL only for executed
EXPLAIN dynamically. CALL a PL/SQL program or EXPLAIN PATH
PLAN access the data path.
Data Control Language (DCL)
Data control statement are use to give privileges to access limited data.
Statement Description
GRANT Gives privileges to user for accessing database data.
REVOKE Take back for given privileges.
ANALYZE ANALYZE statement to collect statistics information about
index, cluster, table.
AUDIT To track the occurrence of a specific SQL statement or all
SQL statements during the user sessions.
COMMENT Write comment to the data table.
Transaction Control Statement (TCS)
Transaction control statement are use to apply the changes permanently save into
database.
Statement Description
COMMIT Permanent work save into database.
ROLLBACK Restore database to original form since the last COMMIT.
SAVEPOINT Create SAVEPOINT for later use ROLLBACK the new
changes.
SET SET TRANSACTION command set the transaction properties
TRANSACTION such as read-write/read only access.
PL/SQL Transaction commit, rollback, savepoint, autocommit, Set Transaction.
Session Control Statement (SCS)
Session control statement are manage properties dynamically of a user session.
Statement Description
ALTER ALTER SESSION statement to modify conditions or
SESSION parameters that are affect to your database connection.
SET ROLE SET ROLE statement to enable or disable the roles that are
currently enabled for the session.

15) How PHP helps in setting cookies? Explain. (or) Explain how to read a
cookie. (or) Difference between cookies and session in PHP.
A cookie is a small file with the maximum size of 4KB that the web server stores on
the client computer.They are typically used to keeping track of information such as a
username that the site can retrieve to personalize the page when the user visits the
website next time.A cookie can only be read from the domain that it has been issued
from.Cookies are usually set in an HTTP header but JavaScript can also set a cookie
directly on a browser.
Setting Cookie In PHP: To set a cookie in PHP,the setcookie() function is used.The
setcookie() function needs to be called prior to any output generated by the script
otherwise the cookie will not be set.
Syntax :
setcookie(name, value, expire, path, domain, security);
Parameters: The setcookie() function requires six arguments in general which are:
1. Name: It is used to set the name of the cookie.
2. Value: It is used to set the value of the cookie.
3. Expire: It is used to set the expiry timestamp of the cookie after which the cookie
can’t be accessed.
4. Path: It is used to specify the path on the server for which the cookie will be
available.
5. Domain: It is used to specify the domain for which the cookie is available.
6. Security: It is used to indicate that the cookie should be sent only if a secure
HTTPS connection exists.
Creating Cookies: Creating a cookie named Auction_Item and assigning the value
Luxury Car to it.The cookie will expire after 2 days(2 days * 24 hours * 60 mins * 60
seconds).
<?php
setcookie("Auction_Item", "Luxury Car", time()+2*24*60*60);
?>
Difference Between Cookies and Session:

16) Briefly explain the handling of downloaded data.


Using readfile function handling of downloaded data can be achieved in PHP.

Syntax:
readfile ( string $filename [, bool $use_include_path = FALSE [, resource $context ]]
) : int
The above function reads a file and writes it to the output buffer.

Parameters:
filename - The filename being read.
use_include_path - You can use the optional second parameter and set it to TRUE, if
you want to search for the file in the include_path, too.
context - A context stream resource.

Return Values:
Returns the number of bytes read from the file on success, or FALSE on failure

Example:
<?php
$file = 'monkey.gif';

if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
}
?>
The above example will output something similar to:

17) List out and explain image creating functions. (or) Explain how to download
images using Ajax. (or) Explain how to download images using Ajax. (or)
Write about imagecopy functions. (or) How to draw image in an AJAX? (or)
Write a note on image copy function. (or) What are the functions to be used
to get the image’s properties? Explain with example. (or) Explain how to open
XMLHTTP request object.
The imagecreate() function is an inbuilt function in PHP which is used to create a new
image. This function returns the blank image of given size. In
general imagecreatetruecolor() function is used instead of imagecreate() function
because imagecreatetruecolor() function creates high quality images.
Syntax:
imagecreate( $width, $height )
Parameters: This function accepts two parameters as mentioned above and described
below:
• $width: It is mandatory parameter which is used to specify the image width.
• $height: It is mandatory parameter which is used to specify the image height.
Return Value: This function returns an image resource identifier on success,
FALSE on errors.
Example 1:
<?php
// Create the size of image or blank image
$image = imagecreate(500, 300);
// Set the background color of image
$background_color = imagecolorallocate($image, 0, 153, 0);
// Set the text color of image
$text_color = imagecolorallocate($image, 255, 255, 255);
// Function to create image which contains string.
imagestring($image, 5, 180, 100, "Google", $text_color);
imagestring($image, 3, 160, 120, "An Online Search Engine", $text_color);
header("Content-Type: image/png");
imagepng($image);
imagedestroy($image);
?>
Output:

Google
An Online Search Engine

In general, imagecreatetruecolor() function is used instead of imagecreate() so that


image processing occurs on the highest quality image possible. If you want to output
a palette image, then imagetruecolortopalette() should be called immediately before
saving the image with imagepng() or imagegif(). imagedestroy() function destroy an
image and imagecreatetruecolor() creates a new true color image
Example 2: (Here imagecolorallocate(), imagestring(), imagepng() and imagedestroy()
functions are used):
<?php
header("Content-Type: image/png");
$im = @imagecreate(110, 20)
or die("Cannot Initialize new GD image stream");
$background_color = imagecolorallocate($im, 0, 0, 0);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5, "A Simple Text String", $text_color);
imagepng($im);
imagedestroy($im);
?>
Output:
Imagecopy() function is used to copy part of an image.
Syntax:
imagecopy ( resource $dst_im , resource $src_im , int $dst_x , int $dst_y , int $src_x
, int $src_y , int $src_w , int $src_h ) : bool
Copy a part of src_im onto dst_im starting at the x,y coordinates src_x, src_y with a
width of src_w and a height of src_h. The portion defined will be copied onto the x,y
coordinates, dst_x and dst_y.
Example program on imagecopy function:
<?php
// Create image instances
$src = imagecreatefromgif('php.gif');
$dest = imagecreatetruecolor(80, 40);
// Copy
imagecopy($dest, $src, 0, 0, 20, 13, 80, 40);
// Output and free from memory
header('Content-Type: image/gif');
imagegif($dest);
imagedestroy($dest);
imagedestroy($src);
?>
Output:

Download images using Ajax (with XMLHttpRequest):


An image can be gettable from a source or a server using XMLHttpRequest object.
When you click on button get the XMLHttpRequest object to get image from server
and display on current page.
Following are easiest example for fetching image from server. Image response type is
BLOB so directly we can not get this image. Response text must be convert into
encoding format using user define encode64 function.
Code:
<html>
<body>
<script language="javascript" type="text/javascript">
function send_with_ajax( ){
if (window.XMLHttpRequest || window.ActiveXObject) {
if (window.ActiveXObject) {
try {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
} catch(exception) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
} else {
xhr = new XMLHttpRequest();
}
} else {
alert("Your browser does not support XMLHTTP Request...!");
}

xhr.open("GET", "300x300.gif", true); // Make sure file is in same server


xhr.overrideMimeType('text/plain; charset=x-user-defined');
xhr.send(null);

xhr.onreadystatechange = function() {
if (xhr.readyState == 4){
if ((xhr.status == 200) || (xhr.status == 0)){
var image = document.getElementById("get_img");
image.src = "data:image/gif;base64," + encode64(xhr.responseText);
}else{
alert("Something misconfiguration : " +
"\nError Code : " + xhr.status +
"\nError Message : " + xhr.responseText);
}
}
};
}

function encode64(inputStr){
var b64 =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/
=";
var outputStr = "";
var i = 0;

while (i> 2;
var enc2 = ((byte1 & 3) << 4) | (byte2 >> 4);

var enc3, enc4;


if (isNaN(byte2)){
enc3 = enc4 = 64;
} else{
enc3 = ((byte2 & 15) << 2) | (byte3 >> 6);
if (isNaN(byte3)){
enc4 = 64;
} else {
enc4 = byte3 & 63;
}
}
outputStr += b64.charAt(enc1) + b64.charAt(enc2) + b64.charAt(enc3) +
b64.charAt(enc4);
}
return outputStr;
}
</script>

<button onClick="send_with_ajax()">Get Image</button><br />


<img id="get_img" />
</body>
Output: (a Get image button appears initially and when the button is clicked an image
gets downloaded which of 300x300 pixels)

Functions to get image properties:


PHP provides various functions and DLL to extract image properties from an image.
These functions are,
1. imagesx() and imagesy()
2. getimagesize()
3. exif_read_data()
The imagesx() and imagesy() are used to extract the width and height of the images
respectively. For that, it accepts the resource type of data which will be returned on
creating new images dynamically using PHP script.
getimagesize() is a PHP method that returns an array of image properties like width,
height, image type, mime type and etc.
Demo code on using getimagesize() function:
<?php
if(isset($_POST["submit"])) {
if(is_array($_FILES)) {
$image_properties = getimagesize($_FILES['myImage']['tmp_name']);
print "<PRE>";
print_r($image_properties);
print "</PRE>";
}
}
?>
Also Imagick::getImageProperties() Returns all associated properties that match the
pattern.
Syntax:
Imagick::getImageProperties ([ string $pattern = "*" [, bool $include_values = TRUE ]]
) : array
Sample code:
<?php
/* Create the object */
$im = new imagick("/path/to/example.jpg");
/* Get the EXIF information */
$exifArray = $im->getImageProperties("exif:*");
/* Loop trough the EXIF properties */
foreach ($exifArray as $name => $property)
{
echo "{$name} => {$property}<br />\n";
}
?>

18) Briefly write out the advantages and disadvantages of AJAX?


Advantages of AJAX
AJAX Concept: Before you starting AJAX you'll need to have a strong knowledge of
JavaScript. AJAX is not a difficult, you can easy implement AJAX in a meaningful
manner. Some IDE are help us to implement AJAX.
Speed: Reduce the server traffic in both side request. Also reducing the time
consuming on both side response.

Interaction: AJAX is much responsive, whole page(small amount of) data transfer at a
time.
XMLHttpRequest: It has an important role in the Ajax web development technique.
XMLHttpRequest is special JavaScript object that was designed by Microsoft.
XMLHttpRequest object call as a asynchronous HTTP request to the Server for
transferring data both side. It's used for making requests to the non-Ajax pages.
Asynchronous calls: AJAX make asynchronous calls to a web server. This means
client browsers are avoid waiting for all data arrive before start the rendering.
Form Validation: This is the biggest advantage. Form are common element in web
page. Validation should be instant and properly, AJAX gives you all of that, and more.
Bandwidth Usage: No require to completely reload page again. AJAX is improve the
speed and performance. Fetching data from database and storing data into database
perform background without reloading page.

Disadvantages of AJAX
1. AJAX application would be a mistake because search engines would not be able to
index an AJAX application.
2. Open Source: View source is allowed and anyone can view the code source written
for AJAX.
3. ActiveX requests are enabled only in Internet Explorer and newer latest browser.
4. The last disadvantage, XMLHttpRequest object itself. For a security reason you can
only use to access information from the web host that serves initial pages. If you need
to fetching information from another server, it's is not possible with in the AJAX.

19) Explain the switch statement with example.


The switch statement is similar to a series of IF statements on the same expression.
In many occasions, you may want to compare the same variable (or expression) with
many different values, and execute a different piece of code depending on which value
it equals to. This is exactly what the switch statement is for.
Syntax:
switch (n) {
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
case label3:
code to be executed if n=label3;
break;
...
default:
code to be executed if n is different from all labels;
}
Example:
<?php
if ($i == 0) {
echo "i equals 0";
} elseif ($i == 1) {
echo "i equals 1";
} elseif ($i == 2) {
echo "i equals 2";
}
switch ($i) {
case 0:
echo "i equals 0";
break;
case 1:
echo "i equals 1";
break;
case 2:
echo "i equals 2";
break;
}
?>
Output: Based on the input value of i, the output will be displayed with equals 0 or
equals 1 or equals 2.

20) Explain how to format text string.


The formatting of text string can be done using sprintf() function.
Syntax:
sprintf ( string $format [, mixed $... ] ) : string
Returns a string produced according to the formatting string format. The arg1, arg2,
++ parameters will be inserted at percent (%) signs in the main string. This function
works "step-by-step". At the first % sign, arg1 is inserted, at the second % sign, arg2
is inserted, etc.
Example:
<html>
<body>
<?php
$number = 9;
$str = "Beijing";
$txt = sprintf("There are %u million bicycles in %s.",$number,$str);
echo $txt;
?>
</body>
</html>
Output:
There are 9 million bicycles in Beijing.

21) Explain how to handle check boxes with example.


A checkbox helps a user to choose between one of the two mutually exclusive options.
There are two types of checkboxes based on the number of options that you make.
• Checkbox group
• Checkbox
Clicking on the checkbox will either change it to ON to OFF or vice verse. These are
preferred for multiple choices options. In use cases where a SINGLE choice must be
made, a radio button or a select option will work better. If in an instance “check all that
apply” question comes up at such cases checkboxes group can be used.

isset() can be used to handle checkboxes by which it checks whether a variable is set
and is not NULL. This function also checks if a declared variable, array or array key
has null value, if it does, isset() returns false, it returns true in all other possible cases.
This problem can be solved with the help of isset() function.
Syntax: bool isset( $var, mixed )
This function accepts more than one parameters. The first parameter of this function
is $var. This parameter is used to store the value of variable.
Example:
<?php if(isset($_GET['submit'])) {
$var = $_GET['option1']; if(isset($var)) {
echo "Option 1 submitted successfully"; } } ?>
<html lang="en"> <head>
<title>GeeksforGeeks Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href=
"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<style>
.gfg { font-size:40px; font-weight:bold; color:green; }
body {
text-align:center;
}
</style>
</head>
<body>
<div class="container">
<div class = "gfg">Google</div>
<h2>Form control: checkbox</h2>
<p>The form below contains one checkbox.</p>
<form method="get">
<div class="checkbox">
<label><input type="checkbox" name = "option1"
value="Option 1">Option 1</label>
<label><button name="submit" value='true'
class="btn btn-default">SUBMIT</button>
</div>
</form>
</div>
</body>
</html>
Output:
Option 1 submitted successfully

Google
Form Control: checkbox

The form below contains on checkbox.

22) Explain how to perform data validation.


Validation means check the input submitted by the user. There are two types of
validation are available in PHP. They are as follows −
• Client-Side Validation − Validation is performed on the client machine web
browsers.
• Server Side Validation − After submitted by data, The data has sent to a
server and perform validation checks in server machine.
Some of Validation rules for field

Field Validation Rules

Name Should required letters and white-spaces


Email Should required @ and .

Website Should required a valid URL

Radio Must be selectable at least once

Check Box Must be checkable at least once

Drop Down menu Must be selectable at least once

Valid URL:
Below code shows validation of URL
$website = input($_POST["site"]);

if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-
z0-9+&@#\/%=~_|]/i",$website)) {
$websiteErr = "Invalid URL";
}
Above syntax will verify whether a given URL is valid or not. It should allow some
keywords as https, ftp, www, a-z, 0-9,..etc..

Valid Email:
Below code shows validation of Email address
$email = input($_POST["email"]);

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid format and please re-enter valid email";
}
Above syntax will verify whether given Email address is well-formed or not.if it is not,
it will show an error message.

23) Explain about reflection in OOP. (or) Explain polymorphism with suitable
example in OOPs.
PHP comes with a complete reflection API that adds the ability to introspect classes,
interfaces, functions, methods and extensions. Additionally, the reflection API offers
ways to retrieve doc comments for functions, classes and methods.
One of the most common ways in which Reflection is useful is for debugging your
code. We’ve probably used the get_class() and get_class_methods() functions when
working with an ambiguously named object. The ability to get the type or methods of
an object when you don’t know what type of object it is, is Reflection.

Another common use of Reflection is for creating documentation. It would be


extremely labour intensive to write documentation about every method of every class
of a large framework or application. Instead, Reflection can automatically generate the
documentation for you. It does this by inspecting each method, constructor and class
to determine what goes in and what comes out.
The two PHP Reflection functions that I use most often
are get_class() and get_class_methods() when we work with someone else’s code.
It’s often quicker to just dump an object out, rather than pull the thread to see where
the object originated from.
Using these functions is really easy:
// An unknown object appeared!
var_dump(get_class($pokemon)); // Pokemon\Electricity\Pikachu
var_dump(get_class_methods($pokemon));
// Tail Whip
// Thunder Bold
// Thunder

The get_class() function will return a string of the class name and
the get_class_methods() function will return an array of the available methods on the
object.
Another common function is the method_exists() function. We will often see this used
inside an object’s __get() or __set() magic methods to see if a getter or setter method
is available on the object.
class User {
protected function getUsername(){}
public function __get($param)
{
$method = ‘get’.ucfirst($param)’;
if(method_exists($this, $method))
return $this->{$method}();
}
}

24) Write short note on default arguments.


PHP allows us to define C++ style default argument values. In such case, if we don't
pass any value to the function, it will use default argument value.

Let' see the simple example of using PHP default arguments in function.

<?php
function sayHello($name="Ram"){
echo "Hello $name<br/>";
}
sayHello("Sonoo");
sayHello();//passing no value
sayHello("Vimal");
?>
Output:
Hello Sonoo
Hello Ram
Hello Vimal
<?php
function makecoffee($type = "cappuccino")
{
return "Making a cup of $type.\n";
}
echo makecoffee();
echo makecoffee(null);
echo makecoffee("espresso");
?>
Output:
Making a cup of cappuccino.
Making a cup of .
Making a cup of espresso.

25) Write short notes on overriding methods. (or) Disucss about the overriding
with suitable example in OOPs. (or) Briefly discuss about static methods in
PHP.
Function overriding is same as other OOPs programming languages. In function
overriding, both parent and child classes should have same function name with and
number of arguments. It is used to replace parent method in child class. The purpose
of overriding is to change the behavior of parent class method. The two methods with
the same name and same parameter is called overriding.
Example:
<?php
// PHP program to implement
// function overriding
// This is parent class
class P {
// Function geeks of parent class
function geeks() {
echo "Parent"; } }
// This is child class
class C extends P {
// Overriding geeks method
function geeks() {
echo "\nChild"; } }
// Reference type of parent
$p = new P;
// Reference type of child
$c= new C;
// print Parent
$p->geeks();
// Print child
$c->geeks();
?>
Output:
Parent
Child
Static methods:
Static methods can be called directly - without creating an instance of a class. Static
methods are declared with the static keyword:
Syntax:
<?php
class ClassName {
public static function staticMethod() {
echo "Hello World!";
} } ?>
To access a static method use the class name, double colon (::), and the method
name:
Syntax: ClassName::staticMethod();
Example:
<?php
class greeting {
public static function welcome() {
echo "Hello World!"; }}
// Call static method
greeting::welcome();?>

26) Explain about an operations in PHP.


In PHP operations are carried out by following means:
1) Using Operators
2) Using files & functions
3) Using database

What is Operator? Simple answer can be given using expression 4 + 5 is equal to 9.


Here 4 and 5 are called operands and + is called operator. PHP language supports
following type of operators.
• Arithmetic Operators
• Comparison Operators
• Logical (or Relational) Operators
• Assignment Operators
• Conditional (or ternary) Operators

File & function operations:


File handling is needed for any application. For some tasks to be done file needs to
be processed. File handling in PHP is similar as file handling is done by using any
programming language like C. PHP has many functions to work with normal files.
Those functions are:
1) fopen() – PHP fopen() function is used to open a file. First parameter of fopen()
contains name of the file which is to be opened and second parameter tells about
mode in which file needs to be opened.
2) fread() - After file is opened using fopen() the contents of data are read using
fread(). It takes two arguments. One is file pointer and another is file size in bytes.
3) fwrite() – New file can be created or text can be appended to an existing file using
fwrite() function. Arguments for fwrite() function are file pointer and text that is to written
to file. It can contain optional third argument where length of text to written is specified.
4) fclose() – file is closed using fclose() function. Its argument is file which needs to be
closed.

Database operations:
PHP will work with virtually all database software, including Oracle and Sybase but
most commonly used is freely available MySQL database. Following are the
operations which can be carried out in the mysql database using PHP:
• Connecting to MySQL database − 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.
• Create MySQL Database Using PHP − 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.
• Delete MySQL Database Using PHP − If a database is no longer required then
it can be deleted forever. You can use pass an SQL command to mysql_query
to delete a database.
• Insert Data To MySQL Database − Once you have created your database and
tables then you would like to insert your data into created tables. This session
will take you through real example on data insert.
• Retrieve Data From MySQL Database − 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.
• Using Paging through PHP − Its always possible that your SQL SELECT
statement query may result into thousand of records. But its is not good idea to
display all the results on one page. So we can divide this result into many pages
as per requirement. Paging means showing your query result in multiple pages
instead of just put them all in one long page. MySQL helps to generate paging
by using LIMIT clause which will take two arguments. First argument as
OFFSET and second argument how many records should be returned from the
database. Below is a simple example to fetch records using LIMIT clause to
generate paging.
• Updating Data Into MySQL Database − Data can be updated into MySQL
tables by executing SQL UPDATE statement through PHP
function mysql_query.
• Deleting Data From MySQL Database − Data can be deleted from MySQL
tables by executing SQL DELETE statement through PHP function
mysql_query.
• Using PHP To Backup MySQL Database − It is always good practice to take a
regular backup of your database. There are three ways you can use to take
backup of your MySQL database. With using SQL Command through PHP,
using MySQL binary mysqldump through PHP and using phpMyAdmin user
interface.

27) How to create the sessions in PHP? Explain.


A session is a way to store information (in variables) to be used across multiple pages.
Unlike a cookie, the information is not stored on the users computer.
A session is started with the session_start() function. Session variables are set with
the PHP global variable: $_SESSION.
Example:
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set."; ?> </body> </html>
Output:
Session variables are set.

28) Discuss briefly about PHP browser handling power. (or) How we can get the
browser properties using php?
PHP has the power of handling browser in terms of using server variables to gain
control of the browser, determining browser type, reading web page data using custom
arrays and validating user-supplied data.

PHP server variables:


$_SERVER is a superglobal array which contains a great deal of information about
what’s going on with the a user’s web application. The $_SERVER[‘PHP_SELF’] can
be used to get the name of the current script, the $SERVER[‘REQUEST METHOD’]
holds the request method that was used (“GET”, “POST”, and so on),
$_SERVER[‘HTTP_USER_AGENT’] holds the type of the user’s browser, and so on.

The following example script can display the script name and the port used to access
it on the server:
<html>
<head>
<title>
Welcome to my script
</title>
</head>

<body>
<h1>Welcome to my script</h1>
<?php
Echo “You have accessed”, $_SERVER(“PHP_SELF”, “on port”,
$_SERVER(“SERVER_PORT”);
?>
</body>
</html>
Output:
Welcome to my script
You have accessed /ch06/phpserver.php on port 80.

In addition to server variables, HTTP headers can also be accessed in the $_SERVER
array as well. These headers are sent by the browser and contain information about
the browser. One useful HTTP header is HTTP_USER_AGENT, which refers to the
user’s browser type: that is, $_SERVER[‘HTTP_USER_AGENT’] holds the user’s type
of browser. Because we have to connect to the user through their browser in web
applications, knowing their browser type can be invaluable in some cases. Some of
the other used HTTP Headers are HTTP_ACCEPT, HTTP_CONNECTION,
HTTP_HOST, HTTP_REFERER.
Example code using HTTP_USER_AGENT header:
<html>
<head>
<title>Determining Browser Type</title>
</head>

<body>
<h1>Determining Browser Type</h1>
<br>
<?php
if(strpos($_SERVER["HTTP_USER_AGENT"], "MSIE")){
echo("<marquee><h1>You're using the Internet
Explorer</h1></marquee>");
}
elseif (strpos($_SERVER["HTTP_USER_AGENT"], "Firefox")) {
echo("<h1>You are using Firefox</h1>");
}
else {
echo("<h1>You are not using Internet Explorer or Firefox</h1>");
}
?>
</body>
</html>
Output:
The following example will explain how $_REQUEST array can be used to collect
user’s info and keep it the server using PHP and reflecting back to the browser:
<html>
<head>
<title>Using one page to accept and process data</title>
</head>

<body>
<h1>Using one page to accept and process data</h1>
<?php
if(isset($_REQUEST["flavor"])){
?>
Your favorite ice cream flavor is
<?php
echo $_REQUEST["flavor"];
}
else {
?>
<form method="post" action="phpone.php">
What's your favorite ice cream flavor?
<input name="flavor" type="text">
<br>
<br>
<input type=submit value=Submit>
</form>
<?php
}
?>
</body>
</html>
Output:
29) How will you create and remove directories with FTP?
The FTP functions give client access to file servers through the File Transfer Protocol
(FTP). The FTP functions are used to open, login and close connections, as well as
upload, download, rename, delete, and get information on files from file servers. Not
all of the FTP functions will work with every server or return the same results. If you
only wish to read from or write to a file on an FTP server, consider using the ftp://
wrapper with the Filesystem functions which provide a simpler and more intuitive
interface.

The ftp_mkdir() function creates a new directory on the FTP server.


Syntax:
ftp_mkdir(ftp_conn, dir);
Here ftp_conn specifies the FTP connection to use and dir specifies the name of the
directory to create.
Example:
<?php
// connect and login to FTP server
$ftp_server = "ftp.example.com";
$ftp_conn = ftp_connect($ftp_server) or die("Could not connect to $ftp_server");
$login = ftp_login($ftp_conn, $ftp_username, $ftp_userpass);

$dir = "images";

// try to create directory $dir


if (ftp_mkdir($ftp_conn, $dir))
{
echo "Successfully created $dir";
}
else
{
echo "Error while creating $dir";
}

// close connection
ftp_close($ftp_conn);
?>

The ftp_rmdir() function deletes a directory on the FTP server. A directory must be
empty before it can be deleted!
Syntax:
ftp_rmdir(ftp_conn, dir);
Here ftp_conn specifies the FTP connection to use and dir specifies the name of the
directory to delete.
Example code:
<?php
// connect and login to FTP server
$ftp_server = "ftp.example.com";
$ftp_conn = ftp_connect($ftp_server) or die("Could not connect to $ftp_server");
$login = ftp_login($ftp_conn, $ftp_username, $ftp_userpass);

$dir = "php/";

// try to delete $dir


if (ftp_rmdir($ftp_conn, $dir))
{
echo "Directory $dir deleted";
}
else
{
echo "Problem deleting $dir";
}
// close connection
ftp_close($ftp_conn);
?>

30) What type of inheritance that PHP supports? Provide an example.


Inheritance in OOP = When a class derives from another class.The child class will
inherit all the public and protected properties and methods from the parent class. In
addition, it can have its own properties and methods. An inherited class is defined by
using the extends keyword.
The types of inheritance which are being supported by PHP are:
• Single inheritance.
• Multi-level inheritance.
• Multiple inheritance.
• Multipath inheritance.
• Hierarchical Inheritance.
• Hybrid Inheritance.

Example:
<?php
class Fruit {
public $name;
public $color;
public function __construct($name, $color) {
$this->name = $name;
$this->color = $color;
}
public function intro() {
echo "The fruit is {$this->name} and the color is {$this->color}.";
}
}

// Strawberry is inherited from Fruit


class Strawberry extends Fruit {
public function message() {
echo "Am I a fruit or a berry? ";
}
}
$strawberry = new Strawberry("Strawberry", "red");
$strawberry->message();
$strawberry->intro();
?>
Output:
Am I a fruit or a berry? The fruit is Strawberry and the color is red.

31) What are the differences between mysql_fetch_array(),


mysql_fetch_object(), mysql_fetch_row()?
mysql_fetch_row ::Return row as aan enumrated array and each line contain a unique
ID .example.
$result=mysql_query($query);
while($row=mysql_fetch_row($result))
{
print "$row[0]";
print "$row[1]";
print "$row[2]";
}

mysql_fetch_array ::Return row as anassociative or an enumrated array or both which


is default .you can refer to outputs as databases fieldname rather then number
.example.
$result=mysql_query($query);
while($row=mysql_fetch_array($result))
{
print "$row['name']";
print "$row['address']";
print "$row['city']";
}

mysql_fetch_object :: it return as an object on the place of array.

$result=mysql_query($query);
while($row=mysql_fetch_object($result))
{
print "$row->name";
print "$row->address";
print "$row->city";
}

You might also like