Tizag.com Webmaster Tutorials - A collection of webmaster tutorials from HTML to PHP.

Monday, December 1, 2008

Morfeus Fucking Scanner

in .httaccess file add the following line

RewriteEngine On
RewriteCond %{HTTP_USER_AGENT} ^Morfeus
RewriteRule ^.*$ - [F]

Saturday, November 29, 2008

Php codes in HTML [configure Apache]

For running a PHP script through HTML file we need to configure httpd.conf

1. Open the file in edit mode
2. Search for Adddandler
3. paste the following line. AddHandler application/x-httpd-php .php .htm .html
4. Restart Apache

Sunday, October 26, 2008

Setting Cron Job

Open putty and log in to the server using user name and password

type crontab -l to see the list of cron jobs.

type which php to see the location of the installation of php location

type crontab -e to edit the cron job.
minute hour day month day-of-week command-line-to-execute

The acceptable values for each of the 6 fields are:

FieldRange of values
minute0-59
hour0-23
day1-31
month1-12
day-of-week0-7 (where both 0 and 7 mean Sun, 1 = Mon, 2 = Tue, etc)
command-line-to-executethe command to run along with the parameters to that command if any

So if I want my cron job to run every at 9:30 pm
we Write

39 21 * * 6 /usr/bin/php /home/www/htdocs/biraj/testbiraj.php

and press ESC :wq

/usr/bin/php /=="PHP LOCATION"

home/www/htdocs/biraj/testbiraj.php == "LOCATION OF THE EXECUTABLE FILE"

for more details refer http://www.thesitewizard.com/general/set-cron-job.shtml

Monday, October 6, 2008

Upload and Read file line by line in PHP

<?php
include_once("includes/connect.php");

?>
<script language="JavaScript">
<!--
function refreshParent() {
window.opener.location.href = window.opener.location.href;

if (window.opener.progressWindow)

{
window.opener.progressWindow.close()
}
window.close();
}
//-->
</script>
<?php

if($_POST){

/*------------------| Upload the file in Server |------------------*/
//print_r($_FILES);
$max_photo_size=50000;
$upload_required=true;
$upload_dir='mails/';
$err_msg=false;
do{
if(!isset($_FILES['book_image'])){
$err_msg="The form was not sent in completely.";
break;
}else{
$book_image=$_FILES['book_image'];
}
switch ($book_image['error']){
case UPLOAD_ERR_INI_SIZE:
$err_msg = 'The size of the image is too large.';
break 2;

case UPLOAD_ERR_PARTIAL:
$err_msg = 'An error occured while uploading the files.';
break 2;

case UPLOAD_ERR_NO_FILE:
$err_msg = 'You did not select a file to upload.';
break 2;

case UPLOAD_ERR_OK:
if($book_image['size'] > $max_photo_size){
$err_msg = 'The size of the file is too large.';
}
break 2;

default:
$err_msg = 'An unknown error occured.';
break 2;
}
if(!in_array($book_image['type'], array('text/plain'))){
$err_msg = 'You need to upload a text file';
break;
}
}while (0);
if(!$err_msg){
if(!move_uploaded_file($book_image['tmp_name'], $upload_dir. $book_image['name'])){
$err_msg='Error moving file in destination';
}
}
/*---------------| Uploading file is over |---------------------*/

/*---------------| Reading file data |----------------------*/
$myFile = $upload_dir.$book_image['name'];
//$myFile = 'mails/example.txt';
//echo $myFile;
$fh = fopen($myFile, 'r');
$theData = fread($fh, filesize($myFile));
echo $theData;
echo "<hr/>";
fclose($fh);

/*---------------| Counting the number of results |----------------*/
$countSpace = substr_count($theData, "\n");
echo $countSpace;

$emailArray=explode("\n", $theData);
$rid = mysql_real_escape_string($_REQUEST['txt_rid']);
$wb='Y';

/*----------------| Inserting the records in the db |---------------*/
for($i=0; $i<=$countSpace; $i++){

$email = mysql_real_escape_string($emailArray[$i]);

/*-------| Save value in primary table |--------------------*/
$query0="SELECT id FROM mailaddr WHERE email like '%".$email."%'";
$query0_execute=mysql_query($query0) or die(mysql_error());
$query0_rows=mysql_num_rows($query0_execute);
if($query0_rows>=1){
$query0_result=mysql_fetch_assoc($query0_execute);
$id=$query0_result[id];
//echo $id;
}else{
$query1="INSERT INTO mailaddr (priority, email) VALUES('7','".$email."')";
echo $query1;
mysql_query($query1) or die('Insert Error 1');
}

/*-------| Get last record from primary table |------------*/
$query2="SELECT max(id) FROM mailaddr";
$query2_execute=mysql_query($query2) or die('error');
$query2_show=mysql_fetch_row($query2_execute);


/*-------| Blacklist/Whitelist Values |--------------------*/
if($query0_rows>=1){
$query3="INSERT INTO wblist (rid, sid, wb) VALUES('".$rid."', '".$id."','".$wb."')";
}else{
$query3="INSERT INTO wblist (rid, sid, wb) VALUES('".$rid."', '".$query2_show[0]."','".$wb."')";
}
mysql_query($query3) or die("Email already blacklisted or whitelisted.<br/><input type=\"button\" value=\"Close\" onclick=\"window.close();\">");

$query_insert="Data Successfully inserted";





}

unlink($myFile);
echo "<script>refreshParent();</script>";

}

?>
<body bgcolor="#B7C9E1">
<br/>
<?php
if($err_msg){
echo $err_msg;
}
?>
<form id="frmAddNewUser" enctype="multipart/form-data" method="post" action="import_whitelist.php">

<table border="0" cellspacing="0" cellpadding="0" width="300">
<tr>
<td width="33%" class="policyContent">File :</td>
<td width="67%" class="policyInput">
<input type="hidden" name="MAX_FILE_SIZE" value="16000"/>
<input type="file" name="book_image" style="border: #2D3191 2px solid;">
</td>
</tr>
<tr>
<td> ;</td>
<td> ;</td>
</tr>
<tr>
<td> ;</td>
<td class="policyContent" align="center">
<input type="hidden" name="txt_hidval" id="txt_hidval" value="0"><input type="hidden" name="txt_rid" id="txt_rid" value="<?php echo $_REQUEST['rid'];?>"><input type="Submit" value="Save" class="button"></td>
</tr>
</table>

</form>
</body>

Saturday, October 4, 2008

Display Page after Interval

<label id=d2> </label>
<script>




var milisec=0
var seconds=5
//document.frm2.d2.value='10'
document.getElementById("d2").innerHTML='5';

function display(){
if (milisec<=0){
milisec=9
seconds-=1
}
if (seconds<=-1){
milisec=0
seconds+=1
}
else
milisec-=1
//document.frm2.d2.value=seconds+"."+milisec
document.getElementById("d2").innerHTML=seconds+"."+milisec
setTimeout("display()",100)
}
display()

function delayer(){
if(document.getElementById("hidval").value==1){
//window.location = "http://www.apps4rent.com/payment-cpanel.html";
window.location = "validcc.html";
}else{
//window.location = "index.php";
window.location = "invalidcc.html";
}
}
setTimeout('delayer()', 5000)
</script>

Friday, September 26, 2008

JavaScript Floating Layer

<!-- THREE STEPS TO INSTALL Persistent LAYER:

1. Copy the coding into the HEAD of your HTML document
2. Add the onLoad event handler into the BODY tag
3. Put the last coding into the BODY of your HTML document -->

<!-- STEP ONE: Paste this code into the HEAD of your HTML document -->

<HEAD>

<SCRIPT LANGUAGE="JavaScript">


<!-- Begin
window.onerror = null;
var topMargin = 100;
var slideTime = 1200;
var ns6 = (!document.all && document.getElementById);
var ie4 = (document.all);
var ns4 = (document.layers);
function layerObject(id,left) {
if (ns6) {
this.obj = document.getElementById(id).style;
this.obj.left = left;
return this.obj;
}
else if(ie4) {
this.obj = document.all[id].style;
this.obj.left = left;
return this.obj;
}
else if(ns4) {
this.obj = document.layers[id];
this.obj.left = left;
return this.obj;
}
}
function layerSetup() {
floatLyr = new layerObject('floatLayer', pageWidth * .5);
window.setInterval("main()", 10)
}
function floatObject() {
if (ns4 || ns6) {
findHt = window.innerHeight;
} else if(ie4) {
findHt = document.body.clientHeight;
}
}
function main() {
if (ns4) {
this.currentY = document.layers["floatLayer"].top;
this.scrollTop = window.pageYOffset;
mainTrigger();
}
else if(ns6) {
this.currentY = parseInt(document.getElementById('floatLayer').style.top);
this.scrollTop = scrollY;
mainTrigger();
} else if(ie4) {
this.currentY = floatLayer.style.pixelTop;
this.scrollTop = document.body.scrollTop;
mainTrigger();
}
}
function mainTrigger() {
var newTargetY = this.scrollTop + this.topMargin;
if ( this.currentY != newTargetY ) {
if ( newTargetY != this.targetY ) {
this.targetY = newTargetY;
floatStart();
}
animator();
}
}
function floatStart() {
var now = new Date();
this.A = this.targetY - this.currentY;
this.B = Math.PI / ( 2 * this.slideTime );
this.C = now.getTime();
if (Math.abs(this.A) > this.findHt) {
this.D = this.A > 0 ? this.targetY - this.findHt : this.targetY + this.findHt;
this.A = this.A > 0 ? this.findHt : -this.findHt;
}
else {
this.D = this.currentY;
}
}
function animator() {
var now = new Date();
var newY = this.A * Math.sin( this.B * ( now.getTime() - this.C ) ) + this.D;
newY = Math.round(newY);
if (( this.A > 0 && newY > this.currentY ) || ( this.A < 0 && newY < this.currentY )) {
if ( ie4 )document.all.floatLayer.style.pixelTop = newY;
if ( ns4 )document.layers["floatLayer"].top = newY;
if ( ns6 )document.getElementById('floatLayer').style.top = newY + "px";
}
}
function start() {
if(ns6||ns4) {
pageWidth = innerWidth;
pageHeight = innerHeight;
layerSetup();
floatObject();
}
else if(ie4) {
pageWidth = document.body.clientWidth;
pageHeight = document.body.clientHeight;
layerSetup();
floatObject();
}
}
// End -->
</script>

</HEAD>

<!-- STEP TWO: Insert the onLoad event handler into your BODY tag -->

<BODY onLoad="start()">

<!-- STEP THREE: Copy this code into the BODY of your HTML document -->

<DIV id="floatLayer" style="position: absolute; height:200px; width:200px; left:30px; top:1px;z-index: 100">This is a Floating Layer. Replace this content with your own.</DIV>

<p><center>
<font face="arial, helvetica" size"-2">Free JavaScripts provided<br>
by <a href="http://javascriptsource.com">The JavaScript Source</a></font>
</center><p>

<!-- Script Size: 3.52 KB -->

Monday, September 15, 2008

JavaScript DateValidation

function isValidDate(ctrl)
}
var dateStr = ctrl.value;
var datePat = /^(\d}1,2})(\/|-)(\d}1,2})\2(\d}2}|\d}4})$/;
var matchArray = dateStr.match(datePat); // is the format ok?
if (matchArray == null)
}
alert("Invalid date format. Please enter the date in the MM/DD/YY format (example: 1/15/08) or select a date by clicking the calendar icon.")
ctrl.focus();
return false;
}
month = matchArray[1]; // parse date into variables
day = matchArray[3];
year = matchArray[4];
if (month <> 12)
}
// check month range
alert("Month must be between 1 and 12.");
return false;
}
if (day <> 31)
}
alert("Day must be between 1 and 31.");
return false;
}
if ((month==4 || month==6 || month==9 || month==11) && day==31)
}
alert("Month "+month+" doesn't have 31 days!")
return false
}
if (month == 2)
}
// check for february 29th
var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
if (day>29 || (day==29 && !isleap))
}
alert("February " + year + " doesn't have " + day + " days!");
return false;
}
}
return true; // date is valid
}







Date Format: mm/dd/yyyy


Sunday, September 14, 2008

PHP Classes

What are classes?

Classes are object-oriented programming for PHP.

What is object-oriented programming?

Object-oriented programming consists of three main vocabulary words: classes, methods, and objects. An object is basically a data structure (also known as an abstract data type), which are encapsulated in a set of routines known as methods. A class is a collection of methods and objects.
What's the purpose of classes in PHP?

It's the same reason as any other programming language: for large projects, classes provide superior organization and less repetitive code.


A Simple Example:
class dummy {
var $variable;
var $variable2 = 1;
var $variable3 = 2;
function sum($one, $two) {
$val = $one + $two;
return $val;
}
?>


As you might have guessed, the line "class dummy {" initializes the class. "dummy" is now inherited as the name of the class. The purpose of this will be shown later. Declaring global variables in classes however are a tad different then regular PHP. They must be preceded by "var". (For all you C coders, this is identical to "int variable;") Next, we see a function in it's most purest form. "function sum($one, $two) {" intializes the function by the name of "sum" with the required arguments $one and $two. The function now adds the value of $one and $two, and returns the value quite obviously through "return $val;". Got it? Time to add more :-)


An Advance Example of Class

<?
class dummy {
var $variable;
var $variable2 = 1;
var $variable3 = 2;
function sum($one, $two) {
$val = $one + $two;
return $val;
}
function sum2() {
$val = $this->sum($this->variable2, $this->variable3);
return $val;
}
}
?>

What we just did right there is one of the most important aspects of object-oriented programming called "inheritance." Let's look at this line for line. All our variables are declared through the "var" procedure, that's nothing new. Nor is the first function sum(). However, sum2() is. First off, you might notice there are no arguments for this variable. That's because this variable is a void, much like numerous internal PHP functions like time() or others I can't think of. This line displays the inheritance. The "$this" variable is a reserved variable in object-oriented PHP programming (translation - don't use it in your classes!) that actually does the inheritance. "$this->sum()" is basically interpreted as, "in this class, perform the sum() function." Like "$this->sum()", "$this->variable2" is interpreted as "in this class, use the value of 'variable2'." Likewise with $this->variable3. Note: all calls to native class functions or variables are done in this manner. Starting with "$this->" and followed by the name of the function or variable you wish to use. I can't stress the importance of that enough. Now I want to show you something imperative to object-oriented programming, using all this outside of your classes. This is how it's done if your class is contained in an external file:


<?
include("/path/to/the/file/with/your/class/in/it");
$yourclass = new yourclassname;
echo $yourclass->somevariable;
?>

If the class is internal, simple exclude the include() line. Now this is more inheritance. "$yourclass" inherits all of the class because of the usage of the "new yourclassname". Obviously, you would replace "yourclassname" with the name of your class in your script. "$yourclass" is now used the same way as "$this" was inside of your class, as shown from the "$yourclass->somevariable" reference. Got all that? Good.
As if you haven't been bogged down with inheritance enough yet, I've got some more for you.


<?
class dummy {
var $variable;
var $variable2 = 1;
var $variable3 = 2;
function sum($one, $two) {
$val = $one + $two;
return $val;
}
function sum2() {
$val = $this->sum($this->variable2, $this->variable3);
return $val;
}
}
class dummy2 extends dummy {
function sum2_clone() {
$val = $this->sum($this->variable2, $this->variable3);
return $val;
}
}

?>


Ok now this is just fun. The "sum2_clone()" function will return the exact same result (3) as will the original "sum2()" function! If you didn't guess yet, the "extends" does this. "extends" inherits all the values of one class for use in a completely different class. IMPORTANT - the name that follows "extends" is *always* the inherited class. In our example, the "dummy" class is inherited. Therefore, we can access "$this->sum()" and everything else from the "dummy" class. How cool is that?
I've got more about "extends" for you (and a new vocabulary word); constructors.


<?
class dummy {
var $variable;
var $variable2 = 1;
var $variable3 = 2;
function sum($one, $two) {
$val = $one + $two;
return $val;
}
function sum2() {
$val = $this->sum($this->variable2, $this->variable3);
return $val;
}
}
class dummy3 extends dummy {
function dummy3($variable1, $variable2) {
$val = $this->sum($variable1, $variable2);
return $val;
}


?>

So what's so special about that? What makes "dummy3" special is how you call it. You'd do it like this:


<?
include("/path/to/file");
$1 = 1;
$2 = 2;
$sum = new dummy3($1, $2);



?>

See how you can pass arguments right inside of your "new dummy3()" call? That's what's special about this. Though it might seem rather pointless, this is great to use for functions you use repetitively and want to make calls to with fewer lines of code. "$sum" will now return 3 if you did "echo $sum" by the way.
The next part of this tutorial is the "::" operator. To be honest, the example shown in the PHP manual is much better then anything I could write. However, I'll give it a whirl.


<?
class dummy4 {
function test() {
echo "I am from class dummy4.";
}
}
class dummy5 extends dummy4 {
function test() {
echo "I am from class dummy5.";
dummy4::test();
}
}

?>

Now, if you were to call the "test()" function from "dummy5" you would see this:
I am from class dummy5.I am from class dummy5.

I think this is pretty self explanatory. The :: operate is simply another way to make a call to something from another class just as "$this" did.
Now if I haven't held your hand through this tutorial, it's time for some parenting. Watch the example and learn.

class dummy6 {
function test() {
echo "I am from class dummy 6.";
}
}
class dummy7 extends dummy6 {
function test() {
echo "I am from class dummy 7.";
parent::test();
}
}
?>


This will return:

I am from class dummy 6.I am from class dummy 7.

"Parent" basically replaces "dummy6". The value of "parent" will always be the name of the class that follows "extends". Got all that? Good.
Finally, the last part of this tutorial deals with "references inside the constructor." Don't worry, it's easier then it sounds. Think of it as adding more to our constructor then just one function. Let's go.

class dummy8 {
function dummy8($text) {
echo $text;
}
}
function clone() {
echo $this->dummy8($this->text);
}
}
?>


Then you would do this:

include("/path/to/file");
$text = "Hey there.";
$class = new dummy8($text);
echo $class->clone();
?>


Can you see what's going to happen? "$class->clone()" will print:

Hey there.

See how it works? "$text" is now recognized as a variable inside the class, so "$this->text" is a proper reference to it. Get it? Good. And that's everything, I hope your mind isn't too fried :P Any questions/comments/complaints/suggestions/hate mail can be sent to Ben Wirth. Happy PHP-ing!

Tuesday, September 9, 2008

PHP Associated MySQL Functions

mysql_fetch_object: The mysql_fetch_object() function returns a row from a recordset as an object. It fetches one row of data from the result associated with the specified result identifier. The row is returned as an array. Each result column is stored in an array offset, starting at offset 0. This function gets a row from the mysql_query() function and returns an object on success, or FALSE on failure or when there are no more rows. mysql_fetch_object() is similar to mysql_fetch_array(), with one difference - an object is returned, instead of an array. Indirectly, that means that you can only access the data by the field names, and not by their offsets (numbers are illegal property names).

$result = mysql_query($sql,$con);
while ($row = mysql_fetch_object($result)) {
echo $row->FirstName . "
";
}


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

mysql_fetch_row: Returns a numerical array that corresponds to the fetched row and moves the internal data pointer ahead. Returns an numerical array of strings that corresponds to the fetched row, or FALSE if there are no more rows.mysql_fetch_row() fetches one row of data from the result associated with the specified result identifier. The row is returned as an array. Each result column is stored in an array offset, starting at offset 0.

$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
$row = mysql_fetch_row($result);
echo $row[0]; // 42
echo $row[1]; // the email value


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

mysql_fetch_array: Fetch a result row as an associative array, a numeric array, or both. This function gets a row from the mysql_query() function and returns an array on success, or FALSE on failure or when there are no more rows. Optional. Specifies what kind of array to return.

Possible values:
* MYSQL_ASSOC - Associative array
* MYSQL_NUM - Numeric array
* MYSQL_BOTH - Default. Both associative and numeric array


$result = mysql_query("SELECT id, name FROM mytable");
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
printf("ID: %s Name: %s", $row[0], $row[1]);
------------------------------ or ----------------------------------------
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
printf("ID: %s Name: %s", $row["id"], $row["name"]);
}
mysql_free_result($result);


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

mysql_fetch_assoc:Returns an associative array that corresponds to the fetched row and moves the internal data pointer ahead. mysql_fetch_assoc() is equivalent to calling mysql_fetch_array() with MYSQL_ASSOC for the optional second parameter. It only returns an associative array.

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

Tuesday, September 2, 2008

Authorize.net AIM Integration | Mail for Valid Transaction

<?php
// calling php config file
require("includes/configs.php");
?>
<!--

###########################################################
# #
# D O C U M E N T A T I O N #
# #
# This code sample has been successfully tested on #
# third-party web servers and performed according to #
# documented Advanced Integration Method (AIM) #
# standards. #
# #
# Last updated September 2004. #
# #
# For complete and freely available documentation, #
# please visit the Authorize.Net web site at: #
# #
# http://www.authorizenet.com/support/guides.php #
# #
###########################################################

###########################################################
# #
# D I S C L A I M E R #
# #
# WARNING: ANY USE BY YOU OF THE SAMPLE CODE PROVIDED #
# IS AT YOUR OWN RISK. #
# #
# Authorize.Net provides this code "as is" without #
# warranty of any kind, either express or implied, #
# including but not limited to the implied warranties #
# of merchantability and/or fitness for a particular #
# purpose. #
# #
# #
###########################################################

###########################################################
# #
# P R E R E Q U I S I T E S #
# #
# Basically, all the required code to generate 1) a #
# unique fingerprint, using the HMAC-MD5 algorithm, #
# and 2) a compatible timestamp is included in the #
# sample code provided in this file and the additional #
# files that should have accompanied this file: #
# - simdata.php #
# - simlib.php #
# #
# However, you need to verify that the required PHP #
# MHASH extension is available; otherwise, you will #
# not be able to generate the required fingerprint. #
# #
# The required MHASH extension comes with PHP and #
# requires no additional cost. #
# #
# Most web hosting providers install this extension #
# along with PHP; however, in some circumstances, you #
# may have to enable it yourself or ask your web host #
# to enable it for you. #
# #
# PLEASE UNDERSTAND that it is impossible for us to #
# anticipate any and all possible web server #
# configurations. #
# #
# If you cannot get the sample code to work due to an #
# unknown server configuration or missing PHP extension, #
# and if you cannot figure out how to test for the #
# availability of the required extension, consider #
# hiring a professional web developer or server #
# administrator. #
# #
# Authorize.Net is unable to assist you with web #
# server troubleshooting. #
# #
# #
###########################################################

###########################################################
# #
# C O N T A C T I N F O R M A T I O N #
# #
# For specific questions, #
# please contact Authorize.Net's Integration Services: #
# #
# integration at authorize dot net #
# #
# Please remember that we cannot support individual #
# e-commerce developers with programming problems and #
# other issues that could be easily solved by referring #
# to the available reference materials. #
# #
###########################################################

###########################################################
# #
# S I M I N A N U T S H E L L #
# #
###########################################################
# #
# 1. You gather some basic transaction data on your web #
# site. #
# #
# 2. Using a standard HTML form, you submit the required #
# information to Authorize.Net, by posting the form data #
# to a specific URL on Authorize.Net’s secure server. #
# #
# 3. On Authorize.Net’s secure server, you collect all #
# the financial information on the SIM Payment Form. #
# #
# 4. When the transaction has been completed, you may #
# either re-direct the user to another web page on your #
# web site or complete the transaction on #
# Authorize.Net’s secure server. #
# #
# #
###########################################################

###########################################################
# #
# H A R D C O D E D V A L U E S #
# #
# The purpose of this sample code is to demonstrate how #
# a basic SIM transaction works. #
# #
# For this purpose, we have hard-coded a number of #
# values, to expedite your testing and integration #
# efforts. #
# #
# Please, pay special attention to values, such as #
# your log-in ID, transaction key, amount, description, #
# etc. that may need to be changed throughout this #
# code sample and/or its associated include files. #
# #
# #
###########################################################

-->


<?
if($_REQUEST['x_Amount']==""){
echo "<script>window.location='index.htm'</script>";
}


$x_Description = $HTTP_GET_VARS['x_Description'];
$x_Amount = $HTTP_GET_VARS['x_Amount'];

$x_Description = $_REQUEST['x_Description'];
$x_Amount = $_REQUEST['x_Amount'];

// *** IF YOU WANT TO PASS CURRENCY CODE do the following: ***
// Assign the transaction currency (from your shopping cart) to $currencycode variable

$currencycode="USD";

if ($x_Description == "")
$x_Description = $HTTP_POST_VARS['x_Description'];

if ($x_Amount == "")
$x_Amount = $HTTP_POST_VARS['x_Amount'];

?>

<!-- Description: <?=$x_Description?> <BR />
Total Amount : <?=$x_Amount?> -->


<!-- <FORM action="https://test.authorize.net/gateway/transact.dll" method="POST">
--><!-- Uncomment the line ABOVE for test accounts or BELOW for live merchant accounts -->
<!--<FORM action="https://developer.authorize.net/param_dump.asp" method="POST">-->

<?

// authdata.php contains the loginid and x_tran_key.
// You may use a more secure alternate method to store these (like a DB / registry).

//include ("authorizedotnet/simdata.php");
//include ("authorizedotnet/simlib.php");

$DEBUGGING = 1; # Display additional information to track down problems
$TESTING = 1; # Set the testing flag so that transactions are not live
$ERROR_RETRIES = 2; # Number of transactions to post if soft errors occur

$auth_net_login_id = "2q";
$auth_net_tran_key = "biraj";
$auth_net_url = "https://secure.authorize.net/gateway/transact.dll";
# Uncomment the line ABOVE for test accounts or BELOW for live merchant accounts
# $auth_net_url = "https://secure.authorize.net/gateway/transact.dll";


$firstname = $_POST["txt_firstnatfme"];
$lastname = $_POST["txt_lastname"];
$streetaddress1 = $_POST["txt_address"];
$city = $_POST["txt_city"];
$state = $_POST["txt_state"];
$zip = $_POST["txt_zip"];
$country = $_POST["cmb_country"];
$email = $_POST["txt_email"];
$homephone = $_POST["txt_phone"];
$creditcard_no = $_POST["txt_creditcardno"];
$expiredate = $_POST["cmb_month"].$_POST["cmb_year"];
$invoice_no = date("siHdmY");





$authnet_values = array
(
"x_login" => $auth_net_login_id,
"x_version" => "3.1",
"x_delim_char" => "|",
"x_delim_data" => "TRUE",
"x_url" => "FALSE",
"x_type" => "AUTH_CAPTURE",
"x_method" => "CC",
"x_tran_key" => $auth_net_tran_key,
"x_relay_response" => "FALSE",
"x_card_num" => $creditcard_no,
"x_exp_date" => $expiredate,
"x_description" => $x_Description,
"x_amount" => $x_Amount,
"x_first_name" => $firstname,
"x_last_name" => $lastname,
"x_address" => $streetaddress1,
"x_city" => $city,
"x_state" => $state,
"x_zip" => $zip,
"x_phone" => $homephone,
);

$fields = "";
foreach( $authnet_values as $key => $value ) $fields .= "$key=" . urlencode( $value ) . "&";






$amount = $x_Amount;

// Trim $ sign if it exists
if (substr($amount, 0,1) == "$") {
$amount = substr($amount,1);
}
// I would validate the Order here before generating a fingerprint

// Seed random number for security and better randomness.

srand(time());
$sequence = rand(1, 1000);
// Insert the form elements required for SIM by calling InsertFP
//$ret = InsertFP ($loginid, $x_tran_key, $amount, $sequence);



//*** IF YOU ARE PASSING CURRENCY CODE uncomment and use the following instead of the InsertFP invocation above ***
//$ret = InsertFP ($loginid, $x_tran_key, $amount, $sequence, $currencycode);

// Insert rest of the form elements similiar to the legacy weblink integration
echo ("<input type=\"hidden\" name=\"x_description\" value=\"" . $x_Description . "\">\n" );
echo ("<input type=\"hidden\" name=\"x_login\" value=\"" . $loginid . "\">\n");
echo ("<input type=\"hidden\" name=\"x_amount\" value=\"" . $amount . "\">\n");

// *** IF YOU ARE PASSING CURRENCY CODE uncomment the line below *****
echo ("<input type=\"hidden\" name=\"x_currency_code\" value=\"" . $currencycode . "\">\n");




$_SESSION["description"]=$x_Description;
$_SESSION["length"]=$length;
$_SESSION["unit"]=$unit;
$_SESSION["startdate"]=$startDate;
$_SESSION["amount"]=$amount;
$_SESSION["cardnumber"]=$cardNumber;
$_SESSION["expirationDate"]=$expirationDate;
$_SESSION["name"]=$firstName;
$_SESSION["address"]=$address;
$_SESSION["city"]=$city;
$_SESSION["state"]=$state;
$_SESSION["zip"]=$zip;
$_SESSION["country"]=$country;

?>
<INPUT type="hidden" name="x_customer_ip" value="<?=$_SERVER[REMOTE_ADDR]?>">


<INPUT type="hidden" name="x_first_name" value="<?=$_POST['txt_firstname'];?>">
<INPUT type="hidden" name="x_last_name" value="<?=$_POST['txt_lasttname'];?>">

<INPUT type="hidden" name="x_address" value="<?=$streetaddress1;?>">
<INPUT type="hidden" name="x_city" value="<?=$city;?>">
<INPUT type="hidden" name="x_state" value="<?=$state;?>">
<INPUT type="hidden" name="x_zip" value="<?=$zip;?>">
<INPUT type="hidden" name="x_country" value="<?=$country;?>">
<INPUT type="hidden" name="x_phone" value="<?=$homephone;?>">
<INPUT type="hidden" name="x_fax" value="<?=$fax;?>">
<INPUT type="hidden" name="x_email" value="<?=$email;?>">
<INPUT type="hidden" name="x_delim_data" value="TRUE">

<INPUT type="hidden" name="x_method" value=""> <!--default will be Credit Card(CC)-->
<INPUT type="hidden" name="x_type" value="">
<INPUT type="hidden" name="x_card_num" value="<?=$creditcard_no;?>">
<INPUT type="hidden" name="x_exp_date" value="<?=$expiredate;?>">
<input type='hidden' name='x_invoice_num' value='<?=$invoice_no?>'>


<!-- <INPUT type="hidden" name="x_show_form" value="PAYMENT_FORM"> -->
<INPUT type="hidden" name="x_test_request" value="FALSE">
<INPUT type="hidden" name="x_relay_url" value="http://www.humpanch.com/authorizedotnet_thankyou.html">

<?php
$ch = curl_init("https://secure.authorize.net/gateway/transact.dll");
### Uncomment the line ABOVE for test accounts or BELOW for live merchant accounts
### $ch = curl_init("https://secure.authorize.net/gateway/transact.dll");
curl_setopt($ch, CURLOPT_HEADER, 0); // set to 0 to eliminate header info from response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // Returns response data instead of TRUE(1)
curl_setopt($ch, CURLOPT_POSTFIELDS, rtrim( $fields, "& " )); // use HTTP POST to send form data
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // uncomment this line if you get no gateway response. ###
$resp = curl_exec($ch); //execute post and get results
curl_close ($ch);
?>

<?
//echo "<b>02: Get post results:</b><br>";
//echo $resp;
//echo "<br>";
?>
<!-- <INPUT type="submit" value="Accept Order"> -->



<?php
//$resp_trim=rtrim($resp,"|");
//$resp_trim=str_split($resp, 1);
$resp_trim=explode("|",$resp);

//echo $resp_trim[0];
if($resp_trim[0]!="1"){

$smarty->assign("HIDVAL", "1");
$smarty->assign("MESSAGE","Thank you for signing up. Your Transaction was successful. An email has been sent to <strong>".$_POST['txt_email']."</strong>.");


$_SESSION["firstname"]=$firstname;
$_SESSION["lastname"]=$lastname;
$_SESSION["DESCRIP"]=$x_Description;
echo $_SESSION["DESCRIP"];
$_SESSION["EMAIL"]=$email;
$_SESSION["PHONE"]=$_POST['txt_phone'];
//echo $_SESSION["PHONE"];
$smarty->assign("EMAIL", $_POST['email']);



/*........... SEND MAIL TO CUSTOMERS .......................*/
/* MAIL SENT PHP */


echo $_SESSION["phone"];
if($_SESSION["blk"]!=""){
$blackberry=" ".$_SESSION["blk"]." Blackberry, ";
}
if($_SESSION["sharept"]!=""){
if($_SESSION["sharept"]=="59.95"){
$sharepoint="Additional Package Amount for Sharepoint Platinum 10GB";
}else if($_SESSION["sharept"]=="24.95"){
$sharepoint="Additional Package Amount for Sharepoint Gold 3GB";
}else{
$sharepoint="Additional Package Amount for Sharepoint Silver 500MB";
}
}

if($_SESSION["blackberrySyn"]!=""){
$blackBerrySyn="Blackberry Syncronisation Price";
}

if($_SESSION["blackberrysetupfee"]!=""){
$blkbrysetupfee="Blackberry Setup Fee";
}

if($_SESSION["totalamount"]!=""){
$totalamount="Total Amount";
}
if($_SESSION["mailbox"]==1){
$dmailbox="Mailbox";
}else{
$dmailbox="Mailboxes";
}

if($_SESSION["blk"]>1){
$noblk= "(".$_SESSION["blk"]." Numbers)";
}
$message1 ="<html><head><style type='text/css'>
<!--
.tableOdd {
font-family: 'Lucida Sans';
font-size: 12px;
font-style: normal;
font-weight: bold;
background-color: #DFE9F7;
padding-left:20px;
}
.tableOddC {
font-family: 'Lucida Sans';
font-size: 12px;
font-style: normal;
font-weight: normal;
text-align:right;
background-color: #DFE9F7;
padding-right:20px;
}
.tableEven {
font-family: 'Lucida Sans';
font-size: 12px;
font-style: normal;
font-weight: bold;
background-color: #FFFFFF;
padding-left:20px;
}
.tableEvenC {
font-family: 'Lucida Sans';
font-size: 12px;
font-style: normal;
font-weight: normal;
text-align:right;
background-color: #FFFFFF;
padding-right:20px;
}
.tableTotal {
font-family: 'Lucida Sans';
font-size: 12px;
font-style: normal;
font-weight: bolder;
background-color: #EEEEEE;
padding-left:20px;
}
.tableTotalC {
font-family: 'Lucida Sans';
font-size: 12px;
font-style: normal;
font-weight: bolder;
text-align:right;
background-color: #EEEEEE;
padding-right:20px;
}
-->
</style>";
$message1 .="</head><body bgcolor='#EEEEEE'><br/><br/><center><table border='0' width='60%' bgcolor='#FFFFFF' cellspacing='0'><tr><td style='padding-left:20px; padding-right:20px; padding-top:40px;'><p><table border='0'><tr><td width='70%'><center><img src='http://www.humpanch.com/images/email-logo-mf.gif' width='257' height='77'/></td><td width='15%'> </td><td style='float:left;' width='15%'><span><a href='http://humpanch.com/chats/request.php?l=admin&x=1&deptid=29&pagex=http%3A//www.humpanch.com/' target='_blank'><img src='http://www.humpanch.com/images/livechat-m.gif' border='0' width='120' height='44'></a></span></td></tr></table></p></center><span style='font-weight:normal; font-size:12px; font-family: Lucida Sans';>Hello ".$_SESSION["firstname"]." ".$_SESSION["lastname"]."</span>,<p style='font-weight:normal; font-size:12px; font-family: Lucida Sans';>Thank you for signing up with humpanch. Please do not ignore this e-mail as it contains vital details that will help you in using our <span>services</span>.</p><p style='font-weight:normal; font-size:12px; font-family: Lucida Sans';>If you have not configured your Account Administration Panel yet, then please configure it now by clicking <a href='http://www.humpanch.com/payment-cpanel.html'>here</a>.</p><p style='font-weight:normal; font-size:12px; font-family: Lucida Sans';>Account Administration Panel needs to be configured initially so that you can start using the services you have purchased. Once you have completed the set-up, you can login into your Account Administration Panel at any time to configure the services you have purchased. You also have the option in your Account Administration Panel of purchasing additional services at any time.</p><p style='font-weight:normal; font-size:12px; font-family: Lucida Sans';>You have purchased following services from us.</p>
<table border='0' width='100%'><tr><td>
<table width='100%' border='0' cellspacing='0' cellpadding='2'>";
if($_SESSION["DESCRIP"]=="SharePointSilver"){
$message1 .= "<tr>
<td class='tableOdd' width='60%'>Sharepoint Silver Plan</td>
<td class='tableOddC'>$ 8.95</td>
</tr>";
}else if($_SESSION["DESCRIP"]=="SharePointGold"){
$message1 .= "<tr>
<td class='tableOdd' width='60%'>Sharepoint Gold Plan</td>
<td class='tableOddC'>$ 24.95</td>
</tr>";
}else if($_SESSION["DESCRIP"]=="SharePointPlatinum"){
$message1 .= "<tr>
<td class='tableOdd' width='60%'>Sharepoint Platinum Plan</td>
<td class='tableOddC'>$ 59.95</td>
</tr>";
}else{
$message1 .= "<tr>
<td class='tableOdd' width='60%'>".$_SESSION["description"]." ".$_SESSION["mailbox"]." ".$dmailbox."</td>
<td class='tableOddC'>".$_SESSION["mailboxprice"]."</td>
</tr>";

if($_SESSION["blk"]!=""){
$message1 .="<tr>
<td class='tableEven' width='60%'>".$blackBerrySyn." ".$noblk."</td>
<td class='tableEvenC' width='40%'>".$_SESSION["blackberrySyn"]."</td>
</tr><tr>
<td class='tableOdd' width='60%'>".$blkbrysetupfee." ".$noblk."</td>
<td class='tableOddC' width='40%'>".$_SESSION["blackberrysetupfee"]."</td>
</tr>";
}

if($_SESSION["sharept"]!=""){
$message1 .="<tr>
<td class='tableEven' width='60%'>".$sharepoint."</td>
<td class='tableEvenC' width='40%'>".$_SESSION["sharept"]."</td>
</tr>";
}


$message1 .="<tr>
<td class='tableTotal' width='60%'>".$totalamount."</td>
<td class='tableTotalC' width='40%'>$".$_SESSION["amount"]."</td>
</tr>";

}



$message1 .="</table></td></tr></table></center>";





$message1 .="<p style='font-weight:normal; font-size:12px;font-family: Lucida Sans;'>If you have any questions or need help, please do not hesitate to contact us at <a href='mailto:support@humpanch.com'>support@humpanch.com</a>. You can also visit http://www.humpanch.com or click on the Live Chat icon above to reach us.</p>";

$message1 .="<p style='font-weight:normal; font-size:12px; font-family: Lucida Sans; padding-bottom:40px;'>Regards,<br/>humpanch Team</p></td></tr></table>";


$message1 .="</body></html>";

$message2 ="<strong>Email :</strong>".$_POST['txt_email']."<br/><strong>Phone :</strong>".$_SESSION["PHONE"];

$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

$headers .= 'From: For humpanch Sales Team<billing@humpanch.com>' . "\r\n" .
'Reply-To: billing@humpanch.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();

$smarty->assign("EMAIL", $_POST['email']);
$smarty->assign("MESSAGE2","You will be automatically redirected to setup your Administration Panel after ");

if($_SESSION["firstname"]!=""){
mail('sales@humpanch.com', 'FOR SALES TEAM:humpanch Account Administration Set-up Details
', $message2.$message1, $headers);
mail($_POST['txt_email'], 'humpanch Account Administration Set-up Details
', $message1, $headers);
}


/*--------------Track IP -------------------------*/
$logparameter_date = date("F jS, Y H:i:s");
$logparameter_d = "AIM";
$remote_address = $_SERVER['REMOTE_ADDR'];

$logparameter = $logparameter_date . "Invoice No.".$invoice_no." Method: " . $logparameter_d . " IP: ". $remote_address . " Card Number: ".$creditcard_no." Expire Date: ".$expiredate." Description: ".$x_Description." Amount: ".$x_Amount." First Name ".$firstname." Last Name: ".$lastname." Street Address".$streetaddress1." City:".$city." State: ".$state." Zip :".$zip." Home Phone".$homephone."\n";
error_log($logparameter, 3, "crcard-iptrack.log");


}else{
$smarty->assign("HIDVAL", "0");
$smarty->assign("MESSAGE","<strong><span style='color:#FF0000;'>The Credit Card information entered is invalid. You will be redirected to the home page.</span></strong>");
$smarty->assign("MESSAGE2","You will be redirected to home page after ");

}

/* end */














$smarty->assign("some","");
$smarty->assign("htmltitle","humpanch - Reseller");
// determind which inner body to be displayed
$smarty->assign("innerbody","sim.tpl");
$smarty->display("main.tpl");
session_destroy();
?>

Monday, September 1, 2008

LDAP Authentication, PHP

<?php
$ds=ldap_connect("***.***.**.**",389); // must be a valid LDAP server!
ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($ds, LDAP_OPT_REFERRALS, 0);
$r=ldap_bind($ds,$username,$password_ldap);
if($r){
$sr=ldap_search($ds, "DC=humaaaaa,DC=com", "(CN=*)") or die('LDAP SEARCH ERROR
');
//$sr=ldap_search($ds, "DC=".$domainname2[0].",DC=".$domainname2[1]."", "(CN=*)") or die('LDAP SEARCH ERROR
');
if(!$sr){
echo "<script>window.location='login.php?status=false'</SCRIPT>";
}else{

$noof_user=ldap_count_entries($ds, $sr); // calculate no. of records found
if($noof_user>=1){
$info=ldap_get_entries($ds, $sr);
for ($i=0; $i<$info["count"]; $i++) {
$givennname=$info[$i]["name"][0];

}

echo "<script>window.location='index.php?session_user=".$username."&access=valid'</SCRIPT>";
}else{
echo "<script>window.location='login.php?status=false'</SCRIPT>";
}
?>

Sunday, August 31, 2008

Java Script: Allow only Numeric Value, Decimal

function allowOnlyNumeric(e) {

var bName = navigator.appName; //alert(bName);

if(bName == "Microsoft Internet Explorer"){

var key_ie = window.event.keyCode;

//alert(key_ie);

if ( (key_ie > 47 && key_ie < 58) || key_ie == 46 || key_ie == 32 || key_ie == 45 )

return;

else

window.event.returnValue = null;

}else{

var key_mozila = e.which;

//alert(key_mozila);

if ( (key_mozila > 47 && key_mozila < 58) || key_mozila == 46 || key_mozila == 32 || key_mozila == 45 )

return;

else

return false;

}

}

onkeypress="javascript:return allowOnlyNumeric(event);"

Saturday, August 23, 2008

MySQL from Command Prompt

The following tutorial assumes that you already have downloaded and installed MySQL on your Windows machine. From inside Windows here’s how you would access MySQL this way:
1) launch a command window by going to: START->ALL PROGRAMS->ACCESSORIES->COMMAND PROMPT
[NOTE: you can also get to it by going to START->RUN and typing: cmd ]
2) inside the Command Prompt window type: cd c:\mysql\bin
(or change directory to the location that you installed if you didn’t use the default install location)
3) if you don’t have a password set yet, then you can set it easily by typing the following:
mysqladmin -u root password new_password
where new_password is the new password that you would like to use
4) next, when you have already set a custom MySQL root password (step #3) then type: mysql -u root -p
PROBLEM #1: if you receive a message asking for your password then enter the custom password (you’ll see asterisk instead of the password). If for some reason you can’t figure out the password you can reset it by following the instructions here: http://dev.mysql.com/doc/mysql/en/Resetting_permissions.html
PROBLEM #2: If you receive a message that indicates the MySQL server isn’t running then you can start the MySQL service from within the Command Prompt by entering the following: net start mysql — you can also see a list of all running NET services by typing: net start
5) next, if the MySQL server is running and you entered in your password correctly you should now be set to communicate directly with the MySQL server from the Command Prompt just like you would if you were telnet or SSH to MySQL on a server. The command prompt should look like this now:
mysql>
You can now view your available database by typing: show databases

Wednesday, August 6, 2008

Page rendering time in PHP

function utime(){
$time = explode( " ", microtime());
$usec = (double)$time[0];
$sec = (double)$time[1];
return $sec + $usec;
}

/*...........on the top of the page................*/
$start = utime();

/*..........bottom of the page before the bolo.......*/
$end = utime();
$run = $end - $start;
echo "<!--

Page created in: " .
substr($run, 0, 5) . " seconds.

-->";

Friday, July 11, 2008

Create Log File PHP

$logparameter_date = date("F jS, Y H:i:s");
$logparameter_d = "AIM";
$remote_address = $_SERVER['REMOTE_ADDR'];

$logparameter = $logparameter_date . "Invoice No.".$invoice_no." Method: " . $logparameter_d . " IP: ". $remote_address . " Card Number: ".$creditcard_no." Expire Date: ".$expiredate." Description: ".$x_Description." Amount: ".$x_Amount." First Name ".$firstname." Last Name: ".$lastname." Street Address".$streetaddress1." City:".$city." State: ".$state." Zip :".$zip." Home Phone".$homephone."\n";
error_log($logparameter, 3, "crcard-iptrack.log");

Tuesday, July 1, 2008

PHP-MySQL Interview Questions

What is the difference between inner join and outer join?
Inner join displays rows from table where the data is available in both the tables, where in outer join we can configure it to bring out rows from one table where the data is missing in other table for the corresponding rows.
Inner join
Say you have one table of CUSTOMERS and one table of ORDERS. Each row in the ORDERS table has a reference (foreign key reference) to a customer id which represents what customer placed that order. If you want to run a query that lists the orders along with the names of the customers who ordered them (since a customer id number itself it pretty useless), you will want to execute a join query:
SELECT CUSTOMERS.NAME, ORDERS.NAME
FROM CUSTOMERS
INNER JOIN ORDERS
ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID
Outer join
If for some reason, you wanted the query results to return all customer name regardless of whether they placed an order, you can use one of two types of OUTER JOINS, in this case, a LEFT JOIN:
SELECT CUSTOMERS.NAME, ORDERS.NAME
FROM CUSTOMERS
LEFT JOIN ORDERS
ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID



Which will be faster out of queries with explicit INNER JOIN and implicit one?
1. Implicit one will be faster.
2. i believe explicit inner join will be faster since in that case mysql doesn’t find the type of join. otherwise it will fetch all the records from both the tables and display it to user.

How do you maintain session in a load balancing system?
Using a common session save path in the php.ini file by mounting a shared location in each of the server.

What are the advantages of PHP5?
PHP 5, which was released earlier this week, is the first major release of PHP in years to focus on new features.
While one of the key goals behind PHP 3 was increasing PHP/FI 2.0’s performance and efficiency, at the same time it introduced a whole new set of functionality.
That was back in 1998.
PHP 4 provided another speed burst, as it introduced the Zend Engine. However, the majority of PHP 4’s changes were behind the scenes. Those features allowed more people than ever to use PHP, but it didn’t provide them with more tools to build their sites.
Finally, after six years, the community has revisited the legacy baggage that made tackling some problems unnecessarily difficult.
In particular, PHP 4’s version of object-oriented programming (OOP) lacks many features, the MySQL extension doesn’t support the new MySQL 4.1 client protocol, and XML support is a hodgepodge.
Fortunately, PHP 5 improves on PHP 4 in three major areas:

* Object-oriented programming
* MySQL
* XML

These items have all been completely rewritten, turning them from limitations into star attractions. While these changes alone warrant a new version of PHP, PHP 5 also provides a plethora of other new features.
In this article, I highlight seven of my favorite PHP 5 features. These features allow your PHP 5 code to frequently be shorter, more elegant, and more flexible than ever before.

1. Robust Support for Object-Oriented Programming
Ever since Zeev and Andi’s late-night OOP hack, PHP programmers have clamored for an increasing amount of OO features. However, neither PHP 3 nor PHP 4 truly incorporates objects into its core.
With PHP 5, PHP programmers can at last stop apologizing for PHP’s krufty OO support. It offers:
* Constructors
* Destructors
* Public, protected, and private properties and methods
* Interfaces
* Abstract classes
* Class type hints
* Static properties and methods
* Final properties and methods
* A whole suite of magical methods
Additionally, objects are now both assigned–and passed–by reference instead of by value, so the necessity to liberally sprinkle ampersands throughout your code is no more.
If you’re a person who enjoys web programming using objects and patterns, then these features alone will make your year. However, PHP 5’s just getting started.

2. A Completely Rewritten MySQL Extension
The MySQL database is PHP’s partner in crime. Many developers power their web sites with MySQL, yet the MySQL extension is showing its age. In retrospect, some design decisions weren’t the best solutions after all.
Also, the latest versions of MySQL, 4.1 and 5.0, introduce many new features, some of which require significant changes to the extension. As a result, PHP 5 comes with a completely new and improved MySQL extension. Dubbed MySQLi, for MySQL Improved. It offers:
* Prepared statements
* Bound input and output parameters
* SSL connections
* Multi-query functions
MySQLi even takes advantage of PHP 5’s new object-oriented support to provide an OO interface to MySQL. On top of that, the latest versions of MySQL now enable subselects, transactions, and replication.

3. A Suite of Interoperable XML Tools
PHP 5 fixes the major problems in PHP 4’s XML extensions. While PHP 4 allows you to manipulate XML, its XML tools are only superficially related. Each tool covers one part of the XML experience, but they weren’t designed to work together, and PHP 4 support for the more advanced XML features is often patchy.
Not so in PHP 5.
The new XML extensions:
* Work together as a unified whole.
* Are standardized on a single XML library: libxml2.
* Fully comply with W3 specifications.
* Efficiently process data.
* Provide you with the right XML tool for your job.
Additionally, following the PHP tenet that creating web applications should be easy, there’s a new XML extension that makes it simple to read and alter XML documents. The aptly named SimpleXML extension allows you to interact with the information in an XML document as though these pieces of information are arrays and objects, iterating through them with for-each loops, and editing them in place merely by assigning new values to variables.
In short, SimpleXML kicks ass!
If you know the document’s format ahead of time, such as when you’re parsing RSS files, REST results, and configuration data, SimpleXML is the way to go.
And if you’re a DOM fan, you’ll be pleasantly surprised with PHP 5’s DOM extension, which is light-years beyond what you’re using in PHP 4.

4. An Embedded Database with SQLite
While MySQL is greater than ever, it’s actually “too much database” for some jobs. SQLite is an embedded database library that lets you store and query data using an SQL interface without the overhead of installing and running a separate database application.
When your application needs a server-side storage mechanism but you can’t rely upon the presence of a specific database, turn to SQLite. It correctly handles locking and concurrent accesses, the two big headaches with homebrewed flat files.
PHP 5 bundles SQLite, providing developers with a database that’s guaranteed to work on all PHP 5 installations. Despite the name, SQLite is nowhere close to a “lite” database. It supports:
* Transactions
* Subqueries
* Triggers
* And many other advanced database features
You can even write user-defined functions in PHP and call them from within SQLite. This is by far and away the coolest feature available in any PHP database extension.
5. Cleaner Error Handling with Exceptions
PHP 5 offers a completely different model of error checking than what’s available in PHP 4. It’s called exception handling. With exceptions, you’re freed from the necessity of checking the return value of every function. Instead, you can separate programming logic from error handling and place them in adjoining blocks of code.
Exceptions are commonly found in object-oriented languages such as Java and C++. When used judiciously, they streamline code, but when used willy-nilly, they create spaghetti code.
Right now, only a few PHP extensions use exceptions, but they’re slowly being phased in. However, they’re available today for any PHP code you write.

6. A First-Class SOAP Implementation
SOAP is a key component of the fast-growing web services field. This extension lets developers create SOAP clients with or without a Web Services Description Language (WSDL) file, and also implement SOAP servers in PHP.
PHP 4’s SOAP support is only fair. While there are a few SOAP packages, the most mature ones are written in PHP instead of C. Therefore, they are slow, and you have to download and install them yourself.
With PHP 5, there’s finally a usable SOAP extension written in C. Currently, this extension implements most, but not all, of SOAP 1.2. This is a significant improvement over previous C extension, and future pieces will be added in time.
Particularly in comparison with .NET and Java, PHP’s SOAP support has always lagged behind the curve. Whether you love or hate SOAP, PHP needs to offer a first-class SOAP extension, and I’m excited to finally see some momentum in this direction.

7. Iterators
Iterators are a completely new PHP 5 feature. They allow you to use a for-each loop to cycle through different types of data: directory listings, database results, and even XML documents. SPL — Standard PHP Library — is a collection of iterators that provide this functionality and also filter, limit, cache, and otherwise modify iterator results.
Iterators are an incredibly handy way to abstract away messy details from your code.
For example, the DirectoryIterator turns directory iteration from this:
$dir = opendir($path);
while (false !== ($file = readdir($dir))) {
print "$filen";
}
closedir($dir);
Into this:
foreach (new DirectoryIterator($path) as $file) {
print "$filen";
}
There are no directory handles to mess about with, nor ugly conditions to check inside a while loop.
These are my top seven favorite features of PHP 5, but they’re by no means the only ones. Besides what I’ve already highlighted, PHP 5 also offers:

* Enhanced streams, wrappers, and filters.First introduced in PHP 4.3, streams are an underutilized part of PHP. They allow you to place a file interface on reading and writing data using protocol-specific objects known as wrappers. Streams also let you modify the data flowing through them by attaching filters.
* Code introspection using the Reflection classes.This set of classes lets you examine classes, methods, parameters, and more, to discover object attributes. It is now simple and easy to create PHP class browsers, debuggers, and other tools that rely on gathering details about objects and functions.
* Compliant HTML output thanks to Tidy.The Tidy extension makes it easy to ensure that your output is valid HTML and XHTML. Its smart parser brings even the most unruly of files into compliance with the latest W3C specifications.
* Superior command-line processing.The PHP5 command-line version now allows individual line processing, similar to Perl and awk. You can specify code to be run at the beginning, on, and at the end of each line in a file.

I hope you’ve found this quick tour around PHP 5 useful. As you can see, PHP 5 is leaps and bounds better than before. I’m sure you’ll find all sorts of cool ways to incorporate its features into your programs.


What are the Importance of Class autoloading?
Many developers writing object-oriented applications create one PHP source file per-class definition. One of the biggest annoyances is having to write a long list of needed includes at the beginning of each script (one for each class).
In PHP 5, this is no longer necessary. You may define an __autoload function which is automatically called in case you are trying to use a class which hasn’t been defined yet. By calling this function the scripting engine is given a last chance to load the class before PHP fails with an error.
Basically, you get a class name as a parameter in your __autoload() function, and using it you have to figure out the path to the actual class file and include it.
If all of the classes are at known paths in known folders, you might be able to find the class file path using simple string concatenation. However, if the folder structure is more complex, a convenient solution is to have a class name/class file path map (associative array), whether hand-made or generated:
function __autoload($classname)
{
$classes = array(
“NotFoundView” => APP_VIEW_DIR.”notFound/NotFoundView.class.php”,
“ErrorView” => APP_VIEW_DIR.”error/ErrorView.class.php”
// and so on
);
if (array_key_exists($classname, $classes)) require($classes[$classname]);
// using name as key, get the path and include the file
}
There can be several autoloading functions named differently, but then they have to be registered explicitly using spl_autoload_register(). Class methods can also be used.
These hacks are not very clean, but they help to bring PHP one little step closer to object- and library-oriented approach.


How can we refresh a page every 20 seconds wothout using javascript?
We can refresh the page with the help of meta refresh tag.
The meta tag belongs within the of your HTML document. When used to refresh the current page, the syntax looks like this:
meta equiv="refresh" content="20"
This is the amount of time, in seconds, until the browser should reload the current page.
Redirecting to a New Page
While the reload option is useful, it is usually not what people want from the meta refresh tag. To redirect to a new page, the syntax is nearly the same:
meta equiv="refresh" content="2;url="
The only difference is in the content attribute.
content=”2;url=http://webdesign.about.com”
The number is the time, in seconds, until the page should be redirected. Then, separated by a semi-colon (;) is the URL that should be loaded.


What is the difference between nodeName and tagName in DOM?
Both function can be applied for element but tagName cant be applied for text node since the text node is not a tag.

How to differentiate isset and empty?
isset -> this variable handling functions determine whether a variable is set . It checks whether a variable is set even though it is empty.
empty -> as the term itself has already given a sign that it would related to something thats empty, this variable handling functions determine whether a variable is empty. It checks whether a variable has a value whether its emptystring, zero0, or not set at all.


What’s the difference between the *connect and *pconnect database functions?
mysql_pconnect() acts very much like mysql_connect() with two major differences.
First, when connecting, the function would first try to find a (persistent) link that’s already open with the same host, username and password. If one is found, an identifier for it will be returned instead of opening a new connection.
Second, the connection to the SQL server will not be closed when the execution of the script ends. Instead, the link will remain open for future use (mysql_close() will not close links established by mysql_pconnect()).

These type of links is therefore called ‘persistent’.

What is the difference between Reply-to and Return-path in the headers of a mail function?
Reply-to: Reply-to is where to delivery the reply of the mail.
Return-path: Return path is when there is a mail delivery failure occurs then where to delivery the failure notification.

What is the purpose of the following files having extensions 1) frm 2) MYD 3) MYI. What these files contains?

In MySql, the default table type is MyISAM.
Each MyISAM table is stored on disk in three files. The files have names that begin with the table name and have an extension to indicate the file type.
The ‘.frm’ file stores the table definition.
The data file has a ‘.MYD’ (MYData) extension.
The index file has a ‘.MYI’ (MYIndex) extension.


What are the advantages of stored procedures, triggers, indexes?
A stored procedure is a set of SQL commands that can be compiled and stored in the server. Once this has been done, clients don’t need to keep re-issuing the entire query but can refer to the stored procedure. This provides better overall performance because the query has to be parsed only once, and less information needs to be sent between the server and the client. You can also raise the conceptual level by having libraries of functions in the server. However, stored procedures of course do increase the load on the database server system, as more of the work is done on the server side and less on the client (application) side.
Triggers will also be implemented. A trigger is effectively a type of stored procedure, one that is invoked when a particular event occurs. For example, you can install a stored procedure that is triggered each time a record is deleted from a transaction table and that stored procedure automatically deletes the corresponding customer from a customer table when all his transactions are deleted.
Indexes are used to find rows with specific column values quickly. Without an index, MySQL must begin with the first row and then read through the entire table to find the relevant rows. The larger the table, the more this costs. If the table has an index for the columns in question, MySQL can quickly determine the position to seek to in the middle of the data file without having to look at all the data. If a table has 1,000 rows, this is at least 100 times faster than reading sequentially. If you need to access most of the rows, it is faster to read sequentially, because this minimizes disk seeks.

What are the difference between abstract class and interface?
Abstract class: abstract classes are the class where one or more methods are abstract but not necessarily all method has to be abstract. Abstract methods are the methods, which are declare in its class but not define. The definition of those methods must be in its extending class.
Interface: Interfaces are one type of class where all the methods are abstract. That means all the methods only declared but not defined. All the methods must be define by its implemented class.


What are the differences between require and include, include_once?
When a script require another script, if the required script does not exists, the script will not go farther but in include, the script will run till end of script if the included file does not exists.
include_once will include a file only once. On the other hand, include will try to include the file though the has already been included and will run the included file every time it has been included.