PHP Programming Q&A Bank
PHP Programming Q&A Bank
(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;
</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;
</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.
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.
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);
<?php
/* First method to create array. */
$numbers = array( 1, 2, 3, 4, 5);
</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
<?php
/* First method to associate create array. */
$salaries = array("mohammad" => 20000, "qadir" => 10000, "zara" =>
5000);
</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
<?php
$marks = array(
"mohammad" => array (
"physics" => 35,
"maths" => 30,
"chemistry" => 39
),
</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
?>
Output:
This will change location of header, i.e. redirect to the URL
Element/Code Description
$_SERVER['PHP_SELF'] Returns the filename of
the currently executing
script
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>';
}
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;
function __clone()
{
// Force a copy of this->object, otherwise
// it will point to same object.
$this->object1 = clone $this->object1;
}
}
print("Original Object:\n");
print_r($obj);
print("Cloned Object:\n");
print_r($obj2);
?>
)
Cloned Object:
MyCloneable Object
(
[object1] => SubObject Object
(
[instance] => 3
)
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).
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.
unlink("test.txt");
?>
// 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:
$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.
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();
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.
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 +).
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.
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>";
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 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);
?>
// 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/'));
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:
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
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);
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.
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
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.
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}();
}
}
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();?>
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.
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.
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.
$dir = "images";
// 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/";
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}.";
}
}
$result=mysql_query($query);
while($row=mysql_fetch_object($result))
{
print "$row->name";
print "$row->address";
print "$row->city";
}