Friday, October 29, 2010

iPhone Project Version Controlling System - SVN

iVersion is an iPhone SVN client which allows developers to edit and manage their code away form their desktop. More information can be found at http://www.benreeves.co.uk.

Here are the Promo code:
WWX3A3WWY7LX, ELTKP7HNXE7L, 7PP4NK969RJ7, A43LWXK6Y4R4, LT4TL6ATTFRM,
F9WLLK4R67PP, EKTN36FYWWLX, 4MPYA3FWPAEA, 6WFTFAM694YY, EKJ79J69YHLY,
T6NNNHHTJLEE, L9WXP9YY36YA, R6LH4M34XH7P, K7K9EAMAEX94, Y4PEMKEXLTWX,
HTHEWNJHPW49, HY34TN7P9LL3, 4FT339Y6PREX, PE9NPP9PE64X, 7MTLPXTPJA66,
ALWM3LLHEPFN, ETF4L94RAFE4, 4K93KNXAH6LN, PW3AW6HHL3MN, WJ9HJL76JHHJ,
W9XLA6RETFL3, WY7WM7H94AEA, 3NJLA3FKHRPN

Tuesday, July 29, 2008

Javascript select / deselect

Javascript code
function checkAll()
{
var field = document.getElementsByName('list[]');
for (i = 0; i < field.length; i++)
field[i].checked = true ;
}

function uncheckAll()
{
var field = document.getElementsByName('list[]');
for (i = 0; i < field.length; i++)
field[i].checked = false ;
}



PHP Code :
if ( isset($_POST['submit']) ) {
//print_r($_POST['list']);
$postCount = count($_POST['list']);

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

//$deleteIds .= $_POST['list'][$i].',';
echo $_POST['list'][$i]."
";

}
}

Sunday, July 27, 2008

Javascript Checkbox Select/Deselect All

<script language="JavaScript"><br /><!-- <!-- Begin function CheckAll(chk) { for (i = 0; i < checked =" true" i =" 0;" checked =" false"><br /></script>

This is the HTML code to be kept inside the body tag.

<form name="myform" action="checkboxes.asp" method="post">

<b>Scripts for Web design and programming</b>


<input name="check_list" value="1" type="checkbox">ASP


<input name="check_list" value="2" type="checkbox">PHP


<input name="check_list" value="3" type="checkbox">JavaScript


<input name="check_list" value="4" type="checkbox">HTML


<input name="check_list" value="5" type="checkbox">MySQL


<input name="Check_All" value="Check All" onclick="CheckAll(document.myform.check_list)" type="button">

<input name="Un_CheckAll" value="Uncheck All" onclick="UnCheckAll(document.myform.check_list)" type="button">


 


 


For PHP code to get check box's value

if ( isset($_POST['Submit']) ) {

$postCount = count($_POST['check_list']);

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

$deleteIds .= $_POST['check_list'][$i].',';

}</form>

Wednesday, January 30, 2008

Shopping Cart Help

*******************Important URL for Coding ***********************
http://de.tikiwiki.org/xref-BRANCH-1-9/nav.html?lang/ca/language.php.source.html

********************************************************
Creating the Database

Let's assume that we're running a website that sells Sony Playstation 2 games. We'll need one table to store the details of each product, and another table to store the contents of each user's shopping cart, so that these details can persist over multiple sessions.

Fire up the MySQL console application and create a database named cart. Populate the database with two tables: items and cart, using this code:

create database cart;

create table items
(
itemId int auto_increment not null,
itemName varchar(50),
itemDesc varchar(250),
itemPrice decimal(4,2),
primary key(itemId),
unique id(itemId)
);

create table cart
(
cartId int auto_increment not null,
cookieId varchar(50),
itemId int,
qty int,
primary key(cartId),
unique id(cartId)

);

The first table, items, will contain a list of items that the user will be able to add to her cart. The items table contains four fields, as described below:

* itemId: A unique numeric identifier that labels each item with its own ID.
* itemName: The name of the item in the catalog.
* itemDesc: A short description of the item in the catalog.
* itemPrice: The price of the item, such as 45.99.

The cart table will store the details of each item in the users cart as she adds them. The cart table also contains four fields, which are described below:

* cartId: A unique numeric identifier that labels each item in the user's cart with an ID.
* cookieId: This is the most important field in both of the tables. It is used to persist the user's cart over multiple sessions. It is the value of the session ID with which the user first started browsing the range of products.
* itemId: The ID of the item that the user is purchasing.
* qty: The number (quantity) of this specific item being purchased.


Displaying the Items

Displaying the list of items from our items table is fairly easy. We'll display the items for sale on one page, and display the shopping cart on another page. We'll also create a file that will store the connection details of the database—along with two functions that will allow us to connect to and work with the database. Create a file called db.php (or open this file from the folder of sample files that you downloaded on the first page of this tutorial) and enter the following code into it:


// This page contains the connection routine for the
// database as well as getting the ID of the cart, etc.

$dbServer = "localhost";
$dbUser = "admin";
$dbPass = "password";
$dbName = "cart";

function ConnectToDb($server, $user, $pass, $database)
{
// Connect to the database and return
// true/false depending on whether or
// not a connection could be made.

$s = @mysql_connect($server, $user, $pass);
$d = @mysql_select_db($database, $s);

if(!$s || !$d)
return false;
else
return true;
}

function GetCartId()
{
// This function will generate an encrypted string and
// will set it as a cookie using set_cookie. This will
// also be used as the cookieId field in the cart table
if(isset($_COOKIE["cartId"]))
{
return $_COOKIE["cartId"];
}
else
{
// There is no cookie set. We will set the cookie
// and return the value of the users session ID

session_start();
setcookie("cartId", session_id(), time() + ((3600 * 24) * 30));
return session_id();
}
}

?>

First, we'll define four variables to hold the details of the MySQL database's server, username, password, and database name respectively. Next, we'll use the ConnectToDb function, which uses our database variables and connects to the MySQL database:

$s = @mysql_connect($server, $user, $pass);
$d = @mysql_select_db($database, $s);

if(!$s || !$d)
return false;
else

return true;

Notice how the calls to mysql_connect and mysql_select_db are prepended with the @ symbol. The @ symbol tells PHP not to produce any errors if the connect fails. If either of the connection or database selection functions fail, then ConnectToDb returns false. Otherwise it returns true, indicating a successful connection.

The GetCartId function makes use of one cookie variable to track a user across multiple sessions. It starts by checking if the cartId cookie variable is set. If not, it grabs the users session ID and sets it as a cookie value which expires in 30 days.

Note: The expiry date of the setcookie function is specified in seconds, so (3600 * 24) * 30 means 3600 seconds ( 1 hour) * 24 (1 day) * 30 (1 month).

The GetCartId function is used in combination with the MySQL cart table to track which user has added which items to their cart.

Db.php is included by both the item listing page and the cart. The item listing page is called products.php. It begins like this:


// This page will list all of the items
// from the items table. Each item will have
// a link to add it to the cart

include("db.php");

// Get a connection to the database
$cxn = @ConnectToDb($dbServer, $dbUser, $dbPass, $dbName);
$result = mysql_query("select * from items order by itemName asc");

?>

As you can see, we include db.php and call the ConnectToDb function to attain a connection to our MySQL database. Next, we grab the entire list of items from the items table and store the result in the $result variable.

Each item will be displayed as part of a table. We'll output some HTML tags and the beginning row of our table before starting a loop through each item, like this:

while($row = mysql_fetch_array($result))
{
?>

For each item, we'll output its name, price, description, and a link to add it to that unique user's shopping cart:









$









Add Item



<<tr>






Finally, we'll close all the table and HTML tags, and display a link to the shopping cart, called cart.php (we'll create the cart.php file in the next section):




Your Shopping Cart >>








After loading up products.php in my browser, you'll receive the following page:
Figure 1. The products.php page displayed in a browser.

Figure 1.The products.php page displayed in a browser.

The "Add Item" link for each item links to cart.php. Now we're ready to create the cart.php page, which allows users to add, update, and delete items from the shopping cart.






Writing the cart.php Script

A shopping cart must perform four functions.

1. It must allow users to add and remove products from their cart.
2. It must allow users to change the quantity of items for each product in their cart.
3. It must allow users to see the products that exist in their cart.
4. It must allow users to see a cumulative total of all of the products in their cart.

Cart.php contains four functions that implement the requirements described above. Cart.php relies on a query string variable, named action, to tell it what to do:


include("db.php");

switch($_GET["action"])
{
case "add_item":
{
AddItem($_GET["id"], $_GET["qty"]);
ShowCart();
break;
}
case "update_item":
{
UpdateItem($_GET["id"], $_GET["qty"]);
ShowCart();
break;
}
case "remove_item":
{
RemoveItem($_GET["id"]);
ShowCart();
break;
}
default:
{
ShowCart();
}
}
?>

The script above uses the $_GET associative array, which was introduced with PHP version 4.1, and was made standard with PHP version 4.2. In PHP 4.2, $HTTP_GET_VARS is deprecated—so you should get into the habit of using $_GET and $_POST instead of $HTTP_GET_VARS and $HTTP_POST_VARS. Using $_GET is quicker too, because it is automatically globally scoped, whereas $HTTP_GET_VARS is not.

Looking at the switch statement above, we have four possible cases. These cases are discussed below:

* add_item: When the user clicks on the "Add Item" button for an item listed on the products.php page, this case is called. It calls the AddItem function, which passed the details of the item's ID number and quantity.
* update_item: This updates the quantity of an item placed in the user's shopping cart. As you will soon see, each item in the cart is displayed with a pop-up list, that, when changed, automatically updates the number of a specific item in the users shopping cart.
* remove_item: This deletes an item from the cart table for the current user.

If the cart.php page is called with no query string parameters, then the ShowCart function is called. Let's start by looking at the AddItem function.

AddItem accepts two parameters: The ID of the item to add to the cart and the quantity (numeric value) for each item that will be purchased:

function AddItem($itemId, $qty)

The main part of the AddItem function checks whether or not this item already exists in the users cart. If it does exist, then the item's quantity field is updated and it isn't added again:

$result = mysql_query("select count(*) from cart where cookieId = '" . GetCartId() . "' and itemId = $itemId");

$row = mysql_fetch_row($result);
$numRows = $row[0];

if($numRows == 0)
{
// This item doesn't exist in the users cart,
// we will add it with an insert query

@mysql_query("insert into cart(cookieId, itemId, qty) values('" . GetCartId() . "', $itemId, $qty)");
}
else
{
// This item already exists in the users cart,
// we will update it instead

UpdateItem($itemId, $qty);
}

Looking at the code above, we can see that if $numRows equals zero (in other words, if the item isn't already in the users cart) then the item is added to the cart table. If not, the items quantity field is updated by calling the UpdateItem function, which is described below.

UpdateItem accepts two parameters, in the same way that the AddItem function does:

function UpdateItem($itemId, $qty)

It executes a simple UPDATE SQL query against the cart table, updating the quantity of one specific item. The cookieId field is used to match the users session ID to that particular product, making sure that the quantity is only updated for that item and the current user:

mysql_query("update cart set qty = $qty where cookieId = '" . GetCartId() . "' and itemId = $itemId");

Removing an item is a simple matter of calling the RemoveItem function. The RemoveItem function accepts only one parameter: the ID of the item to delete:

function RemoveItem($itemId)

Once we've connected to the database, a simple SQL DELETE query removes the item from the current users cart:

mysql_query("delete from cart where cookieId = '" . GetCartId() . "' and itemId = $itemId");

All of these functions are good, but to actually call them, we need to look at the ShowCart function. We'll examine it in the next section of this tutorial.







**************** db.php file ********************************

<?php



// This page contains the connection routine for the

// database as well as getting the ID of the cart, etc



$dbServer = "localhost";

$dbUser = "root";

$dbPass = "";

$dbName = "cart";



function ConnectToDb($server, $user, $pass, $database)

{

// Connect to the database and return

// true/false depending on whether or

// not a connection could be made.



$s = @mysql_connect($server, $user, $pass);

$d = @mysql_select_db($database, $s);



if(!$s || !$d)

return false;

else

return true;

}



function GetCartId()

{

// This function will generate an encrypted string and

// will set it as a cookie using set_cookie. This will

// also be used as the cookieId field in the cart table



if(isset($_COOKIE["cartId"]))

{

return $_COOKIE["cartId"];

}

else

{

// There is no cookie set. We will set the cookie

// and return the value of the users session ID



session_start();

setcookie("cartId", session_id(), time() + ((3600 * 24) * 30));

return session_id();

}

}



?>





**********************************cart.php *************************

<?php



include("db.php");



switch($_GET["action"])

{

case "add_item":

{

AddItem($_GET["id"], $_GET["qty"]);



ShowCart();

break;

}

case "update_item":

{

UpdateItem($_GET["id"], $_GET["qty"]);

ShowCart();

break;

}

case "remove_item":

{

RemoveItem($_GET["id"]);

ShowCart();

break;

}

default:

{

ShowCart();

}

}



function AddItem($itemId, $qty)

{

// Will check whether or not this item

// already exists in the cart table.

// If it does, the UpdateItem function

// will be called instead



global $dbServer, $dbUser, $dbPass, $dbName;



// Get a connection to the database

$cxn = @ConnectToDb($dbServer, $dbUser, $dbPass, $dbName);



// Check if this item already exists in the users cart table

$result = mysql_query("select count(*) from cart where cookieId = '" . GetCartId()
. "' and itemId = $itemId");

$row = mysql_fetch_row($result) or die("failed to execute query");

$numRows = $row[0];



if($numRows == 0)

{

// This item doesn't exist in the users cart,

// we will add it with an insert query



@mysql_query("insert into cart(cookieId, itemId, qty) values('" . GetCartId() .
"', $itemId, $qty)");

}

else

{

// This item already exists in the users cart,

// we will update it instead



UpdateItem($itemId, $qty);

}

}



function UpdateItem($itemId, $qty)

{

// Updates the quantity of an item in the users cart.

// If the qutnaity is zero, then RemoveItem will be

// called instead



global $dbServer, $dbUser, $dbPass, $dbName;



// Get a connection to the database

$cxn = @ConnectToDb($dbServer, $dbUser, $dbPass, $dbName);



if($qty == 0)

{

// Remove the item from the users cart

RemoveItem($itemId);

}

else

{

mysql_query("update cart set qty = $qty where cookieId = '" . GetCartId() . "'
and itemId = $itemId");

}

}



function RemoveItem($itemId)

{

// Uses an SQL delete statement to remove an item from

// the users cart



global $dbServer, $dbUser, $dbPass, $dbName;



// Get a connection to the database

$cxn = @ConnectToDb($dbServer, $dbUser, $dbPass, $dbName);



mysql_query("delete from cart where cookieId = '" . GetCartId() . "' and itemId
= $itemId");

}



function ShowCart()

{

// Gets each item from the cart table and display them in

// a tabulated format, as well as a final total for the cart



global $dbServer, $dbUser, $dbPass, $dbName;



// Get a connection to the database

$cxn = @ConnectToDb($dbServer, $dbUser, $dbPass, $dbName);



$totalCost = 0;

$result = mysql_query("select * from cart inner join items on cart.itemId =
items.itemId where cart.cookieId = '" . GetCartId() . "' order by items.itemName
asc");

?>

<html>

<head>

<title> Your Shopping Cart </title>

<script language="JavaScript">



function UpdateQty(item)

{

itemId = item.name;

newQty = item.options[item.selectedIndex].text;



document.location.href = 'cart.php?action=update_item&id='+itemId+'&qty='+newQty;

}



</script>

</head>

<body bgcolor="#ffffff">

<h1>Your Shopping Cart</h1>

<form name="frmCart" method="get">

<table width="100%" cellspacing="0" cellpadding="0" border="0">

<tr>

<td width="15%" height="25" bgcolor="red">

<font face="verdana" size="1" color="white">

&nbsp;&nbsp;<b>Qty</b>

</font>

</td>

<td width="55%" height="25" bgcolor="red">

<font face="verdana" size="1" color="white">

<b>Product</b>

</font>

</td>

<td width="20%" height="25" bgcolor="red">

<font face="verdana" size="1" color="white">

<b>Price Each</b>

</font>

</td>

<td width="10%" height="25" bgcolor="red">

<font face="verdana" size="1" color="white">

<b>Remove?</b>

</font>

</td>

</tr>

<?php



while($row = mysql_fetch_array($result))

{

// Increment the total cost of all items

$totalCost += ($row["qty"] * $row["itemPrice"]);

?>

<tr>

<td width="15%" height="25">

<font face="verdana" size="1" color="black">

<select name="<?php echo $row["itemId"]; ?>" onChange="UpdateQty(this)">

<?php



for($i = 1; $i <= 20; $i++)

{

echo "<option ";

if($row["qty"] == $i)

{

echo " SELECTED ";

}

echo ">" . $i . "</option>";

}

?>

</select>

</font>

</td>

<td width="55%" height="25">

<font face="verdana" size="1" color="black">

<?php echo $row["itemName"]; ?>

</font>

</td>

<td width="20%" height="25">

<font face="verdana" size="1" color="black">

$<?php echo number_format($row["itemPrice"], 2, ".", ","); ?>

</font>

</td>

<td width="10%" height="25">

<font face="verdana" size="1" color="black">

<a href="cart.php?action=remove_item&id=<?php echo $row["itemId"];
?>">Remove</a>

</font>

</td>

</tr>

<?php

}



// Display the total

?>

<tr>

<td width="100%" colspan="4">

<hr size="1" color="red" NOSHADE>

</td>

</tr>

<tr>

<td width="70%" colspan="2">

<font face="verdana" size="1" color="black">

<a href="products.php">&lt;&lt; Keep Shopping</a>

</font>

</td>

<td width="30%" colspan="2">

<font face="verdana" size="2" color="black">

<b>Total: $<?php echo number_format($totalCost, 2, ".", ","); ?></b>

</font>

</td>

</tr>

</table>

</form>

</body>

</html>

<?php

}



?>




********************************products.php ********************************

<?php



// This page will list all of the items

// from the items table. Each item will have

// a link to add it to the cart



include("db.php");



// Get a connection to the database

$cxn = @ConnectToDb($dbServer, $dbUser, $dbPass, $dbName);

$result = mysql_query("select * from items order by itemName asc");

?>

<html>

<head>

<title> Product List </title>

</head>

<body bgcolor="#ffffff">

<h1>Products</h1>

<table width="100%" cellspacing="0" cellpadding="0" border="0">

<tr>

<td width="30%" height="25" bgcolor="red">

<font face="verdana" size="1" color="white">

&nbsp;&nbsp;<b>Product</b>

</font>

</td>

<td width="10%" height="25" bgcolor="red">

<font face="verdana" size="1" color="white">

<b>Price</b>

</font>

</td>

<td width="50%" height="25" bgcolor="red">

<font face="verdana" size="1" color="white">

<b>Description</b>

</font>

</td>

<td width="10%" height="25" bgcolor="red">

<font face="verdana" size="1" color="white">

<b>Add</b>

</font>

</td>

</tr>

<?php

while($row = mysql_fetch_array($result))

{

?>

<tr>

<td width="30%" height="25">

<font face="verdana" size="1" color="black">

<?php echo $row["itemName"]; ?>

</font>

</td>

<td width="10%" height="25">

<font face="verdana" size="1" color="black">

$<?php echo $row["itemPrice"]; ?>

</font>

</td>

<td width="50%" height="25">

<font face="verdana" size="1" color="black">

<?php echo $row["itemDesc"]; ?>

</font>

</td>

<td width="10%" height="25">

<font face="verdana" size="1" color="black">

<a href="cart.php?action=add_item&id=<?php echo $row["itemId"]; ?>&qty=1">Add
Item</a>

</font>

</td>

</tr>

<tr>

<td width="100%" colspan="4">

<hr size="1" color="red" NOSHADE>

</td>

</tr>

<?php

}

?>

<tr>

<td width="100%" colspan="4">

<font face="verdana" size="1" color="black">

<a href="cart.php">Your Shopping Cart &gt;&gt;</a>

</font>

</td>

</tr>

</table>

</body>

</html>



**************************

Tuesday, January 29, 2008

PHP Interview Questions & Answers Part 2

How can you analyse file uploading ($_FILES) in php?
You can analyse by printing the $_FILES global array using

echo "
";
print_r($_FILES);
How can we reset a cookie in php?
Reset a cookie by specifying its name only
Example: setcookie('w3answers');
Is it possible to eject a CD-ROM from a WINDOWS based OS using PHP?
Yes it is possible.We have to use PHP's COM Methods
ANS:

//create an instance of Windows Media Player
$mp = new COM("WMPlayer.OCX");
//ejects the first cd-rom on the drive list
$mp->cdromcollection->item(0)->eject();
?>

How will we disable the registering of session variables through the $_SESSION
super global ?
Do NOT unset the whole $_SESSION with unset($_SESSION) as this will disable the registering of session variables through the $_SESSION superglobal.
**********************************
Answer is from PHP Manual
refer session_unset function
**********************************

What is the purpose of the open_basedir directive?
A. To indicate the directory that include() calls will use as a base.
B. To restrict file open access to a specific directory.
C. To set the working directory.
D. To allow additional file open access than that granted by safe_mode.
Answer B is correct.
Answer A is incorrect because the behavior of include() is
unchanged.
Answer C is incorrect because the working directory does not depend
on open_basedir.
Answer D is incorrect because open_basedir is not affected by
whether safe_mode is enabled

Which of the following functions can be used to escape data such that it can be displayed without altering the appearance of the original data?
A. htmlspecialchars()
B. addslashes()
C. escapeshellargs()
D. urlencode()

Answer A is correct because htmlspecialchars() will convert special characters
to HTML entities that will display correctly in any Web client.
Answer B is incorrect because addslashes() only escapes single quotes.
Answer C is incorrect because escapeshellargs() is only helpful when dealing with shell command arguments.
Answer D is incorrect because URL encoding is not interpreted by
Web clients except in the context of URLs
When is cross-site scripting a heightened risk?
A. When storing data submitted by the user.
B. When displaying foreign data.
C. When executing a shell command.
D. When opening a remote URL.

Answer B is correct.
When displaying foreign data that is not properly escaped, you
can inadvertently expose your users to significant risk.
Answer A is incorrect because storing data poses no immediate threat, even though this might result in a cross-site scripting vulnerability later.
Answers C and D are incorrect because these activities are unrelated

What is the purpose of the escapeshellarg() function?
A. To prepare data so that it can be used as a single argument in a shell command.
B. To remove malicious characters.
C. To escape metacharacters, so that they can’t be used to execute arbitrary
commands.
D To remove arguments from a shell command.

Answer A is correct.
Answers B and D are incorrect because escapeshellarg()
does not remove characters.
Answer C is incorrect because escapeshellarg()
does not attempt to solve this problem

What is the purpose of the escapeshellcmd() function?
A. To prepare data so that it can be used as a single argument in a shell command.
B. To remove malicious characters.
C. To escape metacharacters, so that they can’t be used to execute arbitrary
commands.
D. To prevent cross-site scripting attacks.

Answer C is correct.
Answer A is incorrect because escapeshellcmd() does not
attempt to solve this problem.
Answer B is incorrect because escapeshellcmd() does not actually remove characters.
Answer D is incorrect because escaping data to protect against cross-site scripting is much different than escaping data to be used in a shell command

What are the two most important practices to mitigate the risk of an SQL
injection vulnerability?
A. Disabling register_globals and enabling safe_mode.
B. Enabling safe_mode and filtering any data used in the construction of the
SQL statement.
C. Filtering and escaping any data used in the construction of the SQL statement.
D. Disabling register_globals and escaping any data used in the construction
of the SQL statement.
Answer C is correct.
With properly filtered data, escaping any metacharacters that
remain can mitigate the remaining risks.
Answers A, B, and D are incorrect because
register_globals does not directly affect the risk of SQL injection, and
safe_mode is unrelated

With register_globals enabled, which of the following practices is
particularly important?
A. Initialize all variables.
B. Filter all foreign data.
C. Escape all data used in SQL statements.
D. Escape all data prior to output.

Answer A is correct.
Answers B, C, and D are incorrect
because these practices are not dependent on
whether register_globals is enabled

The PHP date functions are only guaranteed to work for dates after _____.
A. January 1, 1970 00:00:00
B. January 1, 1900 00:00:00
C. January 1, 1963 00:00:00
D. January 18, 2038 22:14:07

The correct answer is A.
The UNIX epoch is January 1, 1970 00:00:00 UTC. On
32-bit systems, the date functions are only guaranteed
to work until January 19,2038.

Which of the following functions will output the current time as 11:26 pm?
A. print date(‘H:m a’);
B. print date(‘G:M a’);
C. print date(‘G:i a’);
D. print strftime(‘%I:%M %p’);

The correct answers are C and D

The ________ function will return the current UNIX time stamp.
The correct answer is time().

Which of the following sentences are incorrect?
A. date() returns the current UNIX datestamp.
B. date() returns a formatted date string.
C. date() requires a time stamp to be passed to it.
D. date() returns a date array.

The correct answers are A, C, and D.
date() takes a format string and an optional time stamp and produces a formatted date string. If a UNIX time stamp is not passed into date(), it will use the current time

Which of the following functions require an open file resource?
A. fgets()
B. fopen()
C. filemtime()
D. rewind()
E. reset()

The correct answers are A and D. fgets() and rewind() both act on an open file
resource. fopen() opens files to create resources, whereas filemtime() takes a filename and reset() acts on arrays

If you have an open file resource, you can read data from it one line at a time with the _____ function.
The correct answer is fgets().

Which of the following can be used to determine if a file is readable?
A. stat()
B. is_readable()
C. filetype()
D. fileowner()
E. finfo()


The correct answers are A and B.
stat() returns an array of information about a
file, including who owns it and what its permission mode is.Together these are
sufficient to tell if a file is readable.
is_readable(), as the name implies, returns
true if a file is readable.

What are the contents of output.txt after the following code snippet is run?

$str = ‘abcdefghijklmnop’;
$fp = fopen(“output.txt”, ‘w’);
for($i=0; $i< 4; $i++) {
fwrite($fp, $str, $i);
}

?>

A. abcd
B. aababcabcd
C. aababc
D. aaaa

The correct answer is C.

On the first iteration, $i is 0, so no data is written.
On the second iteration $i is 1, so a is written. On the third, ab is written,
and on the fourth abc is written.Taken together, these are aababc.

Which of the following output ‘True’?
A. if(“true”) { print “True”; }

B. $string = “true”;
if($string == 0) { print “True”; }

C. $string = “true”;
if(strncasecmp($string, “Trudeau”, 4)) { print “True”; }

D. if(strpos(“truelove”, “true”)) { print “True”; }

E. if(strstr(“truelove”, “true”)) { print “True”; }

Answers A, B, C, and E are correct.
Answer A is correct because a non-empty
string will evaluate to true inside an if() block.
Answer B is correct when comparing a string and an integer with ==, PHP will convert the string into an integer. ‘true’ converts to 0, as it has no numeric parts.
In answer C, strncasecmp() returns 1 because the first four characters of ‘Trud’ come before the first four characters of true when sorted not case sensitively.
Answer D is incorrect because strpos() returns 0 here (true matches truelove at offset 0).We could make this return True by requiring strpos() to be !== false.
:)
Answer E is correct because strstr() will return the entire string, which will evaluate to true in the if() block.

If $time = ‘Monday at 12:33 PM’; or $time = ‘Friday the 12th at 2:07
AM’; which code fragment outputs the hour (12 or 2, respectively)?
A. preg_match(‘/\S(\d+):/’, $time, $matches);
print $matches[1];
B. preg_match(‘/(\w+)\Sat\S(\d+):\d+/’, $time, $matches);
print $matches[2];
C. preg_match(‘/\s([a-zA-Z]+)\s(\w+)\s(\d+):\d+/’, $time,
$matches);
print $matches[3];
D. preg_match(‘/\s(\d+)/’, $time, $matches);
print $matches[1];
E. preg_match(‘/\w+\s(\d+):\d+/’, $time, $matches);
print $matches[1];

Answer E is correct.
Answer A and B both fail because \S matches nonwhitespace
characters, which break the match. Answer C will correctly match the first $time
correctly, but fail on the second because ‘12th’ will not match [a-zA-Z]. Answer D
matches the first, but will fail on the second, capturing the date (12) instead of the hour.
Which question will replace markup such as img=/smiley.png with
src=”/smiley.png”>?
A. print preg_replace(‘/img=(\w+)/’, ‘’, $text);
B. print preg_replace(‘/img=(\S+)/’, ‘’, $text);
C. print preg_replace(‘/img=(\s+)/’, ‘’, $text);
D. print preg_replace(‘/img=(\w)+/’, ‘’, $text);

Answer B is correct.
The characters / and . are not matched by \w (which only
matches alphanumerics and underscores), or by \s (which only matches whitespace).

Given $email = ‘bob@example.com’; which code block will output example.com?
A. print substr($email, -1 * strrpos($email, ‘@’));
B. print substr($email, strrpos($email, ‘@’));
C. print substr($email, strpos($email, ‘@’) + 1);
D. print strstr($email, ‘@’);
Answer C is correct.
strpos() identifies the position of the @ character in the string.To capture only the domain part of the address, you must advance one place to the first character after the @.

Tell me the following scripts output
$a = array (‘a’ => 20, 1 => 36, 40);
array_rand ($a);
echo $a[0];
?>
A. A random value from $a
B. ‘a’
C. 20
D. 36
E. Nothing
Only E is correct.
The $a array doesn’t have any element with a numeric key of
zero, and the array_rand() function does not change the keys of the array’s elements only their order.

Which of the following functions can be used to sort an array by its keys
in descending order?
A. sort
B. rsort
C. ksort
D. krsort
E. reverse_sort

D is correct.

The sort() and rsort() functions operate on values, whereas
ksort() sorts in ascending order and reverse_sort() is not a PHP function
Which of the following types can be used as an array key? (Select three.)
A. Integer
B. Floating-point
C. Array
D. Object
E. Boolean

Answers A, B, and E are correct.

A Boolean value will be converted to either 0 if
it is false or 1 if it is true, whereas a floating-point value will be truncated to its integer equivalent.

Arrays and objects, however, cannot be used under any circumstance
Which of the following functions allows you to store session data in a database?
A. session_start();
B. session_set_save_handler();
C. mysql_query();
D. You cannot store session data in a database.

Answer B is correct.

You can use session_set_save_handler() to override
PHP’s default session-handling functions and store session data any way you want.
Answer A is incorrect because session_start() only activates PHP sessions for
the current script. Answer C is incorrect because mysql_query() only executes a
query with MySQL and does not affect the behavior of PHP’s session mechanism.
Answer D is incorrect because this statement is false.
Why must you call session_start() prior to any output?
A. Because it is easy to forget if not placed at the top of your scripts.
B. Because you can no longer access the session data store after there has been
output.
C. Because session_start() sets some HTTP headers.
D. Because calling session_start() causes the HTTP headers to be sent.

Answer C is correct.

Answer A is incorrect because this is a technical necessity, not
a best practice. Answer B is incorrect because accessing the session data store is
completely independent of whether there has been any output. Answer D is incorrect
because you can set other HTTP headers after a call to session_start().
If you set a cookie with either setcookie() or header(), you can
immediately check to see whether the client accepted it. True or False ,comment it
A. True, you can check the $_COOKIE superglobal array to see if it contains the
value you set.
B. True, but only if register_globals is enabled.
C. False, you can only use setcookie() if you need to test for acceptance.
Using header() does not work.
D. False, you must wait until you receive another HTTP request to determine
whether it includes the Cookie header.

Answer D is correct.

The response that contains the Set-Cookie header is not sent
until PHP finishes executing, so you cannot test for acceptance prior to this.
Answers A and B are incorrect because the answer is false. Answer C is incorrect
because using setcookie() and header() both result in the same thing: A Set-
Cookie header is included in the response.

When an expiration date is given in a Set-Cookie header, what is the
resulting behavior in subsequent requests?
A. If the expiration date has expired, the cookie is not included.
B. The behavior is the same; the expiration date is included in the Cookie
header, and you can access this information in the $_COOKIE superglobal
array.
C. The cookie persists in memory until the browser is closed.
D. The cookie is deleted and therefore not included in subsequent requests.

Answer A is correct.

Answer B is incorrect because only the name and value of the
cookie are included in the Cookie header. Answer C is incorrect because setting
an expiration date causes a cookie to either be deleted (if the date has expired) or written to disk. Answer D is incorrect because the cookie is only deleted if the date has expired, which isn’t necessarily the case.

Which of the following form element names can be used to create an array
in PHP?
A. foo
B. [foo]
C. foo[]
D. foo[bar]

Answer C is correct.

PHP will create an enumerated array called foo that contains
the values of all form elements named foo[] in the HTML form.Answers A, B,
and D are incorrect because any subsequent form elements of the same name will
overwrite the value in previous elements.
When processing the form, what is the difference between a hidden form
element and a non hidden one, such as a text box?
A. The hidden form element does not have a name.
B. There is no difference.
C. The hidden form element does not have a value.
D. The hidden form element is excluded from the request.

Answer B is correct.

When processing a form, each form element is simply a
name/value pair within one of the superglobal arrays. Answers A and C are incorrect because hidden form elements can (and should) have both a name and a
value. Answer D is incorrect because hidden form elements are only excluded
from the user’s view, not from the HTTP request
Which types of form elements can be excluded from the HTTP request?
A. text, radio, and check box
B. text, submit, and hidden
C. submit and hidden
D. radio and check box

Answer D is correct.

When not selected, both radio buttons and check boxes are
excluded from the HTTP request. Answer A and B are incorrect because text
boxes are always included in the request. Answer C is incorrect because hidden
form elements are always included.
Is it possible to pass data from PHP to JavaScript?
A. No, because PHP is server-side, and JavaScript is client-side.
B. No, because PHP is a loosely typed language.
C. Yes, because JavaScript executes before PHP.
D. Yes, because PHP can generate valid JavaScript.

Answer D is correct.

JavaScript, like HTML, can be dynamically generated by
PHP. Answers A and B are incorrect because the answer is yes. Answer C is incorrect because PHP executes before JavaScript.
What will be the following script output?
error_reporting(E_ALL);
class a
{
var $c;
function a()
{
$this->c = 10;
}
}
class b extends a
{
function print_a()
{
echo $this->c;
}
}
$b = new b;
$b->print_a();

?>

A. Nothing
B. An error because b does not have a constructor
C. 10
D. NULL
E. False

Answer C is correct.

Because the class b does not have a constructor, the constructor of its parent class is executed instead.This results in the value 10 being assigned to the $c member property.
When serializing and unserializing an object, which of the following
precautions should you keep in mind? (Choose two)
A. Always escape member properties that contain user input.
B. If the object contains resource variables, use magic functions to restore the
resources upon unserialization.
C. Use the magic functions to only save what is necessary.
D. Always use a transaction when saving the information to a database.
E. If the object contains resource variables, it cannot be serialized without first destroying and releasing its resources.

Answers B and C are correct.

Whenever you design an object that is meant to be
serialized or that can contain resource objects, you should implement the appropriate magic functions to ensure that it is serialized and unserialized properly—and using the smallest amount of information possible
What will be the following script output?

class a
{
var $c;
function a ($pass)
{
$this->c = $pass;
}
function print_data()
{
echo $this->$c;
}
}
$a = new a(10);
$a->print_data();

?>

A. An error
B. 10
C. “10”
D. Nothing
E. A warning

Answer D is correct.

There actually is a bug in the print_data() function—
$this->$c is interpreted as a variable by PHP, and because the $c variable is not
defined inside the function, no information will be available for printing. Note
that if error reporting had been turned on, either through a php.ini setting or
through an explicit call to error_reporting(), two warnings would have been
outputted instead—but, unless the exam question tells you otherwise, you should
assume that the normal PHP configuration is being used. And in that case, the
interpreter is set not to report warnings.
What will be the following script output?
$a = 1;
$a = $a— + 1;
echo $a;
?>

A. 2
B. 1
C. 3
D. 0
E. Null

Answer B is correct.
Which data type will the $a variable have at the end of the following script?
$a = “1”;
echo $x;
?>

A. (int) 1
B. (string) “1”
C. (bool) True
D. (float) 1.0
E. (float) 1

Answer B is correct.

When a numeric string is assigned to a variable, it remains
a string, and it is not converted until needed because of an operation that
requires so.
What will be the following script output?
$x = 3 - 5 % 3;
echo $x;
?>
A. 2
B. 1
C. Null
D. True
E. 3

Answer B is correct.

Because of operator precedence, the modulus operation is
performed first, yielding a result of 2 (the remainder of the division of 5 by 2).
Then, the result of this operation is subtracted from the integer 3.

PHP Interview Questions & Answers

Web Development PHP

Difference between echo and print?
void echo ( string $arg1 [, string $...] )
Outputs all parameters.
echo() is not actually a function (it is a language construct), so you are not required to use parentheses with it. echo() (unlike some other language constructs) does not behave like a function, so it cannot always be used in the context of a function. Additionally, if you want to pass more than one parameter to echo(), the parameters must not be enclosed within parentheses.

echo() also has a shortcut syntax, where you can immediately follow the opening tag with an equals sign. This short syntax only works with the short_open_tag configuration setting enabled.
I have foo.

print --- out put a string
print behaves like a function and you can return values and echo can't
Prin can be used as a part of more complex operations

What is the use of ob_start in php?
ob_start — Turn on output buffering
According to PHP manual*
Description
bool ob_start ( [callback $output_callback [, int $chunk_size [, bool $erase]]] )
This function will turn output buffering on. While output buffering is active no output is sent from the script (other than headers), instead the output is stored in an internal buffer.
The contents of this internal buffer may be copied into a string variable using ob_get_contents(). To output what is stored in the internal buffer, use ob_end_flush(). Alternatively, ob_end_clean() will silently discard the buffer contents.
Warning
Some web servers (e.g. Apache) change the working directory of a script when calling the callback function. You can change it back by e.g. chdir(dirname($_SERVER['SCRIPT_FILENAME'])) in the callback function.
Output buffers are stackable, that is, you may call ob_start() while another ob_start() is active. Just make sure that you call ob_end_flush() the appropriate number of times. If multiple output callback functions are active, output is being filtered sequentially through each of them in nesting order.

How to reverse an array values using recursive method in php ?
$array=array(1,2,3,4,5,6);
rec($array,5);
echo $f1= substr($f,0,-1);
function rec($arr,$index)
{
global $f;
if($index==-1)
return;
$f.=$arr[$index].',';
$index--;
rec($arr,$index);

}

?>

//Output: 6,5,4,3,2,1

How to reverse a string in php with out using any built in functions?

function w3RevStr($str) {
$revStr = "";
$w=0;
while($c=$str[$w]){
$revStr = $c.$revStr;
$w=$w+1;
}
return $revStr;
}
echo w3RevStr("www.w3answers.com");
?>


How many HTTP headers will send to a web page(client side) from server when you use sessions (session_start()) in php ?.
There are three HTTP headers included in the response:
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache

what are the advantages of storing sessions in database?
If you store a session in a database you have several advantages:
@ Improving the security because on many hosting packages (shared host)
PHP uses the same path for storing sessions for all the users,
somewhere that is not in your folders.
@ You can track who is online etc.
@ For application that are running on multiple servers, you can store
all the session data in one database.
The real beauty of this approach is that you don't have to modify your code or the way you use sessions in any way. $_SESSION still exists and behaves the same way, PHP still takes care of generating and propagating the session identifier, and changes made to session configuration directives still apply. All you have to do is call this one function.

You must call session_set_save_handler() prior to calling session_start(), but you can define the functions themselves anywhere.

The function is called session_set_save_handler(), and it takes six arguments,

1. Opening the session data store
2. Closing the session data store
3. Reading session data
4. Writing session data
5. Destroying all session data
6. Cleaning out old session data

How to get the contents of a web page using php?
you can achieve this using curl in php

see the example below.
function curl_get_con_url($url, $user_agent = '', $referer = '') {
// create a new CURL resource
$ch = curl_init();

// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, false);

/* This lines will make sure that you can save the web page into a variable */
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);
curl_setopt($ch, CURLOPT_REFERER, $referer);

// grab URL
$page_content = curl_exec($ch);

if (curl_errno($ch)) {
$page_content = false;
}

// close CURL resource, and free up system resources
curl_close($ch);

return $page_content;
}



$referads_pc = curl_get_con_url('www.referads.com');

what are the security tips you should know before developing php/mysql web pages ?

1. Do not trust user input.
2. Validate user input on the server side.
3. Do not use user input directly in your MySQL queries.
4. Don't put integers in quotes In your MySQL queries.
5. Always escape the output using php built in functions.
6. When uploading files, validate the file mime type using php.
7. If you are using 3rd party code libraries, be sure to keep them up to date.
8. Give your database users just enough permissions.
9. Do not allow hosts other than localhost to connect to your database.
10. Your library file extensions should be PHP.
11. Have register globals off or define your variables first
12. Keep PHP itself up to date (use latest version php5 or above)


what are the database space-saving functions available in php ?
Use ip2long() and long2ip() to store the IP adresses as Integers instead of storing them as strings, which will reduce the space from 15 bytes to 4 bytes. This will also increase search speed and make it easy to see if a ip falls within a specified range.

# Use gzcompress() and gzuncompress() to reduce the strings before you store them in a database. The gzcompress can compress plain-text up to 90%. The only reason why you shouldn’t use it is when you need full-text indexing capabilities.

what you should know about cookies before start using in php?
There are a few things you should be aware of:

1. Since cookies are used to record information about your activities on a particular domain, they can only be read by the domain that created them

2. A single domain cannot set more than twenty cookies, and each cookie is limited to a maximum size of 4 KB

3. A cookie usually possesses six attributes, of which only the first is mandatory. Here they are:
* name: the name of the cookie
* value: the value of the cookie
* expires: the date and time at which the cookie expires
* path: the top-level directory on the domain from which cookie data can be accessed
* domain: the domain for which the cookie is valid
* secure: a Boolean flag indicating whether the cookie should be transmitted only over a secure HTTP connection

It's important to remember that, since cookies are stored on the user's hard drive, you as the developer have very little control over them. If a user decides to turn off cookie support in his or her browser, your cookies will simply not be saved. Therefore, avoid writing code that depends heavily on cookies; and have a backup plan ready in case cookie data cannot be retrieved from the client.

Two types of cookies

1) temporary and
2) persistent cookies

Given a line of text $string, how would you write a regular expression to strip all the HTML tags from it?

$stringOfText = "

This is a test

";

$expression = "/<(.*?)>(.*?)<\/(.*?)>/";

echo preg_replace($expression, "\\2", $stringOfText);

what are the ways to check image mime types in php?

There are a few inbuilt options you can use however, for example getimagesize() can return the mimetype, as does some of the new fileinfo functions. The mime type in getimagesize is stored in 'mime', and can be accessed as shown below.


$parts = getimagesize($filename);
echo $parts['mime'];

?>
or
$parts = getimagesize($filename);
$allowedMimes = array('image/jpg', 'image/png', 'image/gif');

if(in_array($parts['mime'], $allowedMimes))
echo 'Valid Mimetype!';
?>

other way


$filename = 'maliciousScript.jpg.php'; // filename to check
$parts = explode('.', $filename); // common (but wrong) method used
echo $parts[1];
echo strrchr($filename, '.'); // correct method
?>

echo system('file -ib '. $filename);
?>

how to opening excel files in windows nad linux using php ?

if you're using PHP on Windows, you can use the inbuilt COM library

$excel = new COM("excel.application");
$excel->Workbooks->Open("filename.xls");

On Linux machines, is PHPExcelReader( download from sourceforgr.net), and it seems to work very efficiently and easily with only a few lines of code.

$data = new Spreadsheet_Excel_Reader();
$data->read("filename.xls");

And you can access the data with a simple loop:

for($i=1; $i <= $data->sheets[0]['numRows']; $i++)
{

echo 'Row '. $i .', Column a:' $data->sheets[0]['cells'][$i][1] . '
';
echo 'Row '. $i .', Column b:' $data->sheets[0]['cells'][$i][2] . '
';

}

How many ways your web server can utilize PHP to generate web pages?
Mainly there are three ways
***************************
The first method is to use PHP as a CGI "wrapper". When run this way, an instance of the PHP interpreter is created and destroyed for every page request (for a PHP page) to your web server. Because it is destroyed after every request, any resources that it acquires (such as a link to an SQL database server) are closed when it is destroyed. In this case, you do not gain anything from trying to use persistent connections -- they simply don't persist.

The second, and most popular, method is to run PHP as a module in a multiprocess web server, which currently only includes Apache. A multiprocess server typically has one process (the parent) which coordinates a set of processes (its children) who actually do the work of serving up web pages. When a request comes in from a client, it is handed off to one of the children that is not already serving another client. This means that when the same client makes a second request to the server, it may be served by a different child process than the first time. When opening a persistent connection, every following page requesting SQL services can reuse the same established connection to the SQL server.

The last method is to use PHP as a plug-in for a multithreaded web server. Currently PHP 4 has support for ISAPI, WSAPI, and NSAPI (on Windows), which all allow PHP to be used as a plug-in on multithreaded servers like Netscape FastTrack (iPlanet), Microsoft's Internet Information Server (IIS), and O'Reilly's WebSite Pro. The behavior is essentially the same as for the multiprocess model described before. Note that SAPI support is not available in PHP 3.

What is meant by Persistent Database Connections?
Persistent connections are links that do not close when the execution of your script ends. When a persistent connection is requested, PHP checks if there's already an identical persistent connection (that remained open from earlier) - and if it exists, it uses it. If it does not exist, it creates the link. An 'identical' connection is a connection that was opened to the same host, with the same username and the same password (where applicable).
Note
*****
People who aren't thoroughly familiar with the way web servers work and distribute the load may mistake persistent connects for what they're not. In particular, they do not give you an ability to open 'user sessions' on the same link, they do not give you an ability to build up a transaction efficiently, and they don't do a whole lot of other things. In fact, to be extremely clear about the subject, persistent connections don't give you any functionality that wasn't possible with their non-persistent brothers.

Its extremely simple and efficient. Persistent connections are good if the overhead to create a link to your SQL server is high. Whether or not this overhead is really high depends on many factors. Like, what kind of database it is, whether or not it sits on the same computer on which your web server sits, how loaded the machine the SQL server sits on is and so forth. The bottom line is that if that connection overhead is high, persistent connections help you considerably. They cause the child process to simply connect only once for its entire lifespan, instead of every time it processes a page that requires connecting to the SQL server. This means that for every child that opened a persistent connection will have its own open persistent connection to the server. For example, if you had 20 different child processes that ran a script that made a persistent connection to your SQL server, you'd have 20 different connections to the SQL server, one from each child.

List out some session functions in php?
session_save_path -- Get and/or set the current session save path
session_is_registered -- Find out whether a global variable is registered in a session
session_unset -- Free all session variables
session_cache_expire -- Return current cache expire
session_cache_limiter -- Get and/or set the current cache limiter
session_commit -- Alias of session_write_close()
session_decode -- Decodes session data from a string
session_destroy -- Destroys all data registered to a session
session_write_close -- Write session data and end session
session_encode -- Encodes the current session data as a string
session_get_cookie_params -- Get the session cookie parameters
session_id -- Get and/or set the current session id
session_module_name -- Get and/or set the current session module
session_name -- Get and/or set the current session name
session_regenerate_id -- Update the current session id with a newly generated one
session_register -- Register one or more global variables with the current session
session_set_cookie_params -- Set the session cookie parameters
session_set_save_handler -- Sets user-level session storage functions(Like storing to Databases like MySQl,Oracle etc)
session_start -- Initialize session data
session_unregister -- Unregister a global variable from the current session

What is the process that takes place when you upload a file in php?
There are two basic things covered here.
The form that will be used to post the file data to and the actual program that does the uploading. Further we will discuss the method that PHP itself suggests for uploading files.

Process 1 HTML PART
*******************


Upload a file:



Note the enctype is set to "multipart/form-data".
This is crucial to the working of the application. If it is not specified here then the program will not work.

Next you'll notice that MAX_FILE_SIZE precedes the file input field. The MAX_FILE_SIZE for this demonstration is limited to 30000 bytes, or about 29K, but can easily be modified for larger files.

Finally you have the input sections. The first is set to create an input box that allows the user to choose his file and the second is the button that actually submits the file for upload. In the next section you'll notice that the name of the input element for type="file" will be used to determine the name to pull from the $_FILES array.

Form Method must be POST

Process 2 PHP PART
******************
$imgdir = '/imgdir/';
$uploadfile = $imgdir. basename($_FILES['smefile']['name']);
if (move_uploaded_file($_FILES[ 'smefile']['tmp_name'], $uploadfile)) {
echo "File successfully uploaded";
} else {
echo "Upload failed";
}
?>

Will persistent connection work in the CGI version of php ? mysql_connect() vs mysql_pconnect()
Persistent database connections work only in the module installation of PHP.
If you ask for a persistent connection in the CGI version,
you will simply get a regular connection.

if you become convinced that the sheer overhead of opening new database connections is killing your performance, you might want to investigate opening persistent connections.Unlike regular database connections, these connections are not automatically killed when your page exits (or even when mysql_close() is called) but are saved in a pool for future use. The first time one of your
scripts opens such a connection, it is opened in the same resource-intensive way as with a regular database connection. The next script that executes,however, might get that very same connection in response to its request, which saves the cost of reopening a fresh connection. (The previous connection will be reused only if the
parameters of the new request are identical.)

Other than offering a particular kind of increased efficiency, persistent
database connections do not provide any functionality beyond that of regular database connections.

What are the 'function problems' you have met in php?
1)Call to undefined function we_w3answers()
*****************************************
PHP is trying to call the function we_w3answers(), which has not been
because you misspelled the name of a function (built-in or user-defined)
simply omitted the function definition. If you use include/require
functions, make sure that you are loading the appropriate files.

2)Call to undefined function array()
***********************************
This problem has a cause that is similar to the cause of the previous problem, although it still baffled us completely the first time we ran into it. It can arise when you have code like the following:

$my_w3answers= array();
$my_w3answers(5) = “the fifth”;

3)Cannot redeclare my_function()
*******************************
This is a simple one—somewhere in your code you have two definitions of my_function(), which PHP will not stand for.

Make sure that you are not using include to pull in the same file of function definitions more than once. Use include_once or require_once to avoid

4)Wrong parameter count
***********************

Explain Parse Errors ? what are the most common causes of parse errors ?
The most common category of error arises from mistyped
or syntactically incorrect PHP code, which confuses the PHP parsing engine.
1)The missing semicolon
***********************
If each PHP instruction is not duly finished off with a semicolon,
a parse error will result. In this sample fragment, the first line lacks a semicolon and, therefore, the variable assignment is never completed.
What we have here is
$Problem = “a silly misunderstanding”
echo $Problem;
?>

2)No dollar signs
*******************
Another very common problem is that a dollar sign prepending
a variable name is missing.If the dollar sign is missing during
the initial variable assignment, like so:

What we have here is
Problem = “a big ball of earwax”;
echo $Problem;
?>.
A parse error message will result. However, if instead the
dollar sign is missing from a later
output of the variable, like this:
What we have here is
$Problem = “a big ball of earwax”;
print(“Problem”);
?>

3)Mode issues
**************
A parse error will result if you fail to close off a PHP block properly, as in:
What we have here is
$Problem = “an awful kerfuffle”;
echo $Problem;

4)Unescaped quotes
********************

5)Unterminated strings
**********************
What Are PHP Arrays?
PHP arrays are associative arrays with a little extra machinery thrown in.
The associative part means that arrays store element
values in association with key values rather than in a
strict linear index order. (If you have seen arrays in other programming languages, they are likely to have been vector arrays rather
than associative arrays.) If you store an element in an array,
in association with a key,all you need to retrieve it later from
that array is the key value. For example, storage is as
simple as this:
$state_location[‘San Mateo’] = ‘California’;

which stores the element ‘California’ in the array variable $state_location,
in association with the lookup key ‘San Mateo’. After this has been stored,
you can look up the stored value by using the key, like so:

$state = $state_location[‘San Mateo’]; // equals ‘California’

If all you want arrays for is to store key/value pairs, the preceding
information is all you need to know. Similarly,
if you want to associate a numerical ordering with a bunch of values,
all you have to do is use integers as your key values, as in:

$my_array[1] = “The first thing”;
$my_array[2] = “The second thing”;

Are php strings immutable ?
PHP strings can be changed, but the most common practice seems to be to treat strings as immutable. Strings can be changed by treating them as character
arrays and assigning directly into them, like this:
$my_string = “abcdefg”;
$my_string[5] = “X”;
print($my_string . “
”);
which will give the browser output:
abcdeXg
?>

what is Memcache?

Memcache is a technology which caches objects in memory where your web application can get to them really fast. It is used by sites such as Digg.com, Facebook.com and NowPublic.com and is widely recognized as an essential ingredient in scaling any LAMP application to handle enormous traffic.

How do I prevent Web browsers caching a page in php?
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Pragma: no-cache');
?>

what is the php solution to dynamic caching ?
PHP offers an extremely simple solution
to dynamic caching in the form of
output buffering.

what are the most common caching policy approaches ?
1)Time triggered caching (expiry timestamp).

2)Content change triggered caching (sensitive content has changed, so cache must be updated).

3)Manually triggered caching (manually inform the application that information is outdated, and force a new cache creation).

How to capture content from the output buffer ? or Give me an example for
Output caching in php?
ob_start(); // start an output buffer

echo ‘This text is from the w3answers buffer*******
’; // output that will be stored in the buffer

$w3buffer = ob_get_contents(); // store buffer content in $w3buffer variable
ob_end_clean(); // stop and clean the output buffer
echo ‘This is not from the w3answers buffer!!!!!!!!
’;
echo $w3buffer;
?>
O/p
*****

This is not from the w3answers buffer!!!!!!!!
This text is from the w3answers buffer*******

What is the difference between $message and $$message?
$message is a simple variable whereas $$message is a variable's variable,which means
value of the variable. Example:
$user = 'bob'
is equivalent to

$message = 'user';
$$message = 'bob';

why should we use Object oriented concepts in php ?
1. Object oriented PHP code is much more reusable because by its' very nature, it is modular.

2. Object oriented PHP is easier to update. Again, because PHP code is organised into objects.

3. Object oriented PHP makes team programming much easier to manage.

4. Object oriented PHP makes larger projects much easier to manage.

5. Object oriented PHP makes creating code libraries much easier.

6. Knowing Object oriented PHP will make working with many opensource PHP libraries much easier. For example: projects like PEAR and the Zend Framework are built using Object oriented PHP.

7. Object oriented PHP programmers typically make more money and will be able to work on more projects.

8. Since object oriented concepts are the same in all Object oriented languages, once you learn Object oriented programing in PHP, you will also have a good understanding of several other languages including:

a. Ruby
b. Java
c. C#
d. Actionscript
…among several other languages.

which is faster mysql_unbuffered_query or mysql_query ?

when we do the select queries that retrieve large data sets from MySQL, mysql_unbuffered_query in PHP is likely to give better performance than mysql_query.

PHP manual says,

it “sends a SQL query query to MySQL, without fetching and buffering the result rows automatically”.

How can we extract string "w3answers.com" from a string
mailto:info@w3answers.com using regular expression of PHP ?
$w3 = "mailto:info@w3answers.com";
preg_match('|.*@([^?]*)|', $w3, $w3output);
echo $w3output[1];
?>

Which function in PHP gives us absolute path of a file on the server?
getcwd()

$p = getcwd();
echo $p;
?>


here I have stored my files under httdocs (using php5,i haven't checked under php4) so I get the output as C:\apache2triad\htdocs
you may get your path information while runnings the above code. :)

what is the output here ?
session_start();
$_SESSION["var"] = NULL;
echo $var = "www.w3answers.com";
?>

The output :
www.w3answers.com and warning as below

Warning: Unknown: Your script possibly relies on a session side-effect which existed until PHP 4.2.3. Please be advised that the session extension does not consider global variables as a source of data, unless register_globals is enabled. You can disable this functionality and this warning by setting session.bug_compat_42 or session.bug_compat_warn to off, respectively. in Unknown on line 0

what is the output ?
echo "www.w3answers.com";
if ((string)'-1') { print 'ouch'; } else { print 'echo'; }
?>

a. ouch
b. echo
c. none
d. Parse error

ANS: a

what output do you get here?
$here = "/home/httpd/html/test ";
list ($j1,$j2,$j3,$j4) = split('/',$here);
print "$j3";
?>

a. home
b. Array
c. test
d. httpd
ANS: httpd

Which of the following functions is most efficient for substituting fixed
patterns in strings?
A. preg_replace()
B. str_replace()
C. str_ireplace()
D. substr_replace()

Answer B is correct.

The PHP efficiency mantra is “do no more work than necessary.”
Both str_ireplace() and preg_replace() have more expensive (and flexible)
matching logic, so you should only use them when your problem requires it.
substr_replace() requires you to know the offsets and lengths of the substrings
you want to replace, and is not sufficient to handle the task at hand.

Which of the following represents the proper way to set a session variable?
A. $_SESSION[‘foo’] = ‘bar’;
B. session_start();
C. session_set_save_handler (‘myopen’, ‘myclose’, ‘myread’,
‘mywrite’, ‘mydelete’, ‘mygarbage’);
D. $foo = $_SESSION[‘foo’];

Answer A is correct.

Answer B is incorrect because session_start() only activates
PHP sessions for the current script. Answer C is incorrect because
session_set_save_handler() allows you to override PHP’s default session
mechanism with your own custom functions. Answer D is incorrect; session data is
being used as the value of a regular variable and is not being manipulated in any
way.

How we can pass data from PHP to ASP,ASP.net?
PHP to ASP

Let's first look at how you can pass data from PHP to ASP using WDDX.

You create a WDDX packet by first serializing data into a WDDX packet and then presenting it.
WDDX can convert most variable types that applications use, such as strings, integers, and arrays. After a variable has been converted to a WDDX variable type, it is ready for another application to pick up.

PHP has WDDX support built in, so you don't need to modify your PHP.ini file to start using WDDX.
A PHP Script to Serialize WDDX

//define PHP data to send
$ValueToSend = "Andrew";

//convert PHP data to WDDX data
$wddxvar = wddx_serialize_value("$ValueToSend");

//output WDDX data
print("$wddxvar");

?>
You first set the data you want to serialize into a WDDX packet:

$ValueToSend = "Andrew";
You then serialize that data:

$wddxvar = wddx_serialize_value("$ValueToSend");

Finally, you present that data as

print("$wddxvar");

********************************
O/P=Andrew
********************************
Internet Explorer just shows the data within the WDDX packet. It doesn't show the surrounding XML structures. However, if you choose the view source option, you can see the WDDX packet's XML structures
#################################-END-
**************************************************
ASP Script to Deserialize WDDX Data
**************************************************
To receive the WDDX packet from the PHP script, you must load the packet into a variable within the receiving ASP script. None of the WDDX implementations (the WDDX COM component or PHP's WDDX functions) provides native ways of doing this. You must add this functionality using separate code. After you receive the WDDX packet, you can convert it into a data type native to the receiving application. This is called deserializing.

Using ASP, you can use a third-party COM component. A free COM component that allows such functionality is ASP Tear from http://www.alphasier-rapapa.com/IisDev/Components/ (also included with the WDDX SDK). However, you can use any COM component that has similar functionality.

<%

set aspget = Server.CreateObject("SOFTWING.AspTear")
set wddxob = Server.CreateObject("WDDX.Deserializer.1")

'get WDDX data
wddxdata = aspget.Retrieve("http://localhost/phpbook/Chapter5_Sessions/WDDX/PHP/
two_wddxserver.php", Request_POST, "", "", "")

'convert WDDX data to ASP data
wddxvar = wddxob.deserialize(wddxdata)

'output ASP data
response.write "Hello " & wddxvar

set wddxob = nothing
set aspget = nothing

%>

First, you must load the WDDX and ASP Tear COM objects into memory for use by ASP. Don't worry too much if you are not familiar with using COM objects


set aspget = Server.CreateObject("SOFTWING.AspTear")
set wddxob = Server.CreateObject("WDDX.Deserializer.1")
Next you use ASP Tear to obtain the WDDX packet produced by the PHP server and load it into a variable:

'get WDDX data
wddxdata = aspget.Retrieve("http://localhost/phpbook/Chapter5_Sessions/WDDX/PHP/
two_wddxserver.php", Request_POST, "", "", "")
You deserialize the WDDX packet into a native data type for ASP:

'convert WDDX data to ASP data
wddxvar = wddxob.deserialize(wddxdata)
You then output the value:

'output ASP data
response.write "Hello " & wddxvar
Finally, you unload the COM objects from memory:

set wddxob = nothing
set aspget = nothing
ASP to PHP
PHP can also receive WDDX packets. Here you will see a PHP script obtaining a WDDX packet from an ASP script.

*************************************************
An ASP Script to Serialize WDDX
*************************************************
<%
'define ASP data to send
ValueToSend = "Andrew"

set wddxob = Server.CreateObject("WDDX.Serializer.1")

'convert ASP data to WDDX data
wddxvar = wddxob.serialize(ValueToSend)

'output WDDX data
response.write wddxvar

set wddxob = nothing

%>
This is very much the same as the serializing PHP script. First, you define the value you want to serialize in WDDX:

'define ASP data to send
ValueToSend = "Andrew"
You then load the WDDX COM object into memory, ready for use by ASP:

set wddxob = Server.CreateObject("WDDX.Serializer.1")
You then serialize the value into a WDDX packet:

'convert ASP data to WDDX data
wddxvar = wddxob.serialize(ValueToSend)
You then display the WDDX packet:

'output WDDX data
response.write wddxvar
Finally, you unload the WDDX COM object from memory:

set wddxob = nothing

*******************************************************
A PHP Script to Deserialize WDDX Data
********************************************************

The deserialize PHP script needs to do the same as the deserialize ASP script: It must convert the WDDX packet back into a native variable type for our script (in this case, a native variable type for PHP):


//get WDDX data
$wddxdata = join ('', file
('http://localhost/phpbook/Chapter5_Sessions/WDDX/ASP/one_wddxserver.asp'));

//convert WDDX data to PHP data
$wddxvar = wddx_deserialize("$wddxdata");
//output PHP data
print("Hello " . $wddxvar);

?>
You can obtain the WDDX packet from the ASP script using the PHP join function. To use the function in this manner, you must make sure that HTTP transparency is enabled in the PHP.ini settings file (the allow_url_fopen setting is enabled). (Note that HTTP transparency is enabled by default.)

$wddxdata = join ('', file
('http://localhost/phpbook/Chapter5_Sessions/WDDX/ASP/one_wddxserver.asp'));
As before, you deserialize the WDDX packet into a native variable type:

$wddxvar = wddx_deserialize("$wddxdata");
You then display the WDDX packet:

print("Hello " . $wddxvar);

How can you block certain IP Addresses from accessing your site?
$banned = array("24.91.102.173", "64.21.162.113");
if (in_array($_SERVER['REMOTE_ADDR'], $banned)) {
echo "You have been banned.";
exit;
}
?>
What Storage Engines do you use in MySQL?
MySQL Engines
*****************************************

MyISAM
HEAP
MEMORY
MERGE
MRG_MYISAM
ISAM
MRG_ISAM
InnoDB
INNOBASE
BDB
BERKELEYDB
NDBCLUSTER
NDB
EXAMPLE
ARCHIVE
CSV

What is Apache?
The most widely available HTTP server on the Internet. It supports the PERL and PHP languages.

The Apache HTTP Server Project is a collaborative software development effort aimed at creating a robust, commercial-grade, featureful, and freely-available source code implementation of an HTTP (Web) server. The project is jointly managed by a group of volunteers located around the world, using the Internet and the Web to communicate, plan, and develop the server and its related documentation. This project is part of the Apache Software Foundation. In addition, hundreds of users have contributed ideas, code, and documentation to the project. This file is intended to briefly describe the history of the Apache HTTP Server and recognize the many contributors.

Installing PHP on your Computer?
You can download apache2triad from
http://sourceforge.net/projects/apache2triad/

Its a single setup file for
---------------------------
Apache2 , MySQL , PostgreSQL , OpenSSL , Xmail , SlimFTPd Software developing triad of : PHP , Perl and Python + Apache2TriadCP , PHPmyadmin , PHPPgAdmin , AWStats , UebiMiau , PHPXMail , PHPSFTPd. All latest stables , all manuals

Use this for your php installation in your pc!!!

What can PHP do?
Anything. PHP is mainly focused on server-side scripting, so you can do anything any other CGI program can do, such as collect form data, generate dynamic page content, or send and receive cookies. But PHP can do much more.

There are three main areas where PHP scripts are used.

Server-side scripting. This is the most traditional and main target field for PHP. You need three things to make this work. The PHP parser (CGI or server module), a webserver and a web browser. You need to run the webserver, with a connected PHP installation. You can access the PHP program output with a web browser, viewing the PHP page through the server. All these can run on your home machine if you are just experimenting with PHP programming.

Command line scripting. You can make a PHP script to run it without any server or browser. You only need the PHP parser to use it this way. This type of usage is ideal for scripts regularly executed using cron (on *nix or Linux) or Task Scheduler (on Windows). These scripts can also be used for simple text processing tasks.

Writing desktop applications. PHP is probably not the very best language to create a desktop application with a graphical user interface, but if you know PHP very well, and would like to use some advanced PHP features in your client-side applications you can also use PHP-GTK to write such programs. You also have the ability to write cross-platform applications this way. PHP-GTK is an extension to PHP, not available in the main distribution.

PHP can be used on all major operating systems, including Linux, many Unix variants (including HP-UX, Solaris and OpenBSD), Microsoft Windows, Mac OS X, RISC OS, and probably others. PHP has also support for most of the web servers today. This includes Apache, Microsoft Internet Information Server, Personal Web Server, Netscape and iPlanet servers, Oreilly Website Pro server, Caudium, Xitami, OmniHTTPd, and many others. For the majority of the servers PHP has a module, for the others supporting the CGI standard, PHP can work as a CGI processor.

So with PHP, you have the freedom of choosing an operating system and a web server. Furthermore, you also have the choice of using procedural programming or object oriented programming, or a mixture of them. Although not every standard OOP feature is implemented in PHP 4, many code libraries and large applications (including the PEAR library) are written only using OOP code. PHP 5 fixes the OOP related weaknesses of PHP 4, and introduces a complete object model.

With PHP you are not limited to output HTML. PHP's abilities includes outputting images, PDF files and even Flash movies (using libswf and Ming) generated on the fly. You can also output easily any text, such as XHTML and any other XML file. PHP can autogenerate these files, and save them in the file system, instead of printing it out, forming a server-side cache for your dynamic content.

One of the strongest and most significant features in PHP is its support for a wide range of databases. Writing a database-enabled web page is incredibly simple. The following databases are currently supported:

Adabas D InterBase PostgreSQL
dBase FrontBase SQLite
Empress mSQL Solid
FilePro (read-only) Direct MS-SQL Sybase
Hyperwave MySQL Velocis
IBM DB2 ODBC Unix dbm
Informix Oracle (OCI7 and OCI8)
Ingres Ovrimos

We also have a database abstraction extension (named PDO) allowing you to transparently use any database supported by that extension. Additionally PHP supports ODBC, the Open Database Connection standard, so you can connect to any other database supporting this world standard.

PHP also has support for talking to other services using protocols such as LDAP, IMAP, SNMP, NNTP, POP3, HTTP, COM (on Windows) and countless others. You can also open raw network sockets and interact using any other protocol. PHP has support for the WDDX complex data exchange between virtually all Web programming languages. Talking about interconnection, PHP has support for instantiation of Java objects and using them transparently as PHP objects. You can also use our CORBA extension to access remote objects.

PHP has extremely useful text processing features, from the POSIX Extended or Perl regular expressions to parsing XML documents. For parsing and accessing XML documents, PHP 4 supports the SAX and DOM standards, and you can also use the XSLT extension to transform XML documents. PHP 5 standardizes all the XML extensions on the solid base of libxml2 and extends the feature set adding SimpleXML and XMLReader support.

At last but not least, we have many other interesting extensions, the mnoGoSearch search engine functions, the IRC Gateway functions, many compression utilities (gzip, bz2, zip), calendar conversion, translation...


What is PHP?

PHP: Hypertext Preprocessor, an open source, server-side, HTML embedded scripting language used to create dynamic Web pages.

In an HTML document, PHP script (similar syntax to that of Perl or C ) is enclosed within special PHP tags. Because PHP is embedded within tags, the author can jump between HTML and PHP (similar to ASP and Cold Fusion) instead of having to rely on heavy amounts of code to output HTML. And, because PHP is executed on the server, the client cannot view the PHP code.

PHP can perform any task that any CGI program can do, but its strength lies in its compatibility with many types of databases. Also, PHP can talk across networks using IMAP, SNMP, NNTP, POP3, or HTTP.

PHP was created sometime in 1994 by Rasmus Lerdorf. During mid 1997, PHP development entered the hands of other contributors. Two of them, Zeev Suraski and Andi Gutmans, rewrote the parser from scratch to create PHP version 3 (PHP3).








PHP OOPS Interview Questions

what is Magic methods in php?
There are seven special methods, and they are as follows:

__construct( )
Called when instantiating an object

__destruct( )
Called when deleting an object

__get( )
Called when reading from a nonexistent property

__set( )
Called when writing to a nonexistent property

__call( )
Called when invoking a nonexistent method

__toString( )
Called when printing an object (for eg: converting an object to strings)

__clone( )
Called when cloning an object (copying object)

Explain Constructors and Destructors in php?
__construct( )
Called when instantiating an object

__destruct( )
Called when deleting an object

Constructors and destructors are functions that are called when a new instance of an object is created (constructors) and/or destroyed (destructors). Their primary purpose is to allow for a means to initialize and clean up after an object during its use.
Constructors can accept parameters, which are assigned to specific object fields at
creation time.

Constructors can call class methods or other functions.
constructors are intuitively useful for initializing class properties,

Class constructors can call on other constructors, including those from the class parent.

One classic example is a class to access a database back end, where a constructor could make the connection to the database while the destructor closes it.

PHP 4 Constructors
In PHP 4, only constructors were available and were created by defining a function whose name was the same as the class itself:
class w3Class {
function w3Class($param) {
echo "Created a new instance of w3Class!";
}
}
$w3instance = new w3Class;
?>

In PHP 5, this concept has been changed PHP 5 or (5>=) now uses a unified constructor function named __construct(). PHP 5 or (5>=) also uses a unified __destruct() method for its destructors.

PHP 5 Constructors and Destructors

class w3Class {
function __construct($p) {
echo "Created a new instance of w3Class!";
}
function __destruct() {
echo "Destroyed this instance of w3Class";
}
}
$w3instance = new w3Class("value");

?>

Define class in php?
A class is a blueprint of an object ,variables and functions (called methods),

PHP 4 Class Style:

Create first file as ‘PHP4Class.php’
class w3answersPHP4Class {
var $my_class;
function my_W3method($param) {
echo "hey, you are in my_W3method ($param)!!\n";
echo "The value of my w3class is: ";
echo "{$this->my_class }\n";
}
}
?>

“$this is a special variable within a class that represents the instance of the object itself. It is used to access both methods and properties internally within the object”.
To create an instance of the w3answersPHP4Class, the new statement is used:

Create Second file as ‘instance.php’
require_once ("PHP4Class.php ");
$w3instance = new w3answersPHP4Class();
$w3anotherinstance = new w3answersPHP4Class();
$w3instance->my_class = 100;
$w3anotherinstance->my_class = 200;
?>

When executed, the $my_class property of the $w3instance object will be set to 100, and the $w3anotherinstance’s $my_class property will be set to 200.

The output will be

Hey, you are in my_W3method(MyParam)!!
The value of my w3class is 100

PHP 5 Class style:
Create first file as ‘PHP5Class.php’
class w3answersPHP5Class {
public $my_class;
/*we can also make private $my_class; but it will lead you to error when you tryimg to acess the varaiable
like Fatal Error: Cannot access private property w3answersPHP5Class::my_class in .... */

public function my_W3method($param) {
echo "hey, you are in my_W3method ($param)!!\n";
echo "The value of my w3class is: ";
echo "{$this->my_class }\n";
}
}
?>

Create Second file as ‘instance.php’
include_once ("PHP5Class.php ");
$w3instance = new w3answersPHP5Class();
$w3anotherinstance = new w3answersPHP5Class();
$w3instance->my_class = 100;
$w3anotherinstance->my_class = 200;

?>

How php Implements Polymorphism ?
PHP supports polymorphism in the sense of allowing instance of subclasses to be used in place of parent instances.

How PHP Supports Encapsulation?
Encapsulation is the mechanism that binds together code and data it manipulates and keeps both safe from out side interference and miss use .To implement this concept , PHP 5 supports public, private, and protected variables and member functions .




PHP XML Questions

What are the Technology to Use for Parsing the XML?
There are two types of XML parsers the we can use.
1. DOM (Document Object Module).
2. SAX (Simple API for XML).
DOM
The DOM (Document Object Model) extension allows to operate on XML documents through the DOM API with PHP 5. DOM is a standard defined by the W3C for accessing XML documents.
In PHP 4, DOM xml extension is not following the standard method names.
As per the new W3C compatibility, the old domxml-based scripts won't work anymore. The API is quite different in PHP 5. But if we used the "almost W3C compatible" method names available in PHP 4.3, We only need to change the loading and saving methods, and remove the underscore in the method names. Other adjustments here and there may be necessary, but the main logic can stay the same. Though we have not used earlier so these will not be a problem for us.
The easiest way to read a well-formed XML file is to use the DOM library . The DOM library reads the entire XML document into an object and represents it as a tree of nodes,

SAX
SAX stands for Simple API for XML. It's a callback-based interface for parsing XML documents. SAX support has been available since PHP 3 and hasn't changed a lot since then. For PHP 5 the API is unchanged, The only difference is that it's not based on the expat library anymore, but on the libxml2 library.
Rather than treating an XML document as a tree-like structure, SAX treats it as a series of events such as startDocument or endElement. To accomplish this, a SAX appllication consists of a parser that sends these events to "handlers," methods or functions designated to handle them.

What is XML?
XML (eXtensible Markup Language) is a data format for structured document interchange on the Web. It is a standard defined by The World Wide Web consortium (W3C).
XML doesn't define what data is being stored or the structure of that data.
XML simply defines tags and attributes for those tags. A properly formed XML tag looks like this:
php xml

An XML book list example



Rasmus
PHP 5
zend


w3answers
Project Management
w3labs


XML (eXtensible Markup Language) is a data format for structured document interchange on the Web. It is a standard defined by The World Wide Web consortium (W3C).
XML doesn't define what data is being stored or the structure of that data.
XML simply defines tags and attributes for those tags. A properly formed XML tag looks like this:
php xml

An XML book list example



Rasmus
PHP 5
zend


w3answers
Project Management
w3labs


Ajax Frameworks-php libraries
Sajax
‘Sajax is a tool to make programming websites using the Ajax framework — also known as XMLHTTPRequest or remote scripting — as easy as possible. Sajax makes it easy to call ASP, Cold Fusion, Io, Lua, Perl, PHP, Python or Ruby functions from your webpages via JavaScript without performing a browser refresh. The toolkit does 99% of the work for you so you have no excuse to not use it.’

PHP Class Library - Xajax
‘xajax is an open source PHP class library that allows you to easily create powerful, web-based, Ajax applications using HTML, CSS, JavaScript, and PHP. Applications developed with xajax can asynchronously call server-side PHP functions and update content without reloading the page.’

CPAINT - Ajax Toolkit - what is CPAINT?
‘CPAINT (Cross-Platform Asynchronous INterface Toolkit) is a multi-language toolkit that helps web developers design and implement AJAX web applications with ease and flexibility. It was originally born out of the author’s frustration and disappointment with other open-source AJAX toolkits. It is built on the same principles of AJAX, utilizing JavaScript and the XMLHTTP object on the client-side and the appropriate scripting language on the server-side to complete the full circle of data passing from client to server and back.’

Ajax HTML using PEAR - libraries
This is a PHP and JavaScript package available through the official PEAR website.


Should I use an HTTP GET or POST for my AJAX calls?
AJAX requests should use an HTTP GET request when retrieving data where the data will not change for a given request URL. An HTTP POST should be used when state is updated on the server. This is in line with HTTP idem potency recommendations and is highly recommended for a consistent web application architecture.
What API function provides the connection between the client and server?
XMLHttpRequest

what is ajax? when ajax was born?
"AJAX is an acronym for Asynchronous JavaScript and XML. If you think it doesn't say much, we agree. Simply put, AJAX can be read "empowered JavaScript", because it essentially offers a technique for client-side JavaScript to make background server calls(such as from PHP,ASP.NET,JSP,RUby etc) and retrieve additional data as needed, updating certain portions of the page without causing full page reloads".

The XMLHttpRequest object enables JavaScript to access the server asynchronously, so that the user can continue working, while functionality is performed in the background.


The name AJAX was born in 2005, in Jesse James Garret's article at http://www.adaptivepath.com/publications/essays/archives/ 000385.php,
and gained much popularity when used by Google in many of its applications.



PHP Fresher Job Questions
How can we get second of the current time using date function?
echo $second = date("s");
?>
How can we know the number of elements in an array using php?
Ans:
There are two ways:
1) sizeof($myarray) - This function is an alias of count()
2) count($array) - This function returns the number of elements in an array.
Note
if you just pass a simple variable instead of an array, count() will return 1.
What are the different functions in sorting an array?
Ans:
asort()
arsort()
ksort()
krsort()
uksort()
sort()
natsort()
rsort()

What would the following code print to the browser? Why?

$num = 10;
function multiply(){
$num = $num * 10;
}
multiply();
echo $num;

?>

Ans: 10 because,its a call by value.$num is static here.

change the above code as




$num = 10;
function multiply(){
global $num ;
$num = $num * 10;
}
multiply();
echo $num;

?>


ANS: 100

How can you get round the stateless nature of HTTP using PHP?
ANS: using Sessions in PHP
What function can you use to open a file for reading and writing?
1. fget();
2. file_open();
3. fopen();
4. open_file();

ANS:fopen();

What function would you use to redirect the browser to a new page?
1. redir()
2. header()
3. location()
4. redirect()

ANS:header()

MySQL Interview Questions