PHP Tutorial

Download as pdf or txt
Download as pdf or txt
You are on page 1of 432

PHP

MSQL (with Advanced Queries)

VALIDATION

JAVASCRIPT

AJAX – SIMPLE TO ADVANCED

PHP - XML

WEBSERVICES

HTACCESS

CURL

PROJECT ORIENTED PROBLEM SOLVING TECHNIQUES

FUNCTIONS (PHP, MYSQL)

CODEIGNITER FRAMEWORK - PHP

DRUPAL V.6.17 – PHP CMS

OOPS – PHP

Google ALL API References

More Payment Gateway APIs (Online & Credit Cards)

User Defined Project Oriented Library Tracks


By,
M.N.Ramasubbu.
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

Table of Contents
1
2
3
4
5
6
7
8

Page 2 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

PHP TUTORIAL
PHP Basics

PHP stands for PHP: Hypertext Preprocessor

PHP is a case sensitive webdevelopment software.

Which place to store or save PHP files

1. If you using Xampp server then

colon:/xampp/htdocs/your desire folder/filename.php

2. Otherwise using phpdev server then

colon:/phpdev/www/your desire folder/filename.php

colon:/ means F:/ or E:/ or C:/ or any one.

How to start the PHP coding

<?php

?>

(or)

<?PHP
?>

(or)

If the shorthand function is enabled in php.ini configuration file (Its dangerous syntax)
<?
?>

Each line ends with semicolon.

Each variable name starts with “$” symble.

Examples

$a = 10;
$b = ―Name‖;
Variable declaration syntax
$var_name = value;
How to display your name

<?php
echo ―Your Name‖;
$name = ―Your Name‖;

Page 3 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

echo $name;
?>

or

<?php
$name = print "Your Name";
echo "<br>";
echo $name;
?>

Difference between “echo” and “print”

The ―echo‖ keyword is used to just display any words.

The ―print‖ keyword is used to display any words. But it returns 1 or 0 value.

Comments in PHP

In PHP, we use // to make a single-line comment or /* and */ to make a large comment block.

If you want to use html tags in php then using echo command.

Add, Sub, Multiply and divide 2 no's

<?php
$a = 20;
$b = 5;
echo $a + $b;
echo ―<br>‖;
echo $a - $b;
echo ―<br>‖;
echo $a * $b;
echo ―<br>‖;
echo $a / $b;
?>
Arithmetic Operators

Page 4 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

The If...Else Statement


If you want to execute some code if a condition is true and another code if a condition is false, use
the if....else statement.

Syntax
if (condition)
code to be executed if condition is true;
else
code to be executed if condition is false;

Page 5 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

Example
<html>
<body>

<?php
$d=date("D");
if ($d=="Fri")
echo "Have a nice weekend!";
else
echo "Have a nice day!";
?>

</body>
</html>

The ElseIf Statement


If you want to execute some code if one of several conditions are true use the elseif statement

Syntax

if (condition)
code to be executed if condition is true;
elseif (condition)
code to be executed if condition is true;
else
code to be executed if condition is false;

Example

<html>
<body>

<?php
$d=date("D");
if ($d=="Fri")
echo "Have a nice weekend!";
elseif ($d=="Sun")
echo "Have a nice Sunday!";
else
echo "Have a nice day!";
?>

</body>
</html>

Page 6 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

The Switch Statement


If you want to select one of many blocks of code to be executed, use the Switch statement.
The switch statement is used to avoid long blocks of if..elseif..else code.
Syntax
switch (expression)
{
case label1:
code to be executed if expression = label1;
break;
case label2:
code to be executed if expression = label2;
break;
default:
code to be executed
if expression is different
from both label1 and label2;
}

Example

<html>

<body>

<?php
switch ($x)
{
case 1:
echo "Number 1";
break;
case 2:
echo "Number 2";
break;
case 3:
echo "Number 3";
break;
default:
echo "No number between 1 and 3";
}
?>

</body>
</html>

What is an array?

When working with PHP, sooner or later, you might want to create many similar variables.
Instead of having many similar variables, you can store the data as elements in an array.

Page 7 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

Each element in the array has its own ID so that it can be easily accessed.
There are three different kind of arrays:
 Numeric array - An array with a numeric ID key
 Associative array - An array where each ID key is associated with a value
 Multidimensional array - An array containing one or more arrays

Numeric Arrays
A numeric array stores each element with a numeric ID key.
There are different ways to create a numeric array.

Example 1
In this example the ID key is automatically assigned:
$names = array("Peter","Quagmire","Joe");

$names[0] = "Peter";
$names[1] = "Quagmire";

Example 2

In this example we assign the ID key manually:

$names[2] = "Joe";

The ID keys can be used in a script:

<?php

$names[0] = "Peter";
$names[1] = "Quagmire";
$names[2] = "Joe";

echo $names[1] . " and " . $names[2] .


" are ". $names[0] . "'s neighbors";
?>

Associative Arrays
Example 1
In this example we use an array to assign ages to the different persons:
$ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34);
Example 2
This example is the same as example 1, but shows a different way of creating the array:

<?php

Page 8 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

$ages['Peter'] = "32";
$ages['Quagmire'] = "30";
$ages['Joe'] = "34";

echo "Peter is " . $ages['Peter'] . " years old.";

?>

Get array count

<?php

$a = array(―one‖,‖Two‖,‖three‖);

echo count($a);

?>

Output

Merge 'n' arrays

Syntax

array_merge(array1,array2,...,arrayn);

Example

<?php

$a = array(―one‖);
$b = array(―two‖);

$c = array_merge($a,$b);

print_r($c);

?>

Print array values

<?php

print_r($array);

?>

Page 9 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

Delete an Array element with function

<?php

$a = array("Ram","Subbu","Vijay","Kannan","Bala","Ashok","Ganga");

deleteFromArray($a,$a[0]); // Call function

function deleteFromArray(&$array, $deleteIt, $useOldKeys = FALSE)

$tmpArray = array();

$found = FALSE;

foreach($array as $key => $value)

if($value !== $deleteIt)

if(FALSE === $useOldKeys)

$tmpArray[] = $value;

else

$tmpArray[$key] = $value;

else

$found = TRUE;

Page 10 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

$array = $tmpArray;

return $found;

?>

Multidimensional Arrays

In a multidimensional array, each element in the main array can also be an array. And each
element in the sub-array can be an array, and so on.

Example

In this example we create a multidimensional array, with automatically assigned ID keys:

$families = array
(
"Griffin"=>array
(
"Peter",
"Lois",
"Megan"
),
"Quagmire"=>array
(
"Glenn"
),
"Brown"=>array
(
"Cleveland",
"Loretta",
"Junior"
)
);

The array above would look like this if written to the output:

Array
(
[Griffin] => Array
(
[0] => Peter
[1] => Lois
[2] => Megan
)

Page 11 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

[Quagmire] => Array


(
[0] => Glenn
)
[Brown] => Array
(
[0] => Cleveland
[1] => Loretta
[2] => Junior
)
)

Looping
Very often when you write code, you want the same block of code to run a number of times. You
can use looping statements in your code to perform this.

In PHP we have the following looping statements:

 while - loops through a block of code if and as long as a specified condition is true
 do...while - loops through a block of code once, and then repeats the loop as long as a
special condition is true
 for - loops through a block of code a specified number of times
 foreach - loops through a block of code for each element in an array

The while Statement


The while statement will execute a block of code if and as long as a condition is true. ( If you
don't know how many times you want to do something then using while loop).

Syntax

while (condition)
code to be executed;

Example

The following example demonstrates a loop that will continue to run as long as the variable i is
less than, or equal to 5. i will increase by 1 each time the loop runs:

<html>
<body>

<?php
$i=1;
while($i<=5)
{
echo "The number is " . $i . "<br />";
$i++;
}
?>

Page 12 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

</body>
</html>

Output

The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
The do...while Statement

The do...while statement will execute a block of code at least once - it then will repeat the loop
as long as a condition is true.

Syntax

do

{
code to be executed;
}
while (condition);

Example

The following example will increment the value of i at least once, and it will continue incrementing
the variable i as long as it has a value of less than 5:

<html>
<body>

<?php
$i=0;
do
{
$i++;
echo "The number is " . $i . "<br />";
}
while ($i<5);
?>

</body>
</html>

Output

The number is 1
The number is 2
The number is 3

Page 13 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

The number is 4
The number is 5

The for Statement

The for statement is used when you know how many times you want to execute a statement or a
list of statements. (If Fixed times you want to do something then using this for loop).

Syntax

for (initialization; condition; increment)


{
code to be executed;
}

Note: The for statement has three parameters. The first parameter initializes variables, the
second parameter holds the condition, and the third parameter contains the increments required
to implement the loop. If more than one variable is included in the initialization or the increment
parameter, they should be separated by commas. The condition must evaluate to true or false.

Example
The following example prints the text "Hello World!" five times:

<html>
<body>

<?php
for ($i=1; $i<=5; $i++)
{
echo "Hello World!<br />";
}
?>

</body>
</html>

Output

Hello World!

Hello World!

Hello World!

Hello World!

Hello World!

Page 14 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

The foreach Statement


The foreach statement is used to loop through arrays.

For every loop, the value of the current array element is assigned to $value (and the array pointer
is moved by one) - so on the next loop, you'll be looking at the next element.

Syntax

foreach (array as value)


{
code to be executed;
}

Example
The following example demonstrates a loop that will print the values of the given array:

<html>
<body>

<?php
$arr=array("one", "two", "three");

foreach ($arr as $value)


{
echo "Value: " . $value . "<br />";
}
?>

</body>
</html>

Output

Value: one

Value: two

Value: three

Create a PHP User Defined Function


A function is a block of code that can be executed whenever we need it.

Creating PHP functions:

 All functions start with the word "function()"


 Name the function - It should be possible to understand what the function does by its
name. The name can start with a letter or underscore (not a number)

Page 15 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

 Add a "{" - The function code starts after the opening curly brace
 Insert the function code
 Add a "}" - The function is finished by a closing curly brace

Example
A simple function that writes my name when it is called:

<html>
<body>

<?php
function writeMyName()
{
echo "Kai Jim Ram";
}

writeMyName();
?>

</body>
</html>

Output

Kai Jim Ram

PHP Functions - Adding parameters


Our first function (writeMyName()) is a very simple function. It only writes a static string.

To add more functionality to a function, we can add parameters. A parameter is just like a
variable.

You may have noticed the parentheses after the function name, like: writeMyName(). The
parameters are specified inside the parentheses.

Example 1
The following example will write different first names, but the same last name:

<html>
<body>

<?php
function writeMyName($fname)
{
echo $fname . " Refsnes.<br />";
}

echo "My name is ";

Page 16 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

writeMyName("Kai Jim");

echo "My name is ";


writeMyName("Hege");

echo "My name is ";


writeMyName("Stale");
?>

</body>
</html>

Output

My name is Kai Jim Refsnes.


My name is Hege Refsnes.
My name is Stale Refsnes.

PHP Functions - Return values


Functions can also be used to return values.

Example
<html>
<body>
<?php
function add($x,$y)
{
$total = $x + $y;
return $total;
}

echo "1 + 16 = " . add(1,16);


?>

</body>
</html>

Output

1 + 16 = 17

PHP Form Handling


The most important thing to notice when dealing with HTML forms and PHP is that any form
element in an HTML page will automatically be available to your PHP scripts.
Form example:
<html>
<body>

<form action="welcome.php" method="post">

Page 17 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

Name: <input type="text" name="name" />


Age: <input type="text" name="age" />
<input type="submit" />

</form>

</body>
</html>

The example HTML page above contains two input fields and a submit button. When the user fills
in this form and click on the submit button, the form data is sent to the "welcome.php" file.

The "welcome.php" file looks like this:

<html>
<body>

Welcome <?php echo $_POST["name"]; ?>.<br />


You are <?php echo $_POST["age"]; ?> years old.

</body>
</html>

Output

Welcome John.
You are 28 years old.

The $_GET Variable


The $_GET variable is an array of variable names and values sent by the HTTP GET method.

The $_GET variable is used to collect values from a form with method="get". Information sent
from a form with the GET method is visible to everyone (it will be displayed in the browser's
address bar) and it has limits on the amount of information to send.
Example
<form action="welcome.php" method="get">
Name: <input type="text" name="name" />
Age: <input type="text" name="age" />

Page 18 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

<input type="submit" />


</form>

When the user clicks the "Submit" button, the URL sent could look something like this:

http://localhost/php/welcome.php?name=Ram&age=24

The "welcome.php" file can now use the $_GET variable to catch the form data (notice that the
names of the form fields will automatically be the ID keys in the $_GET array):

Welcome <?php echo $_GET["name"]; ?>.<br />


You are <?php echo $_GET["age"]; ?> years old!

Output

Welcome Ram

You are 24 years old!

The $_POST Variable


The $_POST variable is an array of variable names and values sent by the HTTP POST method.

The $_POST variable is used to collect values from a form with method="post". Information sent
from a form with the POST method is invisible to others and has no limits on the amount of
information to send.

Example

<form action="welcome.php" method="post">


Enter your name: <input type="text" name="name" />
Enter your age: <input type="text" name="age" />

<input type="submit" />


</form>

When the user clicks the "Submit" button, the URL will not contain any form data, and will look
something like this:

http://localhost/php/welcome.php

Page 19 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

The "welcome.php" file can now use the $_POST variable to catch the form data (notice that the
names of the form fields will automatically be the ID keys in the $_POST array):

Welcome <?php echo $_POST["name"]; ?>.<br />


You are <?php echo $_POST["age"]; ?> years old!

Output

Welcome Ram

You are 24 years old!

PHP Date - Format the Date


The first parameter in the date() function specifies how to format the date/time. It uses letters to
represent date and time formats. Here are some of the letters that can be used:

 d - The day of the month (01-31)


 m - The current month, as a number (01-12)
 Y - The current year in four digits

Other characters, like"/", ".", or "-" can also be inserted between the letters to add
additional formatting:

<?php
echo date("Y/m/d");
echo "<br />";
echo date("Y.m.d");
echo "<br />";
echo date("Y-m-d");
?>

Output

2006/07/11
2006.07.11
2006-07-11

Display gmtdate then

gmdate("Y‖); // Full year

gmdate("H‖); // 24 hours format

gmdate("i‖); // minutes

PHP Date - Adding a Timestamp


The second parameter in the date() function specifies a timestamp. This parameter is optional. If

Page 20 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

you do not supply a timestamp, the current time will be used.

In our next example we will use the mktime() function to create a timestamp for tomorrow.

The mktime() function returns the Unix timestamp for a specified date.

Syntax

mktime(hour,minute,second,month,day,year,is_dst)

To go one day in the future we simply add one to the day argument of mktime():

<?php
$tomorrow = mktime(0,0,0,date("m"),date("d")+1,date("Y"));
echo "Tomorrow is ".date("Y/m/d", $tomorrow);
?>

Output

Tomorrow is 2006/07/12

The following characters are recognized in the format parameter string

Format Description Example Returned Values


Character
Day ------------------- -------------------
d Day of the month, 2 digits with leading 01 to 31
zeros
D A textual representation of a day, three Mon through Sun
letters
j Day of the month without leading zeros 1 to 31
l (lowercase 'L') A full textual representation of the day of Sunday through Saturday
the week
N ISO-8601 numeric representation of the 1 (for Monday) through 7 (for
day of the week (added in PHP 5.1.0) Sunday)
S English ordinal suffix for the day of the st, nd, rd or th. Works well with j
month, 2 characters
w Numeric representation of the day of the 0 (for Sunday) through 6 (for
week Saturday)
z The day of the year (starting from 0) 0 through 365
Week ------------------- -------------------
W ISO-8601 week number of year, weeks Example: 42 (the 42nd week in
starting on Monday (added in PHP 4.1.0) the year)
Month ------------------- -------------------
F A full textual representation of a month, January through December

Page 21 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

such as January or March


m Numeric representation of a month, with 01 through 12
leading zeros
M A short textual representation of a month, Jan through Dec
three letters
n Numeric representation of a month, without 1 through 12
leading zeros
t Number of days in the given month 28 through 31
Year ------------------- -------------------
L Whether it's a leap year 1 if it is a leap year, 0 otherwise.
o ISO-8601 year number. This has the same Examples: 1999 or 2003
value as Y, except that if the ISO week
number (W) belongs to the previous or
next year, that year is used instead. (added
in PHP 5.1.0)
Y A full numeric representation of a year, 4 Examples: 1999 or 2003
digits
y A two digit representation of a year Examples: 99 or 03
Time ------------------- -------------------
a Lowercase Ante meridiem and Post am or pm
meridiem
A Uppercase Ante meridiem and Post AM or PM
meridiem
B Swatch Internet time 000 through 999
g 12-hour format of an hour without leading 1 through 12
zeros
G 24-hour format of an hour without leading 0 through 23
zeros
h 12-hour format of an hour with leading 01 through 12
zeros
H 24-hour format of an hour with leading 00 through 23
zeros
i Minutes with leading zeros 00 to 59
s Seconds, with leading zeros 00 through 59
u Milliseconds (added in PHP 5.2.2) Example: 54321
Timezone ------------------- -------------------
e Timezone identifier (added in PHP 5.1.0) Examples: UTC, GMT,
Atlantic/Azores
I (capital i) Whether or not the date is in daylight 1 if Daylight Saving Time, 0
saving time otherwise.
O Difference to Greenwich time (GMT) in Example: +0200

Page 22 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

hours
P Difference to Greenwich time (GMT) with Example: +02:00
colon between hours and minutes (added in
PHP 5.1.3)
T Timezone abbreviation Examples: EST, MDT ...
Z Timezone offset in seconds. The offset for -43200 through 50400
timezones west of UTC is always negative,
and for those east of UTC is always
positive.
Full Date/Time ------------------- -------------------
c ISO 8601 date (added in PHP 5) 2004-02-12T15:19:21+00:00
r » RFC 2822 formatted date Example: Thu, 21 Dec 2000
16:01:07 +0200
U Seconds since the Unix Epoch (January 1 See also time()
1970 00:00:00 GMT)

The include() Function


The include() function takes all the text in a specified file and copies it into the file that uses the
include function.

Example 1
Assume that you have a standard header file, called "header.php". To include the header file in a
page, use the include() function, like this:

<html>
<body>

<?php include("header.php"); ?>

<h1>Welcome to my home page</h1>

<p>Some text</p>

</body>
</html>

Example 2

Now, let's assume we have a standard menu file that should be used on all pages (include files
usually have a ".php" extension). Look at the "menu.php" file below:

<html>
<body>

Page 23 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

<a href="http://www.w3schools.com/default.php">Home</a> |
<a href="http://www.w3schools.com/about.php">About Us</a> |
<a href="http://www.w3schools.com/contact.php">Contact Us</a>

The three files, "default.php", "about.php", and "contact.php" should all include the "menu.php"
file. Here is the code in "default.php":

<?php include("menu.php"); ?>

<h1>Welcome to my home page</h1>

<p>Some text</p>

</body>
</html>

If you look at the source code of the "default.php" in a browser, it will look something like this:

<html>
<body>

<a href="default.php">Home</a> |
<a href="about.php">About Us</a> |
<a href="contact.php">Contact Us</a>
<h1>Welcome to my home page</h1>
<p>Some text</p>
</body>
</html>

And, of course, we would have to do the same thing for "about.php" and "contact.php". By using
include files, you simply have to update the text in the "menu.php" file if you decide to rename or
change the order of the links or add another web page to the site.

The require() Function


The require() function is identical to include(), except that it handles errors differently.

The include() function generates a warning (but the script will continue execution) while the
require() function generates a fatal error (and the script execution will stop after the error).

If you include a file with the include() function and an error occurs, you might get an error
message like the one below.

PHP code:

<html>
<body>

<?php
include("wrongFile.php");

Page 24 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

echo "Hello World!";


?>

</body>
</html>

Error message:

Warning: include(wrongFile.php) [function.include]:


failed to open stream:

No such file or directory in C:\home\website\test.php on line 5

Warning: include() [function.include]:


Failed opening 'wrongFile.php' for inclusion
(include_path='.;C:\php5\pear')
in C:\home\website\test.php on line 5

Hello World!

Notice that the echo statement is still executed! This is because a Warning does not stop the script
execution.

Now, let's run the same example with the require() function.

PHP code:

<html>
<body>

<?php
require("wrongFile.php");
echo "Hello World!";
?>

</body>
</html>

Error message:

Warning: require(wrongFile.php) [function.require]:


failed to open stream:
No such file or directory in C:\home\website\test.php on line 5

Fatal error: require() [function.require]:


Failed opening required 'wrongFile.php'
(include_path='.;C:\php5\pear')
in C:\home\website\test.php on line 5

The echo statement was not executed because the script execution stopped after the fatal error.

Page 25 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

It is recommended to use the require() function instead of include(), because scripts should not
continue executing if files are missing or misnamed.

Opening a File
The fopen() function is used to open files in PHP.

The first parameter of this function contains the name of the file to be opened and the second
parameter specifies in which mode the file should be opened:

<html>
<body>

<?php
$file=fopen("welcome.txt","r") or exit("Unable to open file!");
?>

</body>
</html>

The file may be opened in one of the following modes:

Closing a File
The fclose() function is used to close an open file:

<?php
$file = fopen("test.txt","r");

//some code to be executed

fclose($file);

Page 26 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

?>

Check End-of-file

The feof() function checks if the "end-of-file" (EOF) has been reached.

The feof() function is useful for looping through data of unknown length.

Note: You cannot read from files opened in w, a, and x mode!

if (feof($file)) echo "End of file";

Reading a File Line by Line


The fgets() function is used to read a single line from a file.

Note: After a call to this function the file pointer has moved to the next line.

Example
The example below reads a file line by line, until the end of file is reached:

<?php
$file = fopen("welcome.txt", "r") or exit("Unable to open file!");
//Output a line of the file until the end is reached
while(!feof($file))
{
echo fgets($file). "<br />";
}
fclose($file);
?>

Reading a File Character by Character


The fgetc() function is used to read a single character from a file.

Note: After a call to this function the file pointer moves to the next character.

Example
The example below reads a file character by character, until the end of file is reached:

<?php
$file=fopen("welcome.txt","r") or exit("Unable to open file!");
while (!feof($file))
{
echo fgetc($file);
}
fclose($file);

Page 27 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

?>

Create an Upload-File Form


To allow users to upload files from a form can be very useful.

Look at the following HTML form for uploading files:

<html>
<body>

<form action="upload_file.php" method="post"


enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>

</body>
</html>

Notice the following about the HTML form above:

 The enctype attribute of the <form> tag specifies which content-type to use when
submitting the form. "multipart/form-data" is used when a form requires binary data, like
the contents of a file, to be uploaded
 The type="file" attribute of the <input> tag specifies that the input should be processed as
a file. For example, when viewed in a browser, there will be a browse-button next to the
input field

Note: Allowing users to upload files is a big security risk. Only permit trusted users to perform file
uploads.

Page 28 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

Create The Upload Script


The "upload_file.php" file contains the code for uploading a file:

<?php
if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br />";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br />";
echo "Type: " . $_FILES["file"]["type"] . "<br />";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
echo "Stored in: " . $_FILES["file"]["tmp_name"];
move_uploaded_file($_FILES["file"]["tmp_name"],"upload/" . $_FILES["file"]["name"]);
}
?>

Some Sample file types

$_FILES["file"]["type"] = "image/gif"
$_FILES["file"]["type"] = "image/jpeg"
$_FILES["file"]["type"] = "image/pjpeg"

What is a Cookie?
A cookie is often used to identify a user. A cookie is a small file that the server embeds on the
user's computer. Each time the same computer requests a page with a browser, it will send the
cookie too. With PHP, you can both create and retrieve cookie values.

How to Create a Cookie?


The setcookie() function is used to set a cookie.

Note: The setcookie() function must appear BEFORE the <html> tag.

Syntax

setcookie(name, value, expire, path, domain);

Example
In the example below, we will create a cookie named "user" and assign the value "Alex Porter" to
it. We also specify that the cookie should expire after one hour:

<?php
setcookie("user", "Alex Porter", time()+3600);
?>

Page 29 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

<html>
<body>

</body>
</html>

Note: The value of the cookie is automatically URLencoded when sending the cookie, and
automatically decoded when received (to prevent URLencoding, use setrawcookie() instead).

How to Retrieve a Cookie Value?


The PHP $_COOKIE variable is used to retrieve a cookie value.

In the example below, we retrieve the value of the cookie named "user" and display it on a page:

<?php
// Print a cookie
echo $_COOKIE["user"];

// A way to view all cookies


print_r($_COOKIE);
?>

In the following example we use the isset() function to find out if a cookie has been set:

<html>
<body>

<?php
if (isset($_COOKIE["user"]))
echo "Welcome " . $_COOKIE["user"] . "!<br />";
else
echo "Welcome guest!<br />";
?>

</body>
</html>

How to Delete a Cookie?


When deleting a cookie you should assure that the expiration date is in the past.

Delete example:

<?php
// set the expiration date to one hour ago
setcookie("user", "", time()-3600);
?>

Page 30 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

PHP Session Variables


When you are working with an application, you open it, do some changes and then you close it.
This is much like a Session. The computer knows who you are. It knows when you start the
application and when you end. But on the internet there is one problem: the web server does not
know who you are and what you do because the HTTP address doesn't maintain state.

A PHP session solves this problem by allowing you to store user information on the server for later
use (i.e. username, shopping items, etc). However, session information is temporary and will be
deleted after the user has left the website. If you need a permanent storage you may want to
store the data in a database.

Sessions work by creating a unique id (UID) for each visitor and store variables based on this UID.
The UID is either stored in a cookie or is propagated in the URL.

Starting a PHP Session


Before you can store user information in your PHP session, you must first start up the session.

Note: The session_start() function must appear BEFORE the <html> tag:

<?php session_start(); ?>

<html>
<body>

</body>
</html>

Storing a Session Variable


The correct way to store and retrieve session variables is to use the PHP $_SESSION variable:

<?php
session_start();
// store session data
$_SESSION['views']=1;
?>

<html>
<body>

<?php
//retrieve session data
echo "Pageviews=". $_SESSION['views'];
?>

</body>
</html>

Page 31 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

Output:

Pageviews=1

Destroying a Session
If you wish to delete some session data, you can use the unset() or the session_destroy()
function.

The unset() function is used to free the specified session variable:

<?php
unset($_SESSION['views']);
?>

You can also completely destroy the session by calling the session_destroy() function:

<?php
session_destroy();
?>

Note: session_destroy() will reset your session and you will lose all your stored session data.

The PHP mail() Function


The PHP mail() function is used to send emails from inside a script.

Syntax

mail(to,subject,message,headers,parameters)

Page 32 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

PHP Simple E-Mail


The simplest way to send an email with PHP is to send a text email.

In the example below we first declare the variables ($to, $subject, $message, $from, $headers),
then we use the variables in the mail() function to send an e-mail:

<?php

$to = "[email protected]";
$subject = "Test mail";
$message = "Hello! This is a simple email message.";
$from = "[email protected]";
$headers = "From: $from";
mail($to,$subject,$message,$headers);
echo "Mail Sent.";

?>

PHP Mail Form


With PHP, you can create a feedback-form on your website. The example below sends a text
message to a specified e-mail address:

<html>
<body>

<?php
if (isset($_REQUEST['email']))
//if "email" is filled out, send email
{
//send email
$email = $_REQUEST['email'] ;
$subject = $_REQUEST['subject'] ;
$message = $_REQUEST['message'] ;
mail( "[email protected]", "Subject: $subject",
$message, "From: $email" );
echo "Thank you for using our mail form";
}
else
//if "email" is not filled out, display the form
{
echo "<form method='post' action='mailform.php'>
Email: <input name='email' type='text' /><br />
Subject: <input name='subject' type='text' /><br />
Message:<br />
<textarea name='message' rows='5' cols='20'>
</textarea><br />
<input type='submit' />

Page 33 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

</form>";
}
?>

</body>
</html>

Trigger an Error
In a script where users can input data it is useful to trigger errors when an illegal input occurs. In
PHP, this is done by the trigger_error() function.

Example
In this example an error occurs if the "test" variable is bigger than "1":

<?php
$test=2;
if ($test>1)
{
trigger_error("Value must be 1 or below");
}
?>

The output of the code above should be something like this:

Notice: Value must be 1 or below


in C:\webfolder\test.php on line 6

An error can be triggered anywhere you wish in a script, and by adding a second parameter, you
can specify what error level is triggered.

Page 34 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

Possible error types:

 E_USER_ERROR - Fatal user-generated run-time error. Errors that can not be recovered
from. Execution of the script is halted
 E_USER_WARNING - Non-fatal user-generated run-time warning. Execution of the script is
not halted
 E_USER_NOTICE - Default. User-generated run-time notice. The script found something
that might be an error, but could also happen when running a script normally

Example
In this example an E_USER_WARNING occurs if the "test" variable is bigger than "1". If an
E_USER_WARNING occurs we will use our custom error handler and end the script:

<?php
//error handler function
function customError($errno, $errstr)
{
echo "<b>Error:</b> [$errno] $errstr<br />";
echo "Ending Script";
die();
}

//set error handler


set_error_handler("customError",E_USER_WARNING);

//trigger error
$test=2;
if ($test>1)
{
trigger_error("Value must be 1 or below",E_USER_WARNING);
}
?>

The output of the code above should be something like this:

Error: [512] Value must be 1 or below


Ending Script

Error Logging
By default, PHP sends an error log to the servers logging system or a file, depending on how the
error_log configuration is set in the php.ini file. By using the error_log() function you can send
error logs to a specified file or a remote destination.

Sending errors messages to yourself by e-mail can be a good way of getting notified of specific
errors.

Page 35 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

Send an Error Message by E-Mail


In the example below we will send an e-mail with an error message and end the script, if a
specific error occurs:

<?php
//error handler function
function customError($errno, $errstr)
{
echo "<b>Error:</b> [$errno] $errstr<br />";
echo "Webmaster has been notified";
error_log("Error: [$errno] $errstr",1,
"[email protected]","From: [email protected]");
}

//set error handler


set_error_handler("customError",E_USER_WARNING);

//trigger error
$test=2;
if ($test>1)
{
trigger_error("Value must be 1 or below",E_USER_WARNING);
}
?>

The output of the code above should be something like this:

Error: [512] Value must be 1 or below


Webmaster has been notified

And the mail received from the code above looks like this:

Error: [512] Value must be 1 or below

This should not be used with all errors. Regular errors should be logged on the server using the
default PHP logging system.

What is an Exception
With PHP 5 came a new object oriented way of dealing with errors.

Exception handling is used to change the normal flow of the code execution if a specified error
(exceptional) condition occurs. This condition is called an exception.

This is what normally happens when an exception is triggered:

 The current code state is saved


 The code execution will switch to a predefined (custom) exception handler function

Page 36 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

 Depending on the situation, the handler may then resume the execution from the saved
code state, terminate the script execution or continue the script from a different location in
the code

We will show different error handling methods:

 Basic use of Exceptions


 Creating a custom exception handler
 Multiple exceptions
 Re-throwing an exception
 Setting a top level exception handler

Note: Exceptions should only be used with error conditions, and should not be used to jump to
another place in the code at a specified point.

Basic Use of Exceptions


When an exception is thrown, the code following it will not be executed, and PHP will try to find
the matching "catch" block.

If an exception is not caught, a fatal error will be issued with an "Uncaught Exception" message.

Lets try to throw an exception without catching it:

<?php
//create function with an exception
function checkNum($number)
{
if($number>1)
{
throw new Exception("Value must be 1 or below");
}
return true;
}

//trigger exception
checkNum(2);
?>

The code above will get an error like this:

Fatal error: Uncaught exception 'Exception'


with message 'Value must be 1 or below' in C:\webfolder\test.php:6
Stack trace: #0 C:\webfolder\test.php(12):
checkNum(28) #1 {main} thrown in C:\webfolder\test.php on line 6

Try, throw and catch


To avoid the error from the example above, we need to create the proper code to handle an
exception.

Page 37 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

Proper exception code should include:

1. Try - A function using an exception should be in a "try" block. If the exception does not
trigger, the code will continue as normal. However if the exception triggers, an exception is
"thrown"
2. Throw - This is how you trigger an exception. Each "throw" must have at least one "catch"
3. Catch - A "catch" block retrieves an exception and creates an object containing the
exception information

Lets try to trigger an exception with valid code:

<?php
//create function with an exception
function checkNum($number)
{
if($number>1)
{
throw new Exception("Value must be 1 or below");
}
return true;
}

//trigger exception in a "try" block


try
{
checkNum(2);
//If the exception is thrown, this text will not be shown
echo 'If you see this, the number is 1 or below';
}

//catch exception
catch(Exception $e)
{
echo 'Message: ' .$e->getMessage();
}
?>

The code above will get an error like this:

Message: Value must be 1 or below

Example explained:
The code above throws an exception and catches it:

1. The checkNum() function is created. It checks if a number is greater than 1. If it is, an


exception is thrown
2. The checkNum() function is called in a "try" block
3. The exception within the checkNum() function is thrown
4. The "catch" block retrives the exception and creates an object ($e) containing the
exception information

Page 38 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

5. The error message from the exception is echoed by calling $e->getMessage() from the
exception object

However, one way to get around the "every throw must have a catch" rule is to set a top level
exception handler to handle errors that slip through.

Creating a Custom Exception Class


Creating a custom exception handler is quite simple. We simply create a special class with
functions that can be called when an exception occurs in PHP. The class must be an extension of
the exception class.

The custom exception class inherits the properties from PHP's exception class and you can add
custom functions to it.

Lets create an exception class:

<?php
class customException extends Exception
{
public function errorMessage()
{
//error message
$errorMsg = 'Error on line '.$this->getLine().' in '.$this->getFile()
.': <b>'.$this->getMessage().'</b> is not a valid E-Mail address';
return $errorMsg;
}
}

$email = "[email protected]";

try
{
//check if
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE)
{
//throw exception if email is not valid
throw new customException($email);
}
}

catch (customException $e)


{
//display custom message
echo $e->errorMessage();
}
?>

The new class is a copy of the old exception class with an addition of the errorMessage() function.
Since it is a copy of the old class, and it inherits the properties and methods from the old class,
we can use the exception class methods like getLine() and getFile() and getMessage().

Page 39 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

Example explained:
The code above throws an exception and catches it with a custom exception class:

1. The customException() class is created as an extension of the old exception class. This way
it inherits all methods and properties from the old exception class
2. The errorMessage() function is created. This function returns an error message if an e-mail
address is invalid
3. The $email variable is set to a string that is not a valid e-mail address
4. The "try" block is executed and an exception is thrown since the e-mail address is invalid
5. The "catch" block catches the exception and displays the error message

Multiple Exceptions
It is possible for a script to use multiple exceptions to check for multiple conditions.

It is possible to use several if..else blocks, a switch, or nest multiple exceptions. These exceptions
can use different exception classes and return different error messages:

<?php
class customException extends Exception
{
public function errorMessage()
{
//error message
$errorMsg = 'Error on line '.$this->getLine().' in '.$this->getFile()
.': <b>'.$this->getMessage().'</b> is not a valid E-Mail address';
return $errorMsg;
}
}

$email = "[email protected]";

try
{
//check if
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE)
{
//throw exception if email is not valid
throw new customException($email);
}
//check for "example" in mail address
if(strpos($email, "example") !== FALSE)
{
throw new Exception("$email is an example e-mail");
}
}

catch (customException $e)


{
echo $e->errorMessage();
}

Page 40 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

catch(Exception $e)
{
echo $e->getMessage();
}
?>

Example explained:
The code above tests two conditions and throws an exception if any of the conditions are not met:

1. The customException() class is created as an extension of the old exception class. This way
it inherits all methods and properties from the old exception class
2. The errorMessage() function is created. This function returns an error message if an e-mail
address is invalid
3. The $email variable is set to a string that is a valid e-mail address, but contains the string
"example"
4. The "try" block is executed and an exception is not thrown on the first condition
5. The second condition triggers an exception since the e-mail contains the string "example"
6. The "catch" block catches the exception and displays the correct error message

If there was no customException catch, only the base exception catch, the exception would be
handled there

Set a Top Level Exception Handler


The set_exception_handler() function sets a user-defined function to handle all uncaught
exceptions.

<?php
function myException($exception)
{
echo "<b>Exception:</b> " , $exception->getMessage();
}

set_exception_handler('myException');

throw new Exception('Uncaught Exception occurred');


?>

The output of the code above should be something like this:

Exception: Uncaught Exception occurred

In the code above there was no "catch" block. Instead, the top level exception handler triggered.
This function should be used to catch uncaught exceptions.

Rules for exceptions


 Code may be surrounded in a try block, to help catch potential exceptions

Page 41 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

 Each try block or "throw" must have at least one corresponding catch block
 Multiple catch blocks can be used to catch different classes of exceptions
 Exceptions can be thrown (or re-thrown) in a catch block within a try block

A simple rule: If you throw something, you have to catch it.

Functions and Filters


To filter a variable, use one of the following filter functions:

 filter_var() - Filters a single variable with a specified filter


 filter_var_array() - Filter several variables with the same or different filters
 filter_input - Get one input variable and filter it
 filter_input_array - Get several input variables and filter them with the same or different
filters

In the example below, we validate an integer using the filter_var() function:

<?php
$int = 123;

if(!filter_var($int, FILTER_VALIDATE_INT))
{
echo("Integer is not valid");
}
else
{
echo("Integer is valid");
}
?>

Get Other Country Time

The below function is used to show your desired time (This function is used for find
other country times)

<?php

function ShowSwedenTime()

$hour = gmdate("H");

$minute = gmdate("i");

$seconds = gmdate("s");

Page 42 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

$day = gmdate("d");

$month = gmdate("m");

$year = gmdate("Y");

// This is the offset from the server time to Sweden time.

$hour = $hour - 7;

$minute = $minute + 1;

$seconds = $seconds + 45;

return date("Y-m-d H:i:s", mktime ($hour,$minute,$seconds,$month,$day,$year));

?>

Image Handling (Using GD Library)

The below program is used to get a widht and height in a given file.

<?php

$source = ―c:\sample\sample.jpg‖;

list($width, $height) = getimagesize($source);

echo $width."<br>";

echo $height;

?>

Resizing and create another image file

<?php

$imagepath = "c:\sample\sample.jpg";

$save = "Rename_".$imagepath; //This is the new file you saving

$file = $imagepath; //This is the original file

list($width, $height) = getimagesize($file) ;

$modwidth = 280;

Page 43 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

$diff = $width / $modwidth;

$modheight = 200;

$tn = imagecreatetruecolor($modwidth, $modheight) ;

if($imagename1[1] == "jpeg" || $imagename1[1] == "jpg")

$image = imagecreatefromjpeg($file) ;

if($imagename1[1] == "png")

$image = imagecreatefrompng($file) ;

if($imagename1[1] == "gif")

$image = imagecreatefromgif($file) ;

imagecopyresampled($tn, $image, 0, 0, 0, 0, $modwidth, $modheight, $width, $height) ;

$uploadfile1_1 = substr($save,3,strlen($save));

if($imagename1[1] == "jpeg" || $imagename1[1] == "jpg")

imagejpeg($tn, $save, 100) ;

if($imagename1[1] == "png")

imagepng($tn, $save) ;

Page 44 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

if($imagename1[1] == "gif")

imagegif($tn, $save) ;

?>

Find a word in a static paragraph

<?php

$staticpara = "PHP is a powerful server-side scripting language for creating dynamic and
interactive websites. PHP is the widely-used, free, and efficient alternative to competitors such as
Microsoft's ASP. PHP is perfectly suited for Web development and can be embedded directly into
the HTML code. The PHP syntax is very similar to Perl and C. PHP is often used together with
Apache (web server) on various operating systems. It also supports ISAPI and can be used with
Microsoft's IIS on Windows.";

$staticparaexplode = explode(" ",$staticpara);

foreach($staticparaexplode as $val)

if($val == "ISAPI")

$msg = "Find over";

break;

else

$msg = "The word ISAPI is not found";

echo $msg;

Page 45 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

?>

Find a word (similar to "like" keyword in SQL)in a static paragraph

<?php

$staticpara = "PHP is a powerful server-side scripting language for creating dynamic and
interactive websites. PHP is the widely-used, free, and efficient alternative to competitors such as
Microsoft's ASP. PHP is perfectly suited for Web development and can be embedded directly into
the HTML code. The PHP syntax is very similar to Perl and C. PHP is often used together with
Apache (web server) on various operating systems. It also supports ISAPI and can be used with
Microsoft's IIS on Windows.";

$staticparaexplode = explode(" ",$staticpara);

foreach($staticparaexplode as $val)

if(substr($val,0,5) == "Micro")

$msg = "Find over";

break;

else

$msg = "The word ISAPI is not found";

echo $msg;

?>

Array with Combo box selecting checking

<select name="status">

Page 46 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

<?

$a=array("one","two","three","four","five");

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

if($a[$i]=="four")

?>

<option value=<?=$a[$i];?> selected="selected"><?=$a[$i];?></option>

<? } else { ?>

<option value=<?=$a[$i];?>><?=$a[$i];?></option>

<? }

}?>

</select>

Increase controls dynamically

<table>

<tr><td ColSpan=2>File attachments:

<DIV ID=files>

Attachment 1 : <input type="file" name="File 1" size="20">

</DIV>

<INPUT Type=button Value="Add a file" OnClick=return(Expand())

Style="BORDER-RIGHT: 0px; BORDER-TOP: 0px; BACKGROUND: yellow; BORDER-LEFT: 0px;


CURSOR: hand; BORDER-BOTTOM: 0px">

</td></tr>

</table>

Page 47 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

<SCRIPT>

var nfiles = 1;

function Expand(){

nfiles++

var adh = '<BR> Attachment '+nfiles+' : <input type="file" name="File '+nfiles+'">';

files.insertAdjacentHTML('BeforeEnd',adh);

return false;

};

</script>

Validation
Checkbox Validation

<input type=‖checkbox‖ name="chk[]" value="values form dbase or array‖>

<?php

function valid()

var chks = document.getElementsByName('chk[]');

var hasChecked = false;

for (var i=0;i<chks.length;i++)

if (chks[i].checked)

hasChecked = true;

var confrm;

Page 48 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

confrm=confirm("Are you sure that you want to delete this posting");

return confrm;

break;

if (!hasChecked)

alert("Please select at least one.");

chks[0].focus();

return false;

?>

Characters and numerical validation

<input name="price" type="text" id="price" style="text-align:right" onBlur="priceclear();"


onKeyPress="return numbersonly(event);" maxlength="6">

<script>

function charonly(e)

var unicode=e.charCode? e.charCode : e.keyCode

if (unicode<97 || unicode>122 || unicode==32)

if((unicode<65 && unicode!=32) || unicode>90)


//if not a char

Page 49 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

return false
//disable key press

function numbersonly(e){

var unicode=e.charCode? e.charCode : e.keyCode

if (unicode!=8){ //if the key isn't the backspace key (which we should allow)

if (unicode<48||unicode>57) //if not a number

return false //disable key press

</script>

URL Validation

PHP

<?php

function isValidURL($url)

return preg_match('|^http(s)?://[a-z0-9-]+(\.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $url);

?>

Sample Usage:

Highlight: PHP

<?php

Page 50 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

$url = 'http://www.phpriot.com';

if (isValidURL($url)) {

echo 'Your URL is valid';

else {

echo 'Your URL is invalid';

?>

Javascript

<html>

<head>

<script>

function checkUrl(theUrl){

if(theUrl.value.match(/^(http|ftp)\:\/\/\w+([\.\-]\w+)*\.\w{2,4}(\:\d+)*([\/\.\-
\?\&\%\#]\w+)*\/?$/i) ||

theUrl.value.match(/^mailto\:\w+([\.\-]\w+)*\@\w+([\.\-]\w+)*\.\w{2,4}$/i)){

return true;

} else {

alert("Wrong address.");

theUrl.select();

theUrl.focus();

return false;

</script>

Page 51 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

</head>

</body>

<form onSubmit="return checkUrl(this.URL)">

URL:

<input type=text name="URL" size="45">

<input type=submit value="Save">

</form>

</body>

</html>

IP Address Validation

<script language=‖javascript‖>

function verifyIP (IPvalue)

errorString = "";

theName = "IPaddress";

var ipPattern = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;

var ipArray = IPvalue.match(ipPattern);

if (IPvalue == "0.0.0.0")

errorString = errorString + theName + ': '+IPvalue+' is a special IP address and cannot be


used here.';

else if (IPvalue == "255.255.255.255")

errorString = errorString + theName + ': '+IPvalue+' is a special IP address and cannot be


used here.';

Page 52 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

if (ipArray == null)

errorString = errorString + theName + ': '+IPvalue+' is not a valid IP address.';

else {

for (i = 0; i < 4; i++) {

thisSegment = ipArray[i];

if (thisSegment > 255) {

errorString = errorString + theName + ': '+IPvalue+' is not a valid IP address.';

i = 4;

if ((i == 0) && (thisSegment > 255)) {

errorString = errorString + theName + ': '+IPvalue+' is a special IP address and cannot be


used here.';

i = 4;

extensionLength = 3;

if (errorString == "")

globalchk = 1;

else

alert (errorString);

globalchk = 0;

Page 53 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

</script>

Get random numbers

<?php

echo rand(0,2100000); // rand(starting value, ending value)

?>

New line (\n) to Break (<br>)

Syntax

nl2br(string)

Example

<?php
$a = ―Sample \n Text‖;
echo nl2br($a);
?>

Ouput

Sample
Text

String Replace

Syntax

str_replace("Mixed Search","Mixed Replace","Mixed Subject");

Example

<?php
$a = "PHP is a one of the good webdevelopment software‖;
echo str_replace("good","best",$a);
?>

Simple Class Programs

<?php
class printname
{
function displayname()

Page 54 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

{
echo "AJSquare Inc";
}
}
$obj = new printname;
$obj->displayname();
?>

Output
AJSquare Inc

MYSQL

What is MySQL?
MySQL is a database. A database defines a structure for storing information.

In a database, there are tables. Just like HTML tables, database tables contain rows, columns, and
cells.

Databases are useful when storing information categorically. A company may have a database
with the following tables: "Employees", "Products", "Customers" and "Orders".

Connecting to a MySQL Database


Before you can access and work with data in a database, you must create a connection to the
database.

In PHP, this is done with the mysql_connect() function.

Syntax

mysql_connect(servername,username,password);

Example
In the following example we store the connection in a variable ($con) for later use in the script.
The "die" part will be executed if the connection fails:

<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}

// some code

Page 55 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

?>

Closing a Connection
The connection will be closed as soon as the script ends. To close the connection before, use the
mysql_close() function.

<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}

// some code

mysql_close($con);
?>

Create a Database
The CREATE DATABASE statement is used to create a database in MySQL.

Syntax

CREATE DATABASE database_name

Example
In the following example we create a database called "my_db":

<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}

if (mysql_query("CREATE DATABASE my_db",$con))


{
echo "Database created";
}
else
{
echo "Error creating database: " . mysql_error();
}

mysql_close($con);
?>

Page 56 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

Create a Table
The CREATE TABLE statement is used to create a database table in MySQL.

Syntax

CREATE TABLE table_name


(
column_name1 data_type,
column_name2 data_type,
column_name3 data_type,
.......
)

Example
The following example shows how you can create a table named "person", with three columns.
The column names will be "FirstName", "LastName" and "Age":

<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}

// Create database
if (mysql_query("CREATE DATABASE my_db",$con))
{
echo "Database created";
}
else
{
echo "Error creating database: " . mysql_error();
}

// Create table in my_db database


mysql_select_db("my_db", $con);
$sql = "CREATE TABLE person
(
FirstName varchar(15),
LastName varchar(15),
Age int
)";
mysql_query($sql,$con);

mysql_close($con);
?>

Page 57 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

MySQL Data Types


Below are the different MySQL data types that can be used:

Page 58 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

Primary Keys and Auto Increment Fields

Each table should have a primary key field.

A primary key is used to uniquely identify the rows in a table. Each primary key value must be
unique within the table. Furthermore, the primary key field cannot be null because the database
engine requires a value to locate the record.

The primary key field is always indexed. There is no exception to this rule! You must index the
primary key field so the database engine can quickly locate rows based on the key's value.

The following example sets the personID field as the primary key field. The primary key field is
often an ID number, and is often used with the AUTO_INCREMENT setting. AUTO_INCREMENT
automatically increases the value of the field by 1 each time a new record is added. To ensure that
the primary key field cannot be null, we must add the NOT NULL setting to the field.

Example

<?php

$sql = "CREATE TABLE person


(
personID int NOT NULL AUTO_INCREMENT,
PRIMARY KEY(personID),
FirstName varchar(15),
LastName varchar(15),
Age int
)";

mysql_query($sql,$con);

?>

How to get a Lowest Unique value from the table

select id from (SELECT id, count(field_name)as cnt FROM table_name WHERE


field_name=particular_value group by (field_name))as t where t.cnt = 1

Page 59 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

Insert Data Into a Database Table


The INSERT INTO statement is used to add new records to a database table.

Syntax

INSERT INTO table_name


VALUES (value1, value2,....)

You can also specify the columns where you want to insert the data:

INSERT INTO table_name (column1, column2,...)


VALUES (value1, value2,....)

Note: SQL statements are not case sensitive. INSERT INTO is the same as insert into.

To get PHP to execute the statements above we must use the mysql_query() function. This
function is used to send a query or command to a MySQL connection.

Example
In the previous chapter we created a table named "Person", with three columns; "Firstname",
"Lastname" and "Age". We will use the same table in this example. The following example adds
two new records to the "Person" table:

<?php

$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}

mysql_select_db("my_db", $con);

mysql_query("INSERT INTO person (FirstName, LastName, Age)


VALUES ('Peter', 'Griffin', '35')");

mysql_query("INSERT INTO person (FirstName, LastName, Age)


VALUES ('Glenn', 'Quagmire', '33')");

mysql_close($con);
?>

Insert Data From a Form Into a Database


Now we will create an HTML form that can be used to add new records to the "Person" table.

Here is the HTML form:

Page 60 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

<html>
<body>
<form action="insert.php" method="post">
Firstname: <input type="text" name="firstname" /><br />
Lastname: <input type="text" name="lastname" /><br />
Age: <input type="text" name="age" /><br />
<input type="submit" />
</form>
</body>
</html>

When a user clicks the submit button in the HTML form in the example above, the form data is
sent to "insert.php". The "insert.php" file connects to a database, and retrieves the values from
the form with the PHP $_POST variables. Then, the mysql_query() function executes the INSERT
INTO statement, and a new record will be added to the database table.

Below is the code in the "insert.php" page:

<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}

mysql_select_db("my_db", $con);

$sql="INSERT INTO person (FirstName, LastName, Age)


VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";

if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";

Page 61 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

mysql_close($con)
?>

Select Data From a Database Table


The SELECT statement is used to select data from a database.

Syntax

SELECT column_name(s)
FROM table_name

Note: SQL statements are not case sensitive. SELECT is the same as select.

To get PHP to execute the statement above we must use the mysql_query() function.
This function is used to send a query or command to a MySQL connection.

Example
The following example selects all the data stored in the "Person" table (The * character selects all
of the data in the table):

<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}

mysql_select_db("my_db", $con);

$result = mysql_query("SELECT * FROM person");

while($row = mysql_fetch_array($result))
{
echo $row['FirstName'] . " " . $row['LastName'];
echo "<br />";
}

mysql_close($con);
?>

The example above stores the data returned by the mysql_query() function in the $result
variable. Next, we use the mysql_fetch_array() function to return the first row from the recordset
as an array. Each subsequent call to mysql_fetch_array() returns the next row in the recordset.
The while loop loops through all the records in the recordset. To print the value of each row, we
use the PHP $row variable ($row['FirstName'] and $row['LastName']).

The output of the code above will be:

Page 62 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

Peter Griffin
Glenn Quagmire

Display the Result in an HTML Table


The following example selects the same data as the example above,
but will display the data in an HTML table:

<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}

mysql_select_db("my_db", $con);

$result = mysql_query("SELECT * FROM person");

echo "<table border='1'>


<tr>
<th>Firstname</th>
<th>Lastname</th>
</tr>";

while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "</tr>";
}
echo "</table>";

mysql_close($con);
?>

The output of the code above will be:

Firstname Lastname
Glenn Quagmire
Peter Griffin

Page 63 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

PHP MySQL The Where Clause

The WHERE clause


To select only data that matches a specific criteria, add a
WHERE clause to the SELECT statement.

Syntax
SELECT column FROM table
WHERE column operator value

The following operators can be used with the WHERE clause:

Note: SQL statements are not case sensitive. WHERE is the same as where.

To get PHP to execute the statement above we must use the mysql_query() function.

This function is used to send a query or command to a MySQL connection.

Example

The following example will select all rows from the "Person" table, where FirstName='Peter'

<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}

mysql_select_db("my_db", $con);

$result = mysql_query("SELECT * FROM person


WHERE FirstName='Peter'");

while($row = mysql_fetch_array($result))
{
echo $row['FirstName'] . " " . $row['LastName'];
echo "<br />";
}

?>

The output of the code above will be:

Peter Griffin

Page 64 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

PHP MySQL Order By Keyword

The ORDER BY keyword is used to sort the data in a recordset.

The ORDER BY Keyword


The ORDER BY keyword is used to sort the data in a recordset.

Syntax

SELECT column_name(s)
FROM table_name
ORDER BY column_name

Note: SQL statements are not case sensitive. ORDER BY is the same as order by.

Example
The following example selects all the data stored in the "Person" table,
and sorts the result by the "Age" column:

<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}

mysql_select_db("my_db", $con);

$result = mysql_query("SELECT * FROM person ORDER BY age");

while($row = mysql_fetch_array($result))
{
echo $row['FirstName'];
echo " " . $row['LastName'];
echo " " . $row['Age'];
echo "<br />";
}

mysql_close($con);
?>

Page 65 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

The output of the code above will be:

Glenn Quagmire 33
Peter Griffin 35

Sort Ascending or Descending


If you use the ORDER BY keyword, the sort-order of the recordset is ascending by default
(1 before 9 and "a" before "p").

Use the DESC keyword to specify a descending sort-order (9 before 1 and "p" before "a"):

SELECT column_name(s)

FROM table_name
ORDER BY column_name DESC

Order by Two Columns

It is possible to order by more than one column. When ordering by more than one column,
the second column is only used if the values in the first column are identical:
SELECT column_name(s)

FROM table_name
ORDER BY column_name1, column_name2

Update Data In a Database

The UPDATE statement is used to modify data in a database table.

Syntax
UPDATE table_name

SET column_name = new_value


WHERE column_name = some_value

Note: SQL statements are not case sensitive. UPDATE is the same as update.

To get PHP to execute the statement above we must use the mysql_query() function.
This function is used to send a query or command to a MySQL connection.

Example
Earlier in the tutorial we created a table named "Person". Here is how it looks:
First Name
Last Name
Age
Rama

Page 66 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

Subbu
24
Ashok
Raja
25
The following example updates some data in the "Person" table:
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}

mysql_select_db("my_db", $con);

mysql_query("UPDATE Person SET Age = '25'


WHERE FirstName = 'Rama' AND LastName = 'Subbu'");

mysql_close($con);
?>

After the update, the "Person" table will look like this:

First Name Last Name Age


Rama Subbu 25
Ashok Raja 25

Delete Data In a Database

The DELETE FROM statement is used to delete records from a database table.

Syntax

DELETE FROM table_name

WHERE column_name = some_value

Note: SQL statements are not case sensitive. DELETE FROM is the same as delete from.

To get PHP to execute the statement above we must use the mysql_query() function.
This function is used to send a query or command to a MySQL connection.

Example

Earlier in the tutorial we created a table named "Person". Here is how it looks:

First Name Last Name Age


Rama Subbu 25

Page 67 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

Ashok Raja 25

The following example deletes all the records in the "Person" table where LastName='Subbu':

<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}

mysql_select_db("my_db", $con);

mysql_query("DELETE FROM Person WHERE LastName='Subbu'");

mysql_close($con);
?>

After the deletion, the table will look like this:

First Name Last Name Age

Ashok Raja 25

ODBC is an Application Programming Interface (API) that allows you to connect to a data source
(e.g. an MS Access database).

Create an ODBC Connection

With an ODBC connection, you can connect to any database, on any computer in your network,
as long as an ODBC connection is available.

Here is how to create an ODBC connection to a MS Access Database:

1. Open the Administrative Tools icon in your Control Panel.

2. Double-click on the Data Sources (ODBC) icon inside.

3. Choose the System DSN tab.

4. Click on Add in the System DSN tab.

5. Select the Microsoft Access Driver. Click Finish.

6. In the next screen, click Select to locate the database.

7. Give the database a Data Source Name (DSN).

8. Click OK.

Note that this configuration has to be done on the computer where your web site is located.

Page 68 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

If you are running Internet Information Server (IIS) on your own computer, the instructions
above will work, but if your web site is located on a remote server, you have to have physical
access to that server, or ask your web host to to set up a DSN for you to use.

Connecting to an ODBC
The odbc_connect() function is used to connect to an ODBC data source. The function takes four
parameters: the data source name, username, password, and an optional cursor type.

The odbc_exec() function is used to execute an SQL statement.

Example

The following example creates a connection to a DSN called northwind, with no username and no
password. It then creates an SQL and executes it:

$conn=odbc_connect('northwind','','');

$sql="SELECT * FROM customers";

$rs=odbc_exec($conn,$sql);

Retrieving Records

The odbc_fetch_row() function is used to return records from the result-set.


This function returns true if it is able to return rows, otherwise false.

The function takes two parameters: the ODBC result identifier and an optional row number:

odbc_fetch_row($rs)

Retrieving Fields from a Record

The odbc_result() function is used to read fields from a record. This function takes two
parameters: the ODBC result identifier and a field number or name.

The code line below returns the value of the first field from the record:

$compname=odbc_result($rs,1);

The code line below returns the value of a field called "CompanyName":

$compname=odbc_result($rs,"CompanyName");

Closing an ODBC Connection

The odbc_close() function is used to close an ODBC connection.

odbc_close($conn);

An ODBC Example

The following example shows how to first create a database connection, then a result-set, and
then display the data in an HTML table.
<html>

Page 69 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

<body>
<?php
$conn=odbc_connect('northwind','','');
if (!$conn)
{exit("Connection Failed: " . $conn);}
$sql="SELECT * FROM customers";
$rs=odbc_exec($conn,$sql);
if (!$rs)
{exit("Error in SQL");}
echo "<table><tr>";
echo "<th>Companyname</th>";
echo "<th>Contactname</th></tr>";
while (odbc_fetch_row($rs))
{
$compname=odbc_result($rs,"CompanyName");
$conname=odbc_result($rs,"ContactName");
echo "<tr><td>$compname</td>";
echo "<td>$conname</td></tr>";
}
odbc_close($conn);
echo "</table>";
?>
</body>
</html>

XML
What is XML?

XML is used to describe data and to focus on what data is. An XML file describes the structure of
the data.

In XML, no tags are predefined. You must define your own tags.

What is Expat?

To read and update - create and manipulate - an XML document, you will need an XML parser.

There are two basic types of XML parsers:

 Tree-based parser: This parser transforms an XML document into a tree structure. It
analyzes the whole document, and provides access to the tree elements. e.g. the
Document Object Model (DOM)

 Event-based parser: Views an XML document as a series of events. When a specific event
occurs, it calls a function to handle it

The Expat parser is an event-based parser.

Event-based parsers focus on the content of the XML documents, not their structure. Because of
this, event-based parsers can access data faster than tree-based parsers.

Look at the following XML fraction:

<from>Jani</from>

Page 70 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

An event-based parser reports the XML above as a series of three events:

 Start element: from

 Start CDATA section, value: Jani

 Close element: from

The XML example above contains well-formed XML. However, the example is not valid XML,
because there is no Document Type Definition (DTD) associated with it.

However, this makes no difference when using the Expat parser. Expat is a non-validating parser,
and ignores any DTDs.

As an event-based, non-validating XML parser, Expat is fast and small, and a perfect match for
PHP web applications.

Note: XML documents must be well-formed or Expat will generate an error.

An XML File

The XML file below will be used in our example:

<?xml version="1.0" encoding="ISO-8859-1"?>

<note>

<to>Tove</to>

<from>Jani</from>

<heading>Reminder</heading>

<body>Don't forget me this weekend!</body>

</note>

Initializing the XML Parser

We want to initialize the XML parser in PHP, define some handlers for different XML events, and
then parse the XML file.

Example

<?php
//Initialize the XML parser
$parser=xml_parser_create();

//Function to use at the start of an element


function start($parser,$element_name,$element_attrs)
{
switch($element_name)
{
case "NOTE":
echo "-- Note --<br />";
break;

Page 71 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

case "TO":
echo "To: ";
break;
case "FROM":
echo "From: ";
break;
case "HEADING":
echo "Heading: ";
break;
case "BODY":
echo "Message: ";
}
}

//Function to use at the end of an element


function stop($parser,$element_name)
{
echo "<br />";
}

//Function to use when finding character data


function char($parser,$data)
{
echo $data;
}

//Specify element handler


xml_set_element_handler($parser,"start","stop");

//Specify data handler


xml_set_character_data_handler($parser,"char");

//Open XML file


$fp=fopen("test.xml","r");

//Read data
while ($data=fread($fp,4096))
{
xml_parse($parser,$data,feof($fp)) or
die (sprintf("XML Error: %s at line %d",
xml_error_string(xml_get_error_code($parser)),
xml_get_current_line_number($parser)));
}

//Free the XML parser


xml_parser_free($parser);

?>

The output of the code above will be:

Page 72 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

-- Note --
To: Tove
From: Jani
Heading: Reminder
Message: Don't forget me this weekend!

How it works:
1. Initialize the XML parser with the xml_parser_create() function
2. Create functions to use with the different event handlers
3. Add the xml_set_element_handler() function to specify which function will be executed
when the parser encounters the opening and closing tags
4. Add the xml_set_character_data_handler() function to specify which function will execute
when the parser encounters character data
5. Parse the file "test.xml" with the xml_parse() function
6. In case of an error, add xml_error_string() function to convert an XML error to a textual
description
7. Call the xml_parser_free() function to release the memory allocated with the
xml_parser_create() function
What is DOM?
The W3C DOM provides a standard set of objects for HTML and XML documents, and a standard
interface for accessing and manipulating them.

The W3C DOM is separated into different parts (Core, XML, and HTML) and different levels (DOM
Level 1/2/3):

* Core DOM - defines a standard set of objects for any structured document
* XML DOM - defines a standard set of objects for XML documents
* HTML DOM - defines a standard set of objects for HTML documents
XML Parsing
To read and update - create and manipulate - an XML document, you will need an XML parser.
There are two basic types of XML parsers:
 Tree-based parser: This parser transforms an XML document into a tree structure. It
analyzes the whole document, and provides access to the tree elements
 Event-based parser: Views an XML document as a series of events. When a specific event
occurs, it calls a function to handle it

The DOM parser is an tree-based parser.

Look at the following XML document fraction:

<?xml version="1.0" encoding="ISO-8859-1"?>


<from>Jani</from>

The XML DOM sees the XML above as a tree structure:

 Level 1: XML Document


 Level 2: Root element: <from>

Page 73 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

 Level 3: Text element: "Jani"

An XML File
The XML file below will be used in our example:

<?xml version="1.0" encoding="ISO-8859-1"?>


<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

Load and Output XML


We want to initialize the XML parser, load the xml, and output it:

Example

Load and Output XML

We want to initialize the XML parser, load the xml, and output it:
Example

<?php
$xmlDoc = new DOMDocument();
$xmlDoc->load("note.xml");

print $xmlDoc->saveXML();
?>

The output of the code above will be:

Tove Jani Reminder Don't forget me this weekend!

If you select "View source" in the browser window, you will see the following HTML:

Page 74 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

<?xml version="1.0" encoding="ISO-8859-1"?>


<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

The example above creates a DOMDocument-Object and loads the XML from "note.xml" into it.

Then the saveXML() function to puts the internal XML document into a string, so that we can print
it.
Looping through XML
We want to initialize the XML parser, load the XML, and loop through all elements of the <note>
element:

Example

<?php
$xmlDoc = new DOMDocument();
$xmlDoc->load("note.xml");

$x = $xmlDoc->documentElement;
foreach ($x->childNodes AS $item)
{
print $item->nodeName . " = " . $item->nodeValue . "<br />";
}
?>

The output of the code above will be:

#text =
to = Tove
#text =
from = Jani
#text =
heading = Reminder
#text =
body = Don't forget me this weekend!
#text =

What is SimpleXML?
SimpleXML is new in PHP 5. It is an easy way of getting an element's attributes and text, if you

Page 75 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

know the XML document's layout.

Compared to DOM or the Expat parser, SimpleXML just takes a few lines of code to read text data
from an element.

SimpleXML converts the XML document into an object, like this:

 Elements - Are converted to single attributes of the SimpleXMLElement object. When


there's more than one element on one level, they're placed inside an array
 Attributes - Are accessed using associative arrays, where an index corresponds to the
attribute name
 Element Data - Text data from elements are converted to strings. If an element has more
than one text node, they will be arranged in the order they are found

SimpleXML is fast and easy to use when performing basic tasks like:

 Reading XML files


 Extracting data from XML strings
 Editing text nodes or attributes

However, when dealing with advanced XML, like namespaces, you are better off using the Expat
parser or the XML DOM.

Using SimpleXML
Below is an XML file:

<?xml version="1.0" encoding="ISO-8859-1"?>


<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

We want to output the element names and data from the XML file above.

Here's what to do:

1. Load the XML file


2. Get the name of the first element
3. Create a loop that will trigger on each child node, using the children() function
4. Output the element name and data for each child node

Example

<?php
$xml = simplexml_load_file("test.xml");

Page 76 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

echo $xml->getName() . "<br />";

foreach($xml->children() as $child)
{
echo $child->getName() . ": " . $child . "<br />";
}
?>

The output of the code above will be:

note
to: Tove
from: Jani
heading: Reminder
body: Don't forget me this weekend!

XML - PHP Parsing Programs


Accessing XML Node wise

Create XML Node:


test.xml
<?xml version="1.0" encoding="iso-8859-1"?>
<people>
<person>
<first_name>Ram</first_name>
<last_name>Subbu</last_name>
</person>
</people>

createxmlnode.php - (Simple XML Object Method)


<?php
$xml = simplexml_load_file("test.xml"); //This line will load the XML file.
$sxe = new SimpleXMLElement($xml->asXML()); //In this line it create a SimpleXMLElement
object with the source of the XML file.
//The following lines will add a new child and others child inside the previous child created.
$person = $sxe->addChild("person");
$person->addChild("first_name", "Nambi");
$person->addChild("last_name", "Kumar");
//This next line will overwrite the original XML file with new data added
$sxe->asXML("test1.xml");
?>

Page 77 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

Edit XML Node:


replacexmlnode.php - (DOM XML Object Method)
<?php
$dom = new DOMDocument();
$dom->load('test.xml');
$xpath = new DOMXPath($dom);
$firstname = $xpath->query('person/first_name');
$lastname = $xpath->query('person/last_name');
foreach($firstname as $fname)
{
if($fname->nodeValue == "Ram")
{
foreach($lastname as $lname)
{
$ln = $lname->nodeValue;
$lname->nodeValue = "Kumar";
}
}
}
$dom->save('test2.xml');
?>

Delete XML Node:


deletexmlnode.php
<?php
$xmlfile = "test.xml";
$xmlstr = file_get_contents($xmlfile);
$xml = simplexml_load_string($xmlstr);
$count = 0;
foreach ($xml as $user) {
if (trim($user->first_name) == "Ram")
{
unset($xml->person[$count]); break;
}
$count++;

Page 78 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

}
$xml->asxml("test3.xml");
exit;
?>

AJAX = Asynchronous JavaScript And XML


AJAX is an acronym for Asynchronous JavaScript And XML.

AJAX is not a new programming language, but simply a new technique for creating better, faster,
and more interactive web applications.

AJAX uses JavaScript to send and receive data between a web browser and a web server.

The AJAX technique makes web pages more responsive by exchanging data with the web server
behind the scenes, instead of reloading an entire web page each time a user makes a change.

AJAX Is Based On Open Standards


AJAX is based on the following open standards:

 JavaScript
 XML
 HTML
 CSS

The open standards used in AJAX are well defined, and supported by all major browsers. AJAX
applications are browser and platform independent. (Cross-Platform, Cross-Browser technology)

AJAX Is About Better Internet Applications


Web applications have many benefits over desktop applications:

 they can reach a larger audience


 they are easier to install and support
 they are easier to develop

However, Internet applications are not always as "rich" and user-friendly as traditional desktop
applications.

With AJAX, Internet applications can be made richer (smaller, faster, and easier to use).

You Can Start Using AJAX Today


There is nothing new to learn.

AJAX is based on open standards. These standards have been used by most developers for several
years.

Page 79 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

Most existing web applications can be rewritten to use AJAX technology instead of traditional
HTML forms.

AJAX Uses XML And HTTP Requests


A traditional web application will submit input (using an HTML form) to a web server. After the
web server has processed the data, it will return a completely new web page to the user.

Because the server returns a new web page each time the user submits input, traditional web
applications often run slowly and tend to be less user friendly.

With AJAX, web applications can send and retrieve data without reloading the whole web page.
This is done by sending HTTP requests to the server (behind the scenes), and by modifying only
parts of the web page using JavaScript when the server returns data.

XML is commonly used as the format for receiving server data, although any format, including
plain text, can be used.

You will learn more about how this is done in the next chapters of this tutorial.

PHP and AJAX


There is no such thing as an AJAX server.

AJAX is a technology that runs in your browser. It uses asynchronous data transfer (HTTP
requests) between the browser and the web server, allowing web pages to request small bits of
information from the server instead of whole pages.

AJAX is a web browser technology independent of web server software.

However, in this tutorial we will focus more on actual examples running on a PHP server, and less
on how AJAX works.

The XMLHttpRequest object makes AJAX possible.


The XMLHttpRequest
The XMLHttpRequest object is the key to AJAX.

It has been available ever since Internet Explorer 5.5 was released in July 2000, but not fully
discovered before people started to talk about AJAX and Web 2.0 in 2005.

Creating An XMLHttpRequest Object


Different browsers use different methods to create an XMLHttpRequest object.

Internet Explorer uses an ActiveXObject.

Other browsers uses a built in JavaScript object called XMLHttpRequest.

Page 80 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

Here is the simplest code you can use to overcome this problem:

var XMLHttp=null
if (window.XMLHttpRequest)
{
XMLHttp=new XMLHttpRequest()
}
else if (window.ActiveXObject)
{
XMLHttp=new ActiveXObject("Microsoft.XMLHTTP")
}

Example above explained:

1. First create a variable XMLHttp to use as your XMLHttpRequest object. Set the value to
null.
2. Then test if the object window.XMLHttpRequest is available. This object is available in
newer versions of Firefox, Mozilla, Opera, and Safari.
3. If it's available, use it to create a new object: XMLHttp=new XMLHttpRequest()
4. If it's not available, test if an object window.ActiveXObject is available. This object is
available in Internet Explorer version 5.5 and later.
5. If it is available, use it to create a new object: XMLHttp=new ActiveXObject()

A Better Example?
Some programmers will prefer to use the newest and fastest version of the XMLHttpRequest
object.

The example below tries to load Microsoft's latest version "Msxml2.XMLHTTP", available in Internet
Explorer 6, before it falls back to "Microsoft.XMLHTTP", available in Internet Explorer 5.5 and later.

function GetXmlHttpObject()

{
var xmlHttp=null;

try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");

Page 81 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

}
}
return xmlHttp;
}

Example above explained:

1. First create a variable XMLHttp to use as your XMLHttpRequest object. Set the value to
null.
2. Try to create the object the according to web standards (Mozilla, Opera and
Safari):XMLHttp=new XMLHttpRequest()
3. Try to create the object the Microsoft way, available in Internet Explorer 6 and
later:XMLHttp=new ActiveXObject("Msxml2.XMLHTTP")

4. If this catches an error, try the older (Internet Explorer 5.5) way: XMLHttp=new
ActiveXObject("Microsoft.XMLHTTP")

AJAX Suggest
In the AJAX example below we will demonstrate how a web page can communicate with a web
server online as a user enters data into a web form.

Suggestions: no suggestion

This example consists of three pages:

 a simple HTML form


 a JavaScript
 a PHP page

The HTML Form


This is the HTML page. It contains a simple HTML form and a link to a JavaScript:

<html>
<head>
<script src="clienthint.js"></script>
</head>

<body>

<form>
First Name:
<input type="text" id="txt1"
onkeyup="showHint(this.value)">
</form>

<p>Suggestions: <span id="txtHint"></span></p>

</body>

Page 82 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

</html>

Example Explained - The HTML Form


As you can see, the HTML page above contains a simple HTML form with an input field called
"txt1".

The form works like this:

1. An event is triggered when the user presses, and releases a key in the input field
2. When the event is triggered, a function called showHint() is executed.
3. Below the form is a <span> called "txtHint". This is used as a placeholder for the return
data of the showHint() function.

The JavaScript
The JavaScript code is stored in "clienthint.js" and linked to the HTML document:

var xmlHttp
function showHint(str)
{
if (str.length==0)
{
document.getElementById("txtHint").innerHTML=""
return
}
xmlHttp=GetXmlHttpObject()
if (xmlHttp==null)
{
alert ("Browser does not support HTTP Request")
return
}
var url="gethint.php"
url=url+"?q="+str
url=url+"&sid="+Math.random()
xmlHttp.onreadystatechange=stateChanged
xmlHttp.open("GET",url,true)
xmlHttp.send(null)
}

function stateChanged()
{
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
{
document.getElementById("txtHint").innerHTML=xmlHttp.responseText
}
}

function GetXmlHttpObject()
{
var xmlHttp=null;

Page 83 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}

Example Explained
The showHint() Function

This function executes every time a character is entered in the input field.

If there is some input in the text field (str.length > 0) the function executes the following:

1. Defines the url (filename) to send to the server


2. Adds a parameter (q) to the url with the content of the input field
3. Adds a random number to prevent the server from using a cached file
4. Calls on the GetXmlHttpObject function to create an XMLHTTP object, and tells the object
to execute a function called stateChanged when a change is triggered
5. Opens the XMLHTTP object with the given url.
6. Sends an HTTP request to the server

If the input field is empty, the function simply clears the content of the txtHint placeholder.

The stateChanged() Function

This function executes every time the state of the XMLHTTP object changes.

When the state changes to 4 (or to "complete"), the content of the txtHint placeholder is filled
with the response text.

The GetXmlHttpObject() Function

AJAX applications can only run in web browsers with complete XML support.

The code above called a function called GetXmlHttpObject().

Page 84 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

The purpose of the function is to solve the problem of creating different XMLHTTP objects for
different browsers.

This is explained in the previous chapter.

The PHP Page


The server page called by the JavaScript code is a simple PHP file called "gethint.php".

The code in the "gethint.php" checks an array of names and returns the corresponding names to
the client:

<?php
// Fill up array with names
$a[]="Anna";
$a[]="Brittany";
$a[]="Cinderella";
$a[]="Diana";
$a[]="Eva";
$a[]="Fiona";
$a[]="Gunda";
$a[]="Hege";
$a[]="Inga";
$a[]="Johanna";
$a[]="Kitty";
$a[]="Linda";
$a[]="Nina";
$a[]="Ophelia";
$a[]="Petunia";
$a[]="Amanda";
$a[]="Raquel";
$a[]="Cindy";
$a[]="Doris";
$a[]="Eve";
$a[]="Evita";
$a[]="Sunniva";
$a[]="Tove";
$a[]="Unni";
$a[]="Violet";
$a[]="Liza";
$a[]="Elizabeth";
$a[]="Ellen";
$a[]="Wenche";
$a[]="Vicky";

//get the q parameter from URL


$q=$_GET["q"];

//lookup all hints from array if length of q>0


if (strlen($q) > 0)
{

Page 85 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

$hint="";
for($i=0; $i<count($a); $i++)
{
if (strtolower($q)==strtolower(substr($a[$i],0,strlen($q))))
{
if ($hint=="")
{
$hint=$a[$i];
}
else
{
$hint=$hint." , ".$a[$i];
}
}
}
}

//Set output to "no suggestion" if no hint were found


//or to the correct values
if ($hint == "")
{
$response="no suggestion";
}
else
{
$response=$hint;
}

//output the response


echo $response;
?>

If there is any text sent from the JavaScript (strlen($q) > 0) the following happens:

1. Find a name matching the characters sent from the JavaScript


2. If more than one name is found, include all names in the response string
3. If no matching names were found, set response to "no suggestion"
4. If one or more matching names were found, set response to these names
5. The response is sent to the "txtHint" placeholder

PHP and AJAX XML Example

AJAX can be used for interactive communication with an XML file.

AJAX XML Example


In the AJAX example below we will demonstrate how a web page can fetch information from an
XML file using AJAX technology.

Page 86 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

The HTML Form


The example above contains a simple HTML form and a link to a JavaScript:

<html>
<head>
<script src="selectcd.js"></script>
</head>

<body>

<form>
Select a CD:
<select name="cds" onchange="showCD(this.value)">
<option value="Bob Dylan">Bob Dylan</option>
<option value="Bee Gees">Bee Gees</option>
<option value="Cat Stevens">Cat Stevens</option>
</select>
</form>

<p>
<div id="txtHint"><b>CD info will be listed here.</b></div>
</p>

</body>
</html>

Example Explained
As you can see it is just a simple HTML form with a simple drop down box called "cds".

The paragraph below the form contains a div called "txtHint". The div is used as a placeholder for
info retrieved from the web server.

When the user selects data, a function called "showCD" is executed. The execution of the function
is triggered by the "onchange" event.

In other words: Each time the user changes the value in the drop down box, the function showCD
is called.

The JavaScript
This is the JavaScript code stored in the file "selectcd.js":

var xmlHttp

function showCD(str)
{
xmlHttp=GetXmlHttpObject()
if (xmlHttp==null)

Page 87 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

{
alert ("Browser does not support HTTP Request")
return
}
var url="getcd.php"
url=url+"?q="+str
url=url+"&sid="+Math.random()
xmlHttp.onreadystatechange=stateChanged
xmlHttp.open("GET",url,true)
xmlHttp.send(null)
}

function stateChanged()
{
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
{
document.getElementById("txtHint").innerHTML=xmlHttp.responseText
}
}

function GetXmlHttpObject()
{
var xmlHttp=null;

try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}

Example Explained
The stateChanged() and GetXmlHttpObject functions are the same as in the last chapter, you can
go to the previous page for an explanation of those

The showCD() Function

Page 88 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

If an item in the drop down box is selected the function executes the following:

1. Calls on the GetXmlHttpObject function to create an XMLHTTP object


2. Defines the url (filename) to send to the server
3. Adds a parameter (q) to the url with the content of the input field
4. Adds a random number to prevent the server from using a cached file
5. Call stateChanged when a change is triggered
6. Opens the XMLHTTP object with the given url.
7. Sends an HTTP request to the server

The PHP Page


The server paged called by the JavaScript, is a simple PHP file called "getcd.php".

The page is written in PHP using the XML DOM to load the XML document "cd_catalog.xml".

The code runs a query against the XML file and returns the result as HTML:

<?php
$q=$_GET["q"];

$xmlDoc = new DOMDocument();


$xmlDoc->load("cd_catalog.xml");

$x=$xmlDoc->getElementsByTagName('ARTIST');

for ($i=0; $i<=$x->length-1; $i++)


{
//Process only element nodes
if ($x->item($i)->nodeType==1)
{
if ($x->item($i)->childNodes->item(0)->nodeValue == $q)
{
$y=($x->item($i)->parentNode);
}
}
}

$cd=($y->childNodes);

for ($i=0;$i<$cd->length;$i++)
{
//Process only element nodes
if ($cd->item($i)->nodeType==1)
{
echo($cd->item($i)->nodeName);
echo(": ");
echo($cd->item($i)->childNodes->item(0)->nodeValue);
echo("<br />");
}

Page 89 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

}
?>

Example Explained
When the query is sent from the JavaScript to the PHP page the following happens:

1. PHP creates an XML DOM object of the "cd_catalog.xml" file


2. All "artist" elements (nodetypes = 1) are looped through to find a name matching the one
sent from the JavaScript.
3. The CD containing the correct artist is found
4. The album information is output and sent to the "txtHint" placeholder

AJAX can be used for interactive communication with a database.

AJAX Database Example


In the AJAX example below we will demonstrate how a web page can fetch information from a
MySQL database using AJAX technology.

The Database
The database we will be using in this example looks like this:

id FirstName LastName Age Hometown Job


1 Peter Griffin 41 Quahog Brewery
2 Lois Griffin 40 Newport Piano Teacher
3 Joseph Swanson 39 Quahog Police Officer
4 Glenn Quagmire 41 Quahog Pilot

The HTML Form


The example above contains a simple HTML form and a link to a JavaScript:

<html>
<head>
<script src="selectuser.js"></script>
</head>
<body>

<form>
Select a User:

Page 90 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

<select name="users" onchange="showUser(this.value)">


<option value="1">Peter Griffin</option>
<option value="2">Lois Griffin</option>
<option value="3">Glenn Quagmire</option>
<option value="4">Joseph Swanson</option>
</select>
</form>

<p>
<div id="txtHint"><b>User info will be listed here.</b></div>
</p>

</body>
</html>

Example Explained - The HTML Form


As you can see it is just a simple HTML form with a drop down box called "users" with names and
the "id" from the database as option values.

The paragraph below the form contains a div called "txtHint". The div is used as a placeholder for
info retrieved from the web server.

When the user selects data, a function called "showUser()" is executed. The execution of the
function is triggered by the "onchange" event.

In other words: Each time the user changes the value in the drop down box, the function
showUser() is called.

The JavaScript
This is the JavaScript code stored in the file "selectuser.js":

var xmlHttp

function showUser(str)
{
xmlHttp=GetXmlHttpObject()
if (xmlHttp==null)
{
alert ("Browser does not support HTTP Request")
return
}
var url="getuser.php"
url=url+"?q="+str
url=url+"&sid="+Math.random()
xmlHttp.onreadystatechange=stateChanged
xmlHttp.open("GET",url,true)
xmlHttp.send(null)
}

Page 91 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

function stateChanged()
{
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
{
document.getElementById("txtHint").innerHTML=xmlHttp.responseText
}
}

function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
//Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}

Example Explained
The stateChanged() and GetXmlHttpObject functions are the same as in the PHP AJAX Suggest
chapter, you can go to there for an explanation of those.

The showUser() Function

If an item in the drop down box is selected the function executes the following:

1. Calls on the GetXmlHttpObject function to create an XMLHTTP object


2. Defines the url (filename) to send to the server
3. Adds a parameter (q) to the url with the content of the dropdown box
4. Adds a random number to prevent the server from using a cached file
5. Call stateChanged when a change is triggered
6. Opens the XMLHTTP object with the given url.
7. Sends an HTTP request to the server

The PHP Page


The server page called by the JavaScript, is a simple PHP file called "getuser.php".

Page 92 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

The page is written in PHP and uses a MySQL databse.

The code runs a SQL query against a database and returns the result as an HTML table:

<?php
$q=$_GET["q"];

$con = mysql_connect('localhost', 'peter', 'abc123');


if (!$con)
{
die('Could not connect: ' . mysql_error());
}

mysql_select_db("ajax_demo", $con);

$sql="SELECT * FROM user WHERE id = '".$q."'";

$result = mysql_query($sql);

echo "<table border='1'>


<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
<th>Hometown</th>
<th>Job</th>
</tr>";

while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "<td>" . $row['Age'] . "</td>";
echo "<td>" . $row['Hometown'] . "</td>";
echo "<td>" . $row['Job'] . "</td>";
echo "</tr>";
}
echo "</table>";

mysql_close($con);
?>

Example Explained
When the query is sent from the JavaScript to the PHP page the following happens:

1. PHP opens a connection to a MySQL server


2. The "user" with the specified name is found
3. A table is created and the data is inserted and sent to the "txtHint" placeholder

Page 93 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

PHP and AJAX responseXML Example

AJAX can be used to return database information as XML.

AJAX Database as XML Example


In the AJAX example below we will demonstrate how a web page can fetch information from a
MySQL database, convert it to an XML document, and use it to display information in several
different places.

This example my seem a lot like the "PHP AJAX Database" example in the last chapter, however
there is a big difference: in this example we get the data from the PHP page as XML using the
responseXML function.

Receiving the response as an XML document allows us to update this page several places, instead
of just receiving a PHP output and displaying it.

In this example we will update several <span> elements with the information we receive from the
database.

The Database
The database we will be using in this example looks like this:

id FirstName LastName Age Hometown Job


1 Peter Griffin 41 Quahog Brewery
2 Lois Griffin 40 Newport Piano Teacher
3 Joseph Swanson 39 Quahog Police Officer
4 Glenn Quagmire 41 Quahog Pilot

The HTML Form


The example above contains a simple HTML form and a link to a JavaScript:

<html>
<head>
<script src="responsexml.js"></script>
</head>
<body>

<form>

Page 94 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

Select a User:
<select name="users" onchange="showUser(this.value)">
<option value="1">Peter Griffin</option>
<option value="2">Lois Griffin</option>
<option value="3">Glenn Quagmire</option>
<option value="4">Joseph Swanson</option>
</select>
</form>

<h2><span id="firstname"></span>
&nbsp;<span id="lastname"></span></h2>
<span id="job"></span>
<div style="text-align: right">
<span id="age_text"></span>
<span id="age"></span>
<span id="hometown_text"></span>
<span id="hometown"></span>
</div>

</body>
</html>

Example Explained - The HTML Form


 The HTML form is a drop down box called "users" with names and the "id" from the
database as option values.
 Below the form there are several different <span> elements which are used to as
placeholders for the different values we will retrive.
 When the user selects data, a function called "showUser()" is executed. The execution of
the function is triggered by the "onchange" event.

In other words: Each time the user changes the value in the drop down box, the function
showUser() is called and outputs the result in the specified <span> elements.

The JavaScript
This is the JavaScript code stored in the file "responsexml.js":

var xmlHttp

function showUser(str)
{
xmlHttp=GetXmlHttpObject()
if (xmlHttp==null)
{
alert ("Browser does not support HTTP Request")
return
}
var url="responsexml.php"
url=url+"?q="+str

Page 95 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

url=url+"&sid="+Math.random()
xmlHttp.onreadystatechange=stateChanged
xmlHttp.open("GET",url,true)
xmlHttp.send(null)
}

function stateChanged()
{
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
{
xmlDoc=xmlHttp.responseXML;
document.getElementById("firstname").innerHTML=
xmlDoc.getElementsByTagName("firstname")[0].childNodes[0].nodeValue;
document.getElementById("lastname").innerHTML=
xmlDoc.getElementsByTagName("lastname")[0].childNodes[0].nodeValue;
document.getElementById("job").innerHTML=
xmlDoc.getElementsByTagName("job")[0].childNodes[0].nodeValue;
document.getElementById("age_text").innerHTML="Age: ";
document.getElementById("age").innerHTML=
xmlDoc.getElementsByTagName("age")[0].childNodes[0].nodeValue;
document.getElementById("hometown_text").innerHTML="<br/>From: ";
document.getElementById("hometown").innerHTML=
xmlDoc.getElementsByTagName("hometown")[0].childNodes[0].nodeValue;
}
}

function GetXmlHttpObject()
{
var objXMLHttp=null
if (window.XMLHttpRequest)
{
objXMLHttp=new XMLHttpRequest()
}
else if (window.ActiveXObject)
{
objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP")
}
return objXMLHttp
}

Example Explained
The showUser() and GetXmlHttpObject functions are the same as in the PHP AJAX Database
chapter, you can go to there for an explanation of those.

The stateChanged() Function

If an item in the drop down box is selected the function executes the following:

Page 96 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

1. Defines the "xmlDoc" variable as an xml document using the responseXML function
2. Retrieves data from the xml documents and places them in the correct <span> elements

The PHP Page


The server page called by the JavaScript, is a simple PHP file called "responsexml.php".

The page is written in PHP and uses a MySQL databse.

The code runs a SQL query against a database and returns the result as an XML document:

<?php
header('Content-Type: text/xml');
header("Cache-Control: no-cache, must-revalidate");
//A date in the past
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");

$q=$_GET["q"];

$con = mysql_connect('localhost', 'peter', 'abc123');


if (!$con)
{
die('Could not connect: ' . mysql_error());
}

mysql_select_db("ajax_demo", $con);

$sql="SELECT * FROM user WHERE id = ".$q."";

$result = mysql_query($sql);

echo '<?xml version="1.0" encoding="ISO-8859-1"?>


<person>';
while($row = mysql_fetch_array($result))
{
echo "<firstname>" . $row['FirstName'] . "</firstname>";
echo "<lastname>" . $row['LastName'] . "</lastname>";
echo "<age>" . $row['Age'] . "</age>";
echo "<hometown>" . $row['Hometown'] . "</hometown>";
echo "<job>" . $row['Job'] . "</job>";
}
echo "</person>";

mysql_close($con);
?>

Example Explained
When the query is sent from the JavaScript to the PHP page the following happens:

Page 97 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

1. The content-type of the PHP document is set to be "text/xml"


2. The PHP document is set to "no-cache" to prevent caching
3. The $q variable is set to be the data sent from the html page
4. PHP opens a connection to a MySQL server
5. The "user" with the specified id is found
6. The data is outputted as an xml document

PHP and AJAX Live Search

AJAX can be used for a more user friendly and interactive search.

AJAX Live Search


In the AJAX example below we will demonstrate a live search, where the server gets search
results while the user types.

Live search has many benefits compared to traditional searching:

 Matching results are shown as you type


 Results narrow as you continue typing
 If results become too narrow, remove characters to see a broader result

The HTML Form


This is the HTML page. It contains a simple HTML form, style for the form and a link to a
JavaScript:

<html>
<head>
<script src="livesearch.js"></script>
<style type="text/css">
#livesearch
{
margin:0px;
width:194px;
}
#txt1
{
margin:0px;
}
</style>
</head>
<body>

<form>
<input type="text" id="txt1" size="30"
onkeyup="showResult(this.value)">

<div id="livesearch"></div>
</form>

Page 98 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

</body>
</html>

Example Explained - The HTML Form


As you can see, the HTML page above contains a simple HTML form with an input field called
"txt1".

The form works like this:

1. An event is triggered when the user presses, and releases a key in the input field
2. When the event is triggered, a function called showResult() is executed.
3. Below the form is a <div> called "livesearch". This is used as a placeholder for the return
data of the showResult() function.

The JavaScript
The JavaScript code is stored in "livesearch.js" and linked to the HTML document:

var xmlHttp

function showResult(str)
{
if (str.length==0)
{
document.getElementById("livesearch").
innerHTML="";
document.getElementById("livesearch").
style.border="0px";
return
}

xmlHttp=GetXmlHttpObject()

if (xmlHttp==null)
{
alert ("Browser does not support HTTP Request")
return
}

var url="livesearch.php"
url=url+"?q="+str
url=url+"&sid="+Math.random()
xmlHttp.onreadystatechange=stateChanged
xmlHttp.open("GET",url,true)
xmlHttp.send(null)
}

function stateChanged()
{

Page 99 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
{
document.getElementById("livesearch").
innerHTML=xmlHttp.responseText;
document.getElementById("livesearch").
style.border="1px solid #A5ACB2";
}
}

function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}

The showResult() Function

This function executes every time a character is entered in the input field.

If there is no input in the text field (str.length == 0) the function sets the return field to empty
and removes any border around it.

However, if there is any input in the text field the function executes the following:

1. Defines the url (filename) to send to the server


2. Adds a parameter (q) to the url with the content of the input field
3. Adds a random number to prevent the server from using a cached file
4. Calls on the GetXmlHttpObject function to create an XMLHTTP object, and tells the object
to execute a function called stateChanged when a change is triggered
5. Opens the XMLHTTP object with the given url.
6. Sends an HTTP request to the server

The stateChanged() Function

Page 100 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

This function executes every time the state of the XMLHTTP object changes.

When the state changes to 4 (or to "complete"), the content of the txtHint placeholder is filled
with the response text, and a border is set around the return field.

The PHP Page


The server page called by the JavaScript code is a PHP file called "livesearch.php".

The code in the "livesearch.php" checks the XML document " links.xml". This document contains
titles and URL's of some pages on W3Schools.com.

The code searches the XML file for titles matching the search string and returns the result as
HTML:

<?php
$xmlDoc = new DOMDocument();
$xmlDoc->load("links.xml");

$x=$xmlDoc->getElementsByTagName('link');

//get the q parameter from URL


$q=$_GET["q"];

//lookup all links from the xml file if length of q>0


if (strlen($q) > 0)
{
$hint="";
for($i=0; $i<($x->length); $i++)
{
$y=$x->item($i)->getElementsByTagName('title');
$z=$x->item($i)->getElementsByTagName('url');
if ($y->item(0)->nodeType==1)
{
//find a link matching the search text
if (stristr($y->item(0)->childNodes->item(0)->nodeValue,$q))
{
if ($hint=="")
{
$hint="<a href='" .
$z->item(0)->childNodes->item(0)->nodeValue .
"' target='_blank'>" .
$y->item(0)->childNodes->item(0)->nodeValue . "</a>";
}
else
{
$hint=$hint . "<br /><a href='" .
$z->item(0)->childNodes->item(0)->nodeValue .
"' target='_blank'>" .
$y->item(0)->childNodes->item(0)->nodeValue . "</a>";
}
Page 101 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

}
}
}
}

// Set output to "no suggestion" if no hint were found


// or to the correct values
if ($hint == "")
{
$response="no suggestion";
}
else
{
$response=$hint;
}

//output the response


echo $response;
?>

PHP and AJAX RSS Reader

An RSS Reader is used to read RSS Feeds

RSS allows fast browsing for news and updates

AJAX RSS Reader


In the AJAX example below we will demonstrate an RSS reader where the content from the RSS is
loaded into the webpage without refreshing.

The HTML Form


This is the HTML page. It contains a simple HTML form and a link to a JavaScript:

<html>
<head>
<script type="text/javascript" src="getrss.js"></script>
</head>
<body>

<form>
Select an RSS-Feed:
<select onchange="showRSS(this.value)">
<option value="Google">Google News</option>
<option value="MSNBC">MSNBC News</option>
</select>
</form>

<p><div id="rssOutput">

Page 102 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

<b>RSS Feed will be listed here.</b></div></p>


</body>
</html>

Example Explained - The HTML Form


As you can see, the HTML page above contains a simple HTML form with a drop-down box.

The form works like this:

1. An event is triggered when the user selects an option in the drop down box
2. When the event is triggered, a function called showRSS() is executed.
3. Below the form is a <div> called "rssOutput". This is used as a placeholder for the return
data of the showRSS() function.

The JavaScript
The JavaScript code is stored in "getrss.js" and linked to the HTML document:

var xmlHttp

function showRSS(str)
{
xmlHttp=GetXmlHttpObject()
if (xmlHttp==null)
{
alert ("Browser does not support HTTP Request")
return
}
var url="getrss.php"
url=url+"?q="+str
url=url+"&sid="+Math.random()
xmlHttp.onreadystatechange=stateChanged
xmlHttp.open("GET",url,true)
xmlHttp.send(null)
}

function stateChanged()
{
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
{
document.getElementById("rssOutput")
.innerHTML=xmlHttp.responseText
}
}

function GetXmlHttpObject()
{
var xmlHttp=null;
try

Page 103 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}

The showRSS() Function

Every time an option is selected in the input field this function executes the following:

1. Defines the url (filename) to send to the server


2. Adds a parameter (q) to the url with the selected option from the drop down box
3. Adds a random number to prevent the server from using a cached file
4. Calls on the GetXmlHttpObject function to create an XMLHTTP object, and tells the object
to execute a function called stateChanged when a change is triggered
5. Opens the XMLHTTP object with the given url.
6. Sends an HTTP request to the server

The PHP Page


The server page called by the JavaScript code is a PHP file called "getrss.php":

<?php
//get the q parameter from URL
$q=$_GET["q"];

//find out which feed was selected


if($q=="Google")
{
$xml=("http://news.google.com/news?ned=us&topic=h&output=rss");
}
elseif($q=="MSNBC")
{
$xml=("http://rss.msnbc.msn.com/id/3032091/device/rss/rss.xml");
}

$xmlDoc = new DOMDocument();


$xmlDoc->load($xml);

Page 104 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

//get elements from "<channel>"


$channel=$xmlDoc->getElementsByTagName('channel')->item(0);
$channel_title = $channel->getElementsByTagName('title')
->item(0)->childNodes->item(0)->nodeValue;
$channel_link = $channel->getElementsByTagName('link')
->item(0)->childNodes->item(0)->nodeValue;
$channel_desc = $channel->getElementsByTagName('description')
->item(0)->childNodes->item(0)->nodeValue;

//output elements from "<channel>"


echo("<p><a href='" . $channel_link
. "'>" . $channel_title . "</a>");
echo("<br />");
echo($channel_desc . "</p>");

//get and output "<item>" elements


$x=$xmlDoc->getElementsByTagName('item');
for ($i=0; $i<=2; $i++)
{
$item_title=$x->item($i)->getElementsByTagName('title')
->item(0)->childNodes->item(0)->nodeValue;
$item_link=$x->item($i)->getElementsByTagName('link')
->item(0)->childNodes->item(0)->nodeValue;
$item_desc=$x->item($i)->getElementsByTagName('description')
->item(0)->childNodes->item(0)->nodeValue;

echo ("<p><a href='" . $item_link


. "'>" . $item_title . "</a>");
echo ("<br />");
echo ($item_desc . "</p>");
}
?>

Example Explained - The PHP Page


When an option is sent from the JavaScript the following happens:

1. PHP finds out which RSS feed was selected


2. An XML DOM object is created for the selected RSS feed
3. The elements from the RSS channel are found and outputted
4. The three first elements from the RSS items are looped through and outputted

PHP and AJAX Poll

AJAX Suggest
In the AJAX example below we will demonstrate a poll where the web page can get the result
without reloading.

Page 105 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

The HTML Form


This is the HTML page. It contains a simple HTML form and a link to a JavaScript:

<html>
<head>
<script src="poll.js"></script>
</head>
<body>

<div id="poll">
<h2>Do you like PHP and AJAX so far?</h2>

<form>
Yes:
<input type="radio" name="vote"
value="0" onclick="getVote(this.value)">
<br />No:
<input type="radio" name="vote"
value="1" onclick="getVote(this.value)">
</form>
</div>

</body>
</html>

Example Explained - The HTML Form


As you can see, the HTML page above contains a simple HTML form inside a "<div>" with two
radio buttons.

The form works like this:

1. An event is triggered when the user selects the "yes" or "no" option
2. When the event is triggered, a function called getVote() is executed.
3. Around the form is a <div> called "poll". When the data is returned from the getVote()
function, the return data will replace the form.

The Text File


The text file (poll_result.txt) is where we store the data from the poll.

It is stored like this:

0||0

The first number represents the "Yes" votes, the second number represents the "No" votes.

Note: Remember to allow your web server to edit the text file. Do NOT give everyone access, just
the web server (PHP).

Page 106 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

The JavaScript
The JavaScript code is stored in "poll.js" and linked to in the HTML document:

var xmlHttp

function getVote(int)
{
xmlHttp=GetXmlHttpObject()
if (xmlHttp==null)
{
alert ("Browser does not support HTTP Request")
return
}
var url="poll_vote.php"
url=url+"?vote="+int
url=url+"&sid="+Math.random()
xmlHttp.onreadystatechange=stateChanged
xmlHttp.open("GET",url,true)
xmlHttp.send(null)
}

function stateChanged()
{
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
{
document.getElementById("poll").
innerHTML=xmlHttp.responseText;
}
}

function GetXmlHttpObject()
{
var objXMLHttp=null
if (window.XMLHttpRequest)
{
objXMLHttp=new XMLHttpRequest()
}
else if (window.ActiveXObject)
{
objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP")
}
return objXMLHttp
}

The getVote() Function

This function executes when "yes" or "no" is selected in the HTML form.

1. Defines the url (filename) to send to the server


2. Adds a parameter (vote) to the url with the content of the input field
3. Adds a random number to prevent the server from using a cached file

Page 107 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

4. Calls on the GetXmlHttpObject function to create an XMLHTTP object, and tells the object
to execute a function called stateChanged when a change is triggered
5. Opens the XMLHTTP object with the given url.
6. Sends an HTTP request to the server

The PHP Page


The server page called by the JavaScript code is a simple PHP file called "poll_vote.php".

<?php
$vote = $_REQUEST['vote'];

//get content of textfile


$filename = "poll_result.txt";
$content = file($filename);

//put content in array


$array = explode("||", $content[0]);
$yes = $array[0];
$no = $array[1];

if ($vote == 0)
{
$yes = $yes + 1;
}
if ($vote == 1)
{
$no = $no + 1;
}

//insert votes to txt file


$insertvote = $yes."||".$no;
$fp = fopen($filename,"w");
fputs($fp,$insertvote);
fclose($fp);
?>

<h2>Result:</h2>
<table>
<tr>
<td>Yes:</td>
<td>
<img src="poll.gif"
width='<?php echo(100*round($yes/($no+$yes),2)); ?>'
height='20'>
<?php echo(100*round($yes/($no+$yes),2)); ?>%
</td>
</tr>
<tr>
<td>No:</td>
<td>

Page 108 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

<img src="poll.gif"
width='<?php echo(100*round($no/($no+$yes),2)); ?>'
height='20'>
<?php echo(100*round($no/($no+$yes),2)); ?>%
</td>
</tr>
</table>

PHP Array Functions

Page 109 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

Page 110 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

PHP Calendar Functions

PHP Calendar Introduction


The calendar functions are useful when working with different calendar formats. The standard it is
based on is the Julian day count (Julian day count is a count of days starting from January 1,
4713 B.C.). Note that the Julian day count is not the same as the Julian calendar!

Note: To convert between calendar formats, you must first convert to Julian day count, then to
the calendar format.

Page 111 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

<?php

echo cal_days_in_month( CAL_GREGORIAN, date("m"), date("Y")); // used to display


particular months day.

?>

Page 112 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

Page 113 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

PHP Date / Time Functions

PHP Date / Time Introduction


The date/time functions allow you to extract and format the date and time on the server.

Note: These functions depend on the locale settings of the server!

Page 114 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

PHP libxml Introduction

PHP libxml Functions


The libxml functions and constants are used together with SimpleXML, XSLT and DOM functions.

PHP libxml Functions


PHP: indicates the earliest version of PHP that supports the function.

Function Description PH
P
libxml_clear_errors() Clear libxml error buffer 5

Page 115 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

libxml_get_errors() Retrieve array of errors 5


libxml_get_last_error() Retrieve last error from libxml 5
libxml_set_streams_context() Set the streams context for the next libxml document 5
load or write
libxml_use_internal_errors() Disable libxml errors and allow user to fetch error 5
information as needed

PHP libxml Constants

Function Description PHP

LIBXML_COMPACT Set small nodes allocation optimization. This may 5


improve the application performance
LIBXML_DTDATTR Set default DTD attributes 5
LIBXML_DTDLOAD Load external subset 5
LIBXML_DTDVALID Validate with the DTD 5
LIBXML_NOBLANKS Remove blank nodes 5
LIBXML_NOCDATA Set CDATA as text nodes 5
LIBXML_NOEMPTYTAG Change empty tags (e.g. <br/> to <br></br>), only 5
available in the DOMDocument->save() and
DOMDocument->saveXML() functions
LIBXML_NOENT Substitute entities 5
LIBXML_NOERROR Do not show error reports 5
LIBXML_NONET Stop network access while loading documents 5
LIBXML_NOWARNING Do not show warning reports 5
LIBXML_NOXMLDECL Drop the XML declaration when saving a document 5
LIBXML_NSCLEAN Remove excess namespace declarations 5
LIBXML_XINCLUDE Use XInclude substitution 5
LIBXML_ERR_ERROR Get recoverable errors 5
LIBXML_ERR_FATAL Get fatal errors 5
LIBXML_ERR_NONE Get no errors 5
LIBXML_ERR_WARNING Get simple warnings 5
LIBXML_VERSION Get libxml version (e.g. 20605 or 20617) 5
LIBXML_DOTTED_VERSION Get dotted libxml version (e.g. 2.6.5 or 2.6.17) 5

Page 116 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

PHP MySQL Functions

Function Description PHP

mysql_affected_rows() Returns the number of affected rows in the previous MySQL 3


operation
mysql_change_user() Deprecated. Changes the user of the current MySQL 3
connection
mysql_client_encoding() Returns the name of the character set for the current 4
connection
mysql_close() Closes a non-persistent MySQL connection 3
mysql_connect() Opens a non-persistent MySQL connection 3
mysql_create_db() Deprecated. Creates a new MySQL database. Use 3
mysql_query() instead
mysql_data_seek() Moves the record pointer 3
mysql_db_name() Returns a database name from a call to mysql_list_dbs() 3
mysql_db_query() Deprecated. Sends a MySQL query. Use mysql_select_db() 3
and mysql_query() instead
mysql_drop_db() Deprecated. Deletes a MySQL database. Use mysql_query() 3
instead
mysql_errno() Returns the error number of the last MySQL operation 3
mysql_error() Returns the error description of the last MySQL operation 3
mysql_escape_string() Deprecated. Escapes a string for use in a mysql_query. Use 4
mysql_real_escape_string() instead
mysql_fetch_array() Returns a row from a recordset as an associative array and/or 3
a numeric array
mysql_fetch_assoc() Returns a row from a recordset as an associative array 4
mysql_fetch_field() Returns column info from a recordset as an object 3
mysql_fetch_lengths() Returns the length of the contents of each field in a result row 3

mysql_fetch_object() Returns a row from a recordset as an object 3


mysql_fetch_row() Returns a row from a recordset as a numeric array 3
mysql_field_flags() Returns the flags associated with a field in a recordset 3
mysql_field_len() Returns the maximum length of a field in a recordset 3
mysql_field_name() Returns the name of a field in a recordset 3
mysql_field_seek() Moves the result pointer to a specified field 3
mysql_field_table() Returns the name of the table the specified field is in 3

Page 117 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

mysql_field_type() Returns the type of a field in a recordset 3


mysql_free_result() Free result memory 3

mysql_get_client_info( Returns MySQL client info 4


)
mysql_get_host_info() Returns MySQL host info 4
mysql_get_proto_info( Returns MySQL protocol info 4
)
mysql_get_server_info Returns MySQL server info 4
()
mysql_info() Returns information about the last query 4
mysql_insert_id() Returns the AUTO_INCREMENT ID generated from the previous 3
INSERT operation
mysql_list_dbs() Lists available databases on a MySQL server 3
mysql_list_fields() Deprecated. Lists MySQL table fields. Use mysql_query() instead 3
mysql_list_processes( Lists MySQL processes 4
)
mysql_list_tables() Deprecated. Lists tables in a MySQL database. Use mysql_query() 3
instead
mysql_num_fields() Returns the number of fields in a recordset 3
mysql_num_rows() Returns the number of rows in a recordset 3
mysql_pconnect() Opens a persistent MySQL connection 3
mysql_ping() Pings a server connection or reconnects if there is no connection 4
mysql_query() Executes a query on a MySQL database 3
mysql_real_escape_st Escapes a string for use in SQL statements 4
ring()
mysql_result() Returns the value of a field in a recordset 3
mysql_select_db() Sets the active MySQL database 3
mysql_stat() Returns the current system status of the MySQL server 4
mysql_tablename() Deprecated. Returns the table name of field. Use mysql_query() 3
instead
mysql_thread_id() Returns the current thread ID 4
mysql_unbuffered_qu Executes a query on a MySQL database (without fetching / buffering 4
ery() the result)

Page 118 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

PHP SimpleXML Functions


PHP: indicates the earliest version of PHP that supports the function.

Function Description PHP

__construct() Creates a new SimpleXMLElement object 5


addAttribute() Adds an attribute to the SimpleXML element 5
addChild() Adds a child element the SimpleXML element 5
asXML() Gets an XML string from a SimpleXML element 5
attributes() Gets a SimpleXML element's attributes 5
children() Gets the children of a specified node 5
getDocNamespaces() Gets the namespaces of an XML document 5
getName() Gets the name of a SimpleXML element 5
getNamespaces() Gets the namespaces from XML data 5
registerXPathNamespace() Creates a namespace context for the next XPath query 5
simplexml_import_dom() Gets a SimpleXMLElement object from a DOM node 5
simplexml_load_file() Gets a SimpleXMLElement object from an XML document 5
simplexml_load_string() Gets a SimpleXMLElement object from an XML string 5
xpath() Runs an XPath query on XML data 5

PHP String Introduction


The string functions allow you to manipulate strings.

Function Description PHP

addcslashes() Returns a string with backslashes in front of the 4


specified characters

addslashes() Returns a string with backslashes in front of 3


predefined characters

bin2hex() Converts a string of ASCII characters to hexadecimal 3


values

chop() Alias of rtrim() 3


chr() Returns a character from a specified ASCII value 3

Page 119 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

chunk_split() Splits a string into a series of smaller parts 3


convert_cyr_string() Converts a string from one Cyrillic character-set to 3
another

convert_uudecode() Decodes a uuencoded string 5


convert_uuencode() Encodes a string using the uuencode algorithm 5
count_chars() Returns how many times an ASCII character occurs 4
within a string and returns the information

crc32() Calculates a 32-bit CRC for a string 4


crypt() One-way string encryption (hashing) 3
echo() Outputs strings 3
explode() Breaks a string into an array 3
fprintf() Writes a formatted string to a specified output stream 5
get_html_translation_table() Returns the translation table used by 4
htmlspecialchars() and htmlentities()

hebrev() Converts Hebrew text to visual text 3


hebrevc() Converts Hebrew text to visual text and new lines (\n) 3
into <br />

html_entity_decode() Converts HTML entities to characters 4


htmlentities() Converts characters to HTML entities 3
htmlspecialchars_decode() Converts some predefined HTML entities to characters 5
htmlspecialchars() Converts some predefined characters to HTML entities 3
implode() Returns a string from the elements of an array 3
join() Alias of implode() 3
levenshtein() Returns the Levenshtein distance between two strings 3
localeconv() Returns locale numeric and monetary formatting 4
information

ltrim() Strips whitespace from the left side of a string 3


md5() Calculates the MD5 hash of a string 3
md5_file() Calculates the MD5 hash of a file 4
metaphone() Calculates the metaphone key of a string 4
money_format() Returns a string formatted as a currency string 4
nl_langinfo() Returns specific local information 4

Page 120 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

nl2br() Inserts HTML line breaks in front of each newline in a string 3


number_format() Formats a number with grouped thousands 3
ord() Returns the ASCII value of the first character of a string 3
parse_str() Parses a query string into variables 3
print() Outputs a string 3
printf() Outputs a formatted string 3
quoted_printable_decod Decodes a quoted-printable string 3
e()

quotemeta() Quotes meta characters 3


rtrim() Strips whitespace from the right side of a string 3
setlocale() Sets locale information 3
sha1() Calculates the SHA-1 hash of a string 4
sha1_file() Calculates the SHA-1 hash of a file 4
similar_text() Calculates the similarity between two strings 3
soundex() Calculates the soundex key of a string 3
sprintf() Writes a formatted string to a variable 3
sscanf() Parses input from a string according to a format 4
str_ireplace() Replaces some characters in a string (case-insensitive) 5
str_pad() Pads a string to a new length 4
str_repeat() Repeats a string a specified number of times 4
str_replace() Replaces some characters in a string (case-sensitive) 3
str_rot13() Performs the ROT13 encoding on a string 4
str_shuffle() Randomly shuffles all characters in a string 4
str_split() Splits a string into an array 5
str_word_count() Count the number of words in a string 4
strcasecmp() Compares two strings (case-insensitive) 3
strchr() Finds the first occurrence of a string inside another string (alias 3
of strstr())

strcmp() Compares two strings (case-sensitive) 3


strcoll() Locale based string comparison 4
strcspn() Returns the number of characters found in a string before any part of 3
some specified characters are found
strip_tags() Strips HTML and PHP tags from a string 3
stripcslashes() Unquotes a string quoted with addcslashes() 4

Page 121 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

stripslashes() Unquotes a string quoted with addslashes() 3


stripos() Returns the position of the first occurrence of a string inside another 5
string (case-insensitive)

stristr() Finds the first occurrence of a string inside another string 3


(case-insensitive)

strlen() Returns the length of a string 3

strnatcasecmp() Compares two strings using a "natural order" algorithm (case-insensitive) 4

strnatcmp() Compares two strings using a "natural order" algorithm (case-sensitive) 4


strncasecmp() String comparison of the first n characters (case-insensitive) 4

strncmp() String comparison of the first n characters (case-sensitive) 4


strpbrk() Searches a string for any of a set of characters 5
strpos() Returns the position of the first occurrence of a string inside another 3
string (case-sensitive)

strrchr() Finds the last occurrence of a string inside another string 3


strrev() Reverses a string 3
strripos() Finds the position of the last occurrence of a string inside another string 5
(case-insensitive)

strrpos() Finds the position of the last occurrence of a string inside another string 3
(case-sensitive)

strspn() Returns the number of characters found in a string that contains only 3
characters from a specified charlist

strstr() Finds the first occurrence of a string inside another string (case-sensitive) 3
strtok() Splits a string into smaller strings 3
strtolower() Converts a string to lowercase letters 3
strtoupper() Converts a string to uppercase letters 3
strtr() Translates certain characters in a string 3
substr() Returns a part of a string 3

substr_compa Compares two strings from a specified start position (binary safe and 5
re() optionally case-sensitive)
substr_count() Counts the number of times a substring occurs in a string 4
substr_replace Replaces a part of a string with another string 4
()

trim() Strips whitespace from both sides of a string 3

Page 122 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

ucfirst() Converts the first character of a string to uppercase 3


ucwords() Converts the first character of each word in a string to uppercase 3
vfprintf() Writes a formatted string to a specified output stream 5
vprintf() Outputs a formatted string 4
vsprintf() Writes a formatted string to a variable 4
wordwrap() Wraps a string to a given number of characters 4

PHP XML Parser Functions

Function Description PHP

utf8_decode() Decodes an UTF-8 string to ISO-8859-1 3


utf8_encode() Encodes an ISO-8859-1 string to UTF-8 3
xml_error_string() Gets an error string from the XML parser 3
xml_get_current_byte_index() Gets the current byte index from the XML parser 3
xml_get_current_column_number() Gets the current column number from the XML parser 3

xml_get_current_line_number() Gets the current line number from the XML parser 3
xml_get_error_code() Gets an error code from the XML parser 3
xml_parse() Parses an XML document 3
xml_parse_into_struct() Parse XML data into an array 3
xml_parser_create_ns() Create an XML parser with namespace support 4
xml_parser_create() Create an XML parser 3
xml_parser_free() Free an XML parser 3
xml_parser_get_option() Get options from an XML parser 3
xml_parser_set_option() Set options in an XML parser 3
xml_set_character_data_handler() Set handler function for character data 3
xml_set_default_handler() Set default handler function 3
xml_set_element_handler() Set handler function for start and end element of 3
elements

xml_set_end_namespace_decl_h Set handler function for the end of namespace 4


andler() declarations

Page 123 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

xml_set_external_entity_ref_han Set handler function for external entities 3


dler()

xml_set_notation_decl_handler() Set handler function for notation declarations 3


xml_set_object() Use XML Parser within an object 4
xml_set_processing_instruction_h Set handler function for processing instruction 3
andler()

xml_set_start_namespace_decl_h Set handler function for the start of namespace 4


andler() declarations

xml_set_unparsed_entity_decl_h Set handler function for unparsed entity declarations 3


andler()

PHP Zip File Functions

Function Description PHP

zip_close() Closes a ZIP file 4


zip_entry_close() Closes an entry in the ZIP file 4
zip_entry_compressedsize() Returns the compressed size of an entry in the ZIP 4
file

zip_entry_compressionmethod() Returns the compression method of an entry in the 4


ZIP file

zip_entry_filesize() Returns the actual file size of an entry in the ZIP file 4
zip_entry_name() Returns the name of an entry in the ZIP file 4
zip_entry_open() Opens an entry in the ZIP file for reading 4
zip_entry_read() Reads from an open entry in the ZIP file 4
zip_open() Opens a ZIP file 4
zip_read() Reads the next entry in a ZIP file 4

Page 124 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

Simple AJAX Example

--------------------AJAX STARTIN----------------

ajax.js

var xmlHttp

function showcontent(str)

// alert(str);

if (str.length==0)

document.getElementById("comment").innerHTML=""

return

xmlHttp=GetXmlHttpObject()

if (xmlHttp==null)

alert ("Browser does not support HTTP Request")

return

var url="destinationajax.php"

url=url+"?comm="+str

xmlHttp.onreadystatechange=stateChanged

xmlHttp.open("GET",url,true)

xmlHttp.send(null)

Page 125 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

function stateChanged()

if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")

document.getElementById("comment").innerHTML=xmlHttp.responseText;

//alert(xmlHttp.responseText);

function GetXmlHttpObject()

var objXMLHttp=null

if (window.XMLHttpRequest)

objXMLHttp=new XMLHttpRequest()

else if (window.ActiveXObject)

objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP")

return objXMLHttp

sourfile.php

<script src="ajax.js"></script>

<form name="frm" method="post" action="">

Page 126 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

<input type="text" name="t1" id="t1">

<input type="button" name="button" id="button" value="Check Available"


onClick="showcontent(frm.t1.value);">

</form>

<span id="comment"></span>

destinationajax.php

<?php

echo $_GET['comm']; // Using Dbase codings

?>

----------AJAX OVER--------------

File Write Program

<?php
$str = "Welcome to PHP File Streams";
$out = fopen("out.txt", "w");
fwrite($out, $str);
fclose($out);
?>

WEB SERVICES
What is a Web Service?

A "web service" is a network accessible interface to application functionality built using XML and
usually HTTP.

Examples

 Where is my FedEx package?


 What is the current stock price of IBM?
 Which kitchen utensils does OXO sell?
Why do we care?
These interfaces work regardless of the client's and server's platform and language.

Standard Setup

 Clients make requests and servers reply


 Communication done over the Internet

Page 127 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

Four Basic Steps


 Web Services client script builds up the request
 Client sends the request to server using HTTP
 Server replies and returns an XML document with results
 Client parses XML
Three forms of Web Services

 SOAP
 XML-RPC
 REST
This talk covers
 SOAP Client
 SOAP Server
 XML-RPC (just a little)
 REST Client
 Querying Amazon.Com
Protocols

Page 128 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

SOAP

 Formerly known as Simple Object Access Protocol.


 Uses XML, but you never need to touch it.
 Which is good, because SOAP is messy to look at.
 You just call functions and manipulate arrays. (Unless you want to.)
 A few PHP implementations: PEAR::SOAP, PHP-SOAP, NuSOAP
 (Dirty little secret: Nobody uses SOAP.)
Load in the SOAP Client

<?php require 'SOAP/Client.php';?>

Generate Client Proxy (for Amazon.Com)

<?php
// We have human readable explanation of the API.
$wsdl_url = 'http://soap.amazon.com/schemas3/AmazonWebServices.wsdl';
$WSDL = new SOAP_WSDL($wsdl_url);
$client = $WSDL->getProxy();
?>

Web Service Description Language (WSDL)

Machine readable description (XML) of a web service. Used here to define server's methods and
parameters.

Make ManufacturerSearchRequest for OXO Kitchen Supplies

<?php
// I love OXO kitchen products
$params = array('manufacturer' => 'oxo',
'mode' => 'kitchen',
'page' => 1,
'type' => 'lite',
'tag' => 'trachtenberg-20',
'devtag' => 'XXXXXX'
);

$hits = $client->ManufacturerSearchRequest($params);
?>

What We Get

<?xml version="1.0" encoding="UTF-8"?>


<SOAP-ENV:Envelope xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" SOAP-
ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-
ENV="http://schemas.xmlsoap.org/soap/envelope/"

Page 129 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:amazon="http://soap.amazon.com">
<SOAP-ENV:Body>
<namesp37:ManufacturerSearchRequestResponse
xmlns:namesp37="http://soap.amazon.com">
<return xsi:type="amazon:ProductInfo">
<TotalResults xsi:type="xsd:string">165</TotalResults>
<Details SOAP-ENC:arrayType="amazon:Details[10]" xsi:type="SOAP-ENC:Array">
<Details xsi:type="amazon:Details">
<Url xsi:type="xsd:string">http://www.amazon.com/...</Url>
<Asin xsi:type="xsd:string">B00004OCKR</Asin>
<ProductName xsi:type="xsd:string">OXO Good Grips Salad Spinner</ProductName>
<Catalog xsi:type="xsd:string">Kitchen</Catalog>
<Manufacturer xsi:type="xsd:string">OXO</Manufacturer>
<ImageUrlSmall xsi:type="xsd:string">http://images.amazon.com/...</ImageUrlSmall>
<ImageUrlMedium
xsi:type="xsd:string">http://images.amazon.com/...</ImageUrlMedium>
<ImageUrlLarge xsi:type="xsd:string">http://images.amazon.com/...</ImageUrlLarge>
<ListPrice xsi:type="xsd:string">$35.00</ListPrice>
<OurPrice xsi:type="xsd:string">$24.95</OurPrice>
</Details>
</Details>
</return>
</namesp37:ManufacturerSearchRequestResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>

What We See

stdClass Object
(
[TotalResults] => 165
[Details] => Array
(
[0] => stdClass Object
(
[Url] => http://www.amazon.com/...
[Asin] => B00004OCKR
[ProductName] => OXO Good Grips Salad Spinner
[Catalog] => Kitchen
[Manufacturer] => OXO
[ImageUrlSmall] => http://images.amazon.com/...
[ImageUrlMedium] => http://images.amazon.com/...
[ImageUrlLarge] => http://images.amazon.com/...
[ListPrice] => $35.00
[OurPrice] => $24.95
)
)
)

Parse the Results

Page 130 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

<?php
foreach ($hits->Details as $hit) {
printf('<p style="clear:both"><img src="%s" alt="%s"
align="left" /><a href="%s">%s</a><br/>%s</p>',
$hit->ImageUrlSmall,
htmlspecialchars($hit->ProductName),
$this->Url, htmlspecialchars($hit->ProductName),
htmlspecialchars($hit->OurPrice)
);
}
?>

Output

HTML

<p style="clear:both"> <img src="http://images.amazon.com/..." alt="OXO Good Grips Salad


Spinner" align="left" /> <a href="http://www.amazon.com/..."> OXO Good Grips Salad
Spinner</a><br/> $24.95 </p>

Page 131 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

<p style="clear:both"> <img src="http://images.amazon.com/..." alt="OXO Steel 6-Piece


Kitchen Essentials Set" align="left" /> <a href="http://www.amazon.com/..."> OXO Steel 6-Piece
Kitchen Essentials Set</a><br/> $49.99</p>

SOAP Server

<?php
require_once 'SOAP/Server.php';

class SOAP_Server_rot13 {
function rotate($input) {
return str_rot13($input);
}
}

$server = new SOAP_Server;


$soapclass = new SOAP_Server_rot13();
// Associate PHP class with SOAP message
$server->addObjectMap($soapclass ,'urn:SOAP_Server_rot13');
$server->service($HTTP_RAW_POST_DATA);
?>

SOAP Client Server

<?php
require_once 'SOAP/Client.php';
$client = new SOAP_Client('http://localhost/rot13.php');

// this namespace is the same as declared earlier


$options = array('namespace' => 'urn:SOAP_Server_rot13');

$rotated_string = $client->call("rotate",
$params = array("input" =>
"Rotate Me!"),
$options);
print $rotated_string;
?>

Results

Ebgngr Zr!

XML-RPC
 XML Remote Procedure Call
 Similar to SOAP, but less complex

Page 132 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

 Which is its biggest advantage


 And its biggest disadvantage
 But it is often "good enough"
 But, SOAP has better buzzword compliance

REST
 REpresentational State Transfer (Roy Fielding)
 Make URI request using existing HTTP methods: GET / POST / PUT / DELETE.
 Data returned as XML, and you do need to touch it.
 Which is good, because it's not complicated.
 Many ways to parse XML: SAX / DOM / XSLT / SimpleXML

Construct Query String

<?php
$url = 'http://xml.amazon.com/onca/xml3?';

$params = array('ManufacturerSearch' => 'oxo',


'mode' => 'kitchen',
'page' => 1,
'type' => 'lite',
'f' => 'xml',
't' => 'trachtenberg-20',
'dev-t' => 'XXXXXXXXXXXXXX',
);
foreach ($params as $a => $v) {
$url .= "$a=$v&";
}
?>
Use cURL to make get request

<?php
$c = curl_init($url);
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
$hits = curl_exec($c);
curl_close($c);
?>

XML Results

<?xml version="1.0" encoding="UTF-8"?>


<ProductInfo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://xml.amazon.com/schemas3/dev-lite.xsd">

<TotalResults>165</TotalResults>
<Details url="http://www.amazon.com/...">
<Asin>B00004OCKR</Asin>
<ProductName>OXO Good Grips Salad Spinner</ProductName>
<Catalog>Kitchen</Catalog>

Page 133 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

<Manufacturer>OXO</Manufacturer>
<ImageUrlSmall>http://images.amazon.com/...</ImageUrlSmall>
<ImageUrlMedium>http://images.amazon.com/...</ImageUrlMedium>
<ImageUrlLarge>http://images.amazon.com/...</ImageUrlLarge>
<ListPrice>$35.00</ListPrice>
<OurPrice>$24.95</OurPrice>
</Details>

<Details url="http://www.amazon.com/...">
...
</Details>

...

</ProductInfo>

Create SAX Parser

<?php $xml = xml_parser_create(); ?>

Instantiate Object

<?php
// code to appear on later...
$obj = new Amazon_parser;
?>

Configure Parser

<?php
xml_set_object($xml, $obj);
xml_set_element_handler($xml, 'start_element', 'end_element');
xml_set_character_data_handler($xml, 'character_data');
xml_parser_set_option($xml, XML_OPTION_CASE_FOLDING, false);
?>

Action!

<?php
xml_parse($xml, $hits);
xml_parser_free($xml);
?>

Parsing Class

<?php
class Amazon_parser {

var $tag;
var $item;

Page 134 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

function start_element($parser, $tag, $attributes) {


...
}

function end_element($parser, $tag) {


...
}

function character_data($parser, $data) {


...
}
}
?>

A new element begins...


<?php
function start_element($parser, $tag, $attributes) {
// Each new item lives inside a Details container
if ('Details' == $tag) {
// Make a new Item
$this->item = new Amazon_item;

// Loop through the attributes


foreach ($attributes as $name => $value) {
if (isset($this->item->$name)) {
$this->item->$name .= trim($value);
}
}
} elseif (!empty($this->item)) {
$this->tag = $tag;
}
}
?>

...in between is data...

<?php
function character_data($parser, $data) {
if (!empty($this->item)) {
// only add pre-declared character data elements
if (isset($this->item->{$this->tag})) {
$this->item->{$this->tag} .= trim($data);
}
}
}
?>

...and then it closes.

Page 135 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

<?php
function end_element($parser, $tag) {
// Each product ends with a closing Details tag
if ('Details' == $tag) {
$this->item->display();
unset($this->item);
}
}
?>

A class for each item

<?php
class Amazon_item {

// attributes and character data fields we want


var $ProductName = '' ;
var $OurPrice = '';
var $url = '';
var $ImageUrlSmall = '';

// same display() as before!


function display() {
printf('<p style="clear:both"><img src="%s" alt="%s"
align="left" /><a href="%s">%s</a><br/>%s</p>',
$this->ImageUrlSmall,
htmlspecialchars($this->ProductName),
$this->url, htmlspecialchars($this->ProductName),
htmlspecialchars($this->OurPrice)
);
}
}

?>

Output

Page 136 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

HTML

<p style="clear:both"> <img src="http://images.amazon.com/..." alt="OXO Good Grips Salad


Spinner" align="left" /> <a href="http://www.amazon.com/exec/..."> OXO Good Grips Salad
Spinner</a><br/> $24.95 </p>
<p style="clear:both"> <img src="http://images.amazon.com/..." alt="OXO Steel 6-Piece
Kitchen Essentials Set" align="left" /> <a href="http://www.amazon.com/..."> OXO Steel 6-Piece
Kitchen Essentials Set</a><br/> $49.99</p>

Resources

This presentation: <a href="http://talks.php.net/show/webservices-


oscon2003">http://talks.php.net/show/webservices-oscon2003</a>
 PHP + SOAP + Amazon <a
href="http://www.onlamp.com/pub/a/php/2003/07/03/php_amazon_soap.html">http://w
ww.onlamp.com/pub/a/php/2003/07/03/php_amazon_soap.html</a>
 PEAR::SOAP <a href="http://pear.php.net/package-
info.php?package=SOAP">http://pear.php.net/package-info.php?package=SOAP</a>
 Shane Carvaeo's SOAP Presentation <a href="http://talks.php.net/show/soap-phpcon-
ny2003/">http://talks.php.net/show/soap-phpcon-ny2003/</a> (Very detailed.)
 <a href="http://www.oreilly.com/catalog/progphp">Programming PHP</a> - Chapter 11
("XML") (Mostly XML-RPC.) <a href="http://www.oreilly.com/catalog/phpckbk">PHP
Cookbook</a> Recipes:
 SOAP: 12.9, 12.10
 XML-RPC: 12.7, 12.8
 Building & Sending HTTP Requests: 8.9, 11.2
 Parsing XML: 12.4, 12.5, 12.6

 XML.com's Web services area: <a


href="http://www.xml.com/webservices/">http://www.xml.com/webservices/</a>

HTACCESS
Example #1:

http://yourdomain.com/xyz.html into
The following converts
http://yourdomain.com/index.php?xyz):

RewriteEngine on
RewriteBase /
RewriteRule ^([a-z]+).html$ /index.php?$1 [R,L]

NOTE: The RewriteBase cannot be empty. It must indicate the base directory or a referring
directory.

Regex Character Definitions for htaccess


#
The # instructs the server to ignore the line. Used for including comments.
[F]
Forbidden: instructs the server to return a 403 Forbidden to the client.
[L]

Page 137 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

Last rule: instructs the server to stop rewriting after the preceding directive is processed.
[N]
Next: instructs Apache to rerun the rewrite rule until all rewriting directives have been
achieved.
[G]
Gone: instructs the server to deliver Gone (no longer exists) status message.
[P]
Proxy: instructs server to handle requests by mod_proxy
[C]
Chain: instructs server to chain the current rule with the previous rule.
[R]
Redirect: instructs Apache to issue a redirect, causing the browser to request the
rewritten/modified URL.
[NC]
No Case: defines any associated argument as case-insensitive. i.e., "NC" = "No Case".
[PT]
Pass Through: instructs mod_rewrite to pass the rewritten URL back to Apache for further
processing.
[OR]
Or: specifies a logical "or" that ties two expressions together such that either one proving
true will cause the associated rule to be applied.
[NE]
No Escape: instructs the server to parse output without escaping characters.
[NS]
No Subrequest: instructs the server to skip the directive if internal sub-request.
[QSA]
Append Query String: directs server to add the query string to the end of the expression
(URL).
[S=x]
Skip: instructs the server to skip the next "x" number of rules if a match is detected.
[E=variable:value]
Environmental Variable: instructs the server to set the environmental variable "variable" to
"value".
[T=MIME-type]
Mime Type: declares the mime type of the target resource.

[]
Specifies a character class, in which any character within the brackets will be a match. e.g.,
[xyz] will match either an x, y, or z.

[]+
Character class in which any combination of items within the brackets will be a match. e.g.,
[xyz]+ will match any number of x‘s, y‘s, z‘s, or any combination of these characters.
[^]
Specifies not within a character class. e.g., [^xyz] will match any character that is neither
x, y, nor z.
[a-z]
a dash (-) between two characters within a character class ([]) denotes the range of
characters between them. e.g., [a-zA-Z] matches all lowercase and uppercase letters from
a to z.
a{n}

Page 138 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

specifies an exact number, n, of the preceding character. e.g., x{3} matches exactly three
x‘s.
a{n,}
specifies n or more of the preceding character. e.g., x{3,} matches three or more x‘s.
a{n,m}
specifies a range of numbers, between n and m, of the preceding character. e.g., x{3,7}
matches three, four, five, six, or seven x‘s.
()
used to group characters together, thereby considering them as a single unit. e.g.,
(perishable)?press will match press, with or without the perishable prefix.
^
denotes the beginning of a regex (regex = regular expression) test string. i.e., begin
argument with the proceeding character.
$
denotes the end of a regex (regex = regular expression) test string. i.e., end argument
with the previous character.
?
declares as optional the preceding character. e.g., monzas? will match monza or monzas,
while mon(za)? will match either mon or monza. i.e., x? matches zero or one of x.
!
declares negation. e.g., ―!string‖ matches everything except ―string‖.
.
a dot (or period) indicates any single arbitrary character.
-
instructs ―not to‖ rewrite the URL, as in ―...domain.com.* - [F]‖.
+
matches one or more of the preceding character. e.g., G+ matches one or more G‘s, while
"+" will match one or more characters of any kind.
*
matches zero or more of the preceding character. e.g., use ―.*‖ as a wildcard.
|
declares a logical ―or‖ operator. for example, (x|y) matches x or y.
\
escapes special characters ( ^ $ ! . * | ). e.g., use ―\.‖ to indicate/escape a literal dot.
\.
indicates a literal dot (escaped).
/*
zero or more slashes.
.*
zero or more arbitrary characters.
^$
defines an empty string.
^.*$
the standard pattern for matching everything.
[^/.]
defines one character that is neither a slash nor a dot.
[^/.]+
defines any number of characters which contains neither slash nor dot.
http://
this is a literal statement — in this case, the literal character string, ―http://‖.
^domain.*
defines a string that begins with the term ―domain‖, which then may be proceeded by any

Page 139 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

number of any characters.


^domain\.com$
defines the exact string ―domain.com‖.
-d
tests if string is an existing directory
-f
tests if string is an existing file
-s
tests if file in test string has a non-zero value

Redirection Header Codes


 301 - Moved Permanently
 302 - Moved Temporarily
 403 - Forbidden
 404 - Not Found
 410 – Gone
 500 – Internal Server Error

Commenting your htaccess Files


# this is a comment

Enable Basic Rewriting


Certain servers may not have ―mod_rewrite‖ enabled by default. To ensure mod_rewrite (basic
rewriting) is enabled throughout your site, add the following line once to your site‘s root htaccess
file:
# enable basic rewriting
RewriteEngine on

Example #1:

http://yourdomain.com/xyz.html into
The following converts
http://yourdomain.com/index.php?xyz):

RewriteEngine on
RewriteBase /
RewriteRule ^([a-z]+).html$ /index.php?$1 [R,L]

NOTE: The RewriteBase cannot be empty. It must indicate the base directory or a referring
directory.

Example #2:

http://yourdomain.com/directory/xyz.html into
The following converts
http://yourdomain.com/directory/index.php?xyz):

RewriteEngine on
RewriteBase /directory
RewriteRule ^([a-z]+).html$ /index.php?$1[R,L]

Page 140 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

Example #3:

The following converts:


http://yourdomain.com/tutorials.php?req=tutorial&id=3&page=0 to
http://yourdomain.com/tutorials/3/0.php:
RewriteEngine On
RewriteRule ^tutorials/(.*)/(.*).php /tutorials.php?req=tutorial&tut_id=$1&page=$2

Example #4:
The following will display contents in newpage.html when visitor browses to oldpage.html:
RewriteEngine on
RewriteRule ^oldpage.html$ /newpage.html

Example #5:

The following will rewrite the URL to http://yourdomain.com/directory/newpage.html


when visitors browse to http://yourdomain.com/anypage.html
RewriteEngine on
RewriteRule ^([a-z]+).html$ /directory/newpage.html[R,NC,L]

Example #6:
Another example of a similar .htaccess file using ip blocking in RewriteCond directive will forward
user to http://www.yahoo.com URL if they come from a specified IP address (eg.
123.45.67.8):
RewriteEngine on
RewriteCond %{REMOTE_ADDR} ^123.45.67.8$
RewriteRule ^(.*)$ http://www.yahoo.com [L]

Example #7:

If you have problems with certain visitors to your website, you can ban them. There are two
different ways to ban visitors: (1) using their IP address they came from or (2) using the domain
name which they came from.
The following example denies a visitor coming from IP address 123.45.67.8:
order allow,deny
deny from 123.45.67.8
allow from all
The following example denies visitors coming from a block of IP addresses coming from
123.45.67.0 to 123.45.67.255
order allow,deny
deny from 123.45.67.
allow from all
The following example denies a user by the domain name from which they came from:
order allow,deny
deny from www.theirdomain.com
allow from all
The following example denies a visitor from a domain name and all subdomains within the domain
name:
order allow,deny
deny from .theirdomain.com
allow from all

Page 141 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

The following example denies all visitors except your own IP address assigned to you by your ISP
(Internet Service Provider):
Order deny,allow
Deny from all
Allow from youripaddress

Example #8:
The following example denies access to all files if the visitor is browsing from IP address
123.45.67.8:
<Files *>
Order allow,deny
Deny from 123.45.67.8
Satisfy All
</Files>

Example #9:
The following example will redirect a user browsing to yourdomain.com to www.yourdomain.com:

RewriteEngine on
RewriteCond %{HTTP_HOST} ^yourdomain.com
RewriteRule ^(.*)$ http://www.yourdomain.com [R=permanent,L]

Multiple Redirects

RewriteRule ^products/([0-9][0-9])/$ /productinfo.php?prodID=$1[R]


If your site visitor had entered something like products/12, the rule above won‘t do a redirect, as
the slash at the end is missing.

Multiple redirects in the same .htaccess file can be applied in sequence, which is what
we‘re doing here. This rule is added before the one we did above, like so:

RewriteRule ^products/([0-9][0-9])$ /products/$1/ [R]

RewriteRule ^products/([0-9][0-9])/$ /productinfo.php?prodID=$1

Thus, if the user types in the URL products/12, our first rule kicks in, rewriting the URL to include
the trailing slash, and doing a new request for products/12/ so the user can see that we likes our
trailing slashes around here. Then the second rule has something to match, and transparently
redirects this URL to productinfo.php?prodID=12.

Redirect everyone to different site except 1 IP


ErrorDocument 403 http://www.htaccesselite.com
Order deny,allow
Deny from all
Allow from 1.1.1.1
Redirect all but 1 IP to different site, using mod_rewrite
RewriteEngine On
RewriteBase /
RewriteCond %{REMOTE_HOST} !^1\.1\.1\.1
RewriteRule .* http://www.htaccesselite.com [R=302,L]

Page 142 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

Set the Timezone of the server


SetEnv TZ America/Indianapolis
SetEnv TZ Australia/Adelaide

SetEnv TZ Europe/London

SetEnv TZ US/Central

SetEnv TZ US/Midwest

Set the Server Administrator Email


Include a link to your email address in Apache-Generated Error Documents. Shows up on default
Apache error pages
ServerSignature EMail
SetEnv SERVER_ADMIN [email protected]

Turn off the ServerSignature


Turns off the address part of your Server Signature (Server Versions and Admin Email ID) in
Apache generated Error Documents.
ServerSignature Off

Set the default language and character set


Here is an easy way to set the default language for pages served by your server (edit the
language to suit your needs):
# set the default language
DefaultLanguage en-US
Likewise, here we are setting the default character set (edit to taste):
# set the default character set
AddDefaultCharset UTF-8
Security

Prevent Access to .htaccess


Add the following code block to your htaccess file to add an extra layer of security. Any attempts
to access the htaccess file will result in a 403 error message. Of course, your first layer of defense
to protect htaccess files involves setting htaccess file permissions via CHMOD to 644:

<Files .htaccess>
order allow,deny
deny from all
</Files>

Prevent Access to a Specific File


To restrict access to a specific file, add the following code block and edit the file name,
―secretfile.jpg‖, with the name of the file that you wish to protect:

<files secretfile.jpg>
order allow,deny
deny from all
</files>

Page 143 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

Prevent access to multiple file types


To restrict access to a variety of file types, add the following code block and edit the file types
within parentheses to match the extensions of any files that you wish to protect:
<FilesMatch "\.(htaccess|htpasswd|ini|phps|fla|psd|log|sh)$">
Order Allow,Deny
Deny from all
</FilesMatch>

Change Default Index Page


This rule tells the server to search for and serve ―business.html‖ as the default directory index.
This rule must exist in the htaccess files of the root directory for which you wish to replace the
default index file (e.g., ―index.html‖):
DirectoryIndex business.html

Automatically CHMOD Various File Types


chmod .htpasswd files 640
chmod .htaccess files 644
chmod php files 600

irect from http://old-domain.com to http://new-domain.com

For a basic domain change from ―old-domain.com‖ to ―new-domain.com‖ (and folder/file names
have not been changed), use the Rewrite rule to remap the old domain to the new domain. When
checking the redirect live, the old domain may appear in the browser‘s address bar. Simply check
an image path (right-click an image and select ―properties‖) to verify proper redirection.
Remember to check your site thoroughly after implementing this redirect.
# redirect from old domain to new domain
RewriteEngine On
RewriteRule ^(.*)$ http://www.new-domain.com/$1 [R=301,L]

If you want to continue global variables


php_flag register_globals On

For Example:- You can change from 2M to 50m. You will probably also need to increase the
max_execution_time for files of that size.
php_value upload_max_filesize 50M
php_value max_execution_time 800
php_value memory_limit 250M

php_value session.use_only_cookies 0

session.use_only_cookies specifies whether the module will only use cookies to store the
session id on the client side. Enabling this setting prevents attacks involved passing session ids in
URLs. This setting was added in PHP 4.3.0. Defaults to 1 (enabled) since PHP 6.0.

php_value session.cache_expire 180


session.cache_expire specifies time-to-live for cached session pages in minutes, this has
no effect for nocache limiter. Defaults to 180. See also

php_value session.gc_maxlifetime 10800

session.gc_maxlifetime specifies the number of seconds after which data will be seen as 'garbage'

Page 144 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

and cleaned up. Garbage collection occurs during session start.

php_value session.save_path "/local/web/websites/nl.propertyalert.org/livesession"

php_value display_errors On

AllowOverride None
AllowOverride is set to allow the use of .htaccess files, Apache will look in every directory
for .htaccess files. Thus, permitting .htaccess files causes a performance hit, whether or not you
actually even use them! Also, the .htaccess file is loaded every time a document is requested.

Bidcrown Site:-
RewriteEngine on
php_flag magic_quotes_gpc on

Clubeternal.biz:-
http://www.clubeternal.biz/index.php?membername
http://www/clubeternal.biz/membername

RewriteEngine on
RewriteRule ^([a-z,0-9]+)$ /index.php?$1

http://www.webmaster-toolkit.com

Change the File extension with your desired extension with .htaccess

Options +FollowSymLinks
RewriteEngine on
RewriteRule ^(.*)\.ram$ $1.php [nc]

get a Difference between two dates

function dateDiff($dformat, $endDate, $beginDate)


{
$date_parts1=explode($dformat, $beginDate);
$date_parts2=explode($dformat, $endDate);
$start_date=gregoriantojd($date_parts1[0], $date_parts1[1], $date_parts1[2]);
$end_date=gregoriantojd($date_parts2[0], $date_parts2[1], $date_parts2[2]);
return $end_date - $start_date;
}

// Example 2008-01-25

echo dateDiff(―-‖, ―2008-01-25‖, ―2008-01-10‖);

LTrim, RTrim and Trim functions in javascript

// Removes leading whitespaces


function LTrim( value ) {

var re = /\s*((\S+\s*)*)/;
return value.replace(re, "$1");

Page 145 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

// Removes ending whitespaces


function RTrim( value ) {

var re = /((\s*\S+)*)\s*/;
return value.replace(re, "$1");

// Removes leading and ending whitespaces


function trim( value ) {

return LTrim(RTrim(value));

function test()
{
var a = "sample ";
alert(trim(a));
}

use this function for cut the whole words and display all words .

function str_split1($content,$s = 20)


{

$temp = '';
$l = strlen($content);
for($i=0;$i<$l;$i = $i+$s)
{
$temp = $temp.substr($content,$i,$s).'<br>';
}
return $temp;
}

Email ID Validation with regular expression

<?php
// Function used to check e-mail syntax
function validateEmail($email)
{
// Create the e-mail validation regular expression
$regexp = "^([_a-z0-9-]+)(\.[_a-z0-9-]+)*@([a-z0-9-]+)(\.[a-z0-9-]+)*(\.[a-z]{2,6})$";
// Validate the syntax
if (eregi($regexp, $email)) return 1;
else return 0;
}
// Has the form been submitted?

Page 146 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

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

$name = htmlentities($_POST['name']);
$email = htmlentities($_POST['email']);
printf("Hi %s<br />", $name);
if (validateEmail($email))
printf("The address %s is valid!", $email);
else
printf("The address <strong>%s</strong> is invalid!", $email);
}
?>
<form action="subscribe.php" method="post">
<p>
Name:<br />
<input type="text" id="name" name="name" size="20" maxlength="40" />
</p>
<p>
E-mail address:<br />
<input type="text" id="email" name="email" size="20" maxlength="40" />
</p>
<input type="submit" id="submit" name = "submit" value="Go!" />
</form>

array array_change_key_case ( array $input [, int $case ] )

Returns an array with all keys from input lowercased or uppercased. Numbered indices are left as
is.

array array_chunk ( array $input , int $size [, bool $preserve_keys ] )


Chunks an array into size large chunks. The last chunk may contain less than size elements.
array array_combine ( array $keys , array $values )

Creates an array by using the values from the keys array as keys and the values from the values
array as the corresponding values.
array array_count_values ( array $input )
array_count_values() returns an array using the values of the input array as keys and their
frequency in input as values.
array array_diff_assoc ( array $array1 , array $array2 [, array $... ] )

Compares array1 against array2 and returns the difference. Unlike array_diff() the array keys
are used in the comparision.
array array_diff_key ( array $array1 , array $array2 [, array $... ] )
Compares the keys from array1 against the keys from array2 and returns the difference. This
function is like array_diff() except the comparison is done on the keys instead of the values.
array array_diff_uassoc ( array $array1 , array $array2 [, array $... ], callback
$key_compare_func )

Compares array1 against array2 and returns the difference. Unlike array_diff() the array keys

Page 147 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

are
used in the comparision.

Unlike array_diff_assoc() an user supplied callback function is used for the indices
comparision, not internal function.
array array_diff_ukey ( array $array1 , array $array2 [, array $ ... ], callback
$key_compare_func )
Compares the keys from array1 against the keys from array2 and returns the difference. This
function is like array_diff() except the comparison is done on the keys instead of the values.

Unlike array_diff_key() an user supplied callback function is used for the indices comparision,
not internal function.
array array_diff ( array $array1 , array $array2 [, array $ ... ] )
Compares array1 against array2 and returns the difference.
array array_fill_keys ( array $keys , mixed $value )
Fills an array with the value of the value parameter, using the values of the keys array as keys.
array array_fill ( int $start_index , int $num , mixed $value )
Fills an array with num entries of the value of the value parameter, keys starting at the
start_index parameter.
array array_filter ( array $input [, callback $callback ] )
Iterates over each value in the input array passing them to the callback function. If the callback
function returns true, the current value from input is returned into the result array. Array keys are
preserved.
array array_flip ( array $trans )

array_flip() returns an array in flip order, i.e. keys from trans become values and values from
trans become keys.

array array_intersect_assoc ( array $array1 , array $array2 [, array $ ... ] )


array_intersect_assoc() returns an array containing all the values of array1 that are present in
all the arguments. Note that the keys are used in the comparison unlike in array_intersect().
array array_intersect_key ( array $array1 , array $array2 [, array $ ... ] )
array_intersect_key() returns an array containing all the values of array1 which have matching
keys that are present in all the arguments.
array array_intersect_uassoc ( array $array1 , array $array2 [, array $ ... ], callback
$key_compare_func )
array_intersect_uassoc() returns an array containing all the values of array1 that are present
in all the arguments. Note that the keys are used in the comparison unlike in array_intersect().

array array_intersect_ukey ( array $array1 , array $array2 [, array $... ], callback


$key_compare_func )array_intersect_ukey() returns an array containing all the values of
array1 which have matching keys that are present in all the arguments.

Page 148 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

array array_intersect ( array $array1 , array $array2 [, array $ ... ] )

array_intersect() returns an array containing all the values of array1 that are present in all the
arguments. Note that keys are preserved.

bool array_key_exists ( mixed $key , array $search )


array_key_exists() returns TRUE if the given key is set in the array. key can be any value
possible for an array index. array_key_exists() also works on objects.
array array_keys ( array $input [, mixed $search_value [, bool $strict ]] )
array_keys() returns the keys, numeric and string, from the input array.
array array_map ( callback $callback , array $arr1 [, array $... ] )

array_map() returns an array containing all the elements of arr1 after applying the callback
function to each one. The number of parameters that the callback function accepts should match
the number of arrays passed to the array_map()
array array_merge_recursive ( array $array1 [, array $... ] )
array_merge_recursive() merges the elements of one or more arrays together so that the
values of one are appended to the end of the previous one. It returns the resulting array.

array array_merge ( array $array1 [, array $array2 [, array $... ]] )


array_merge() merges the elements of one or more arrays together so that the values of one
are appended to the end of the previous one. It returns the resulting array.
bool array_multisort ( array $ar1 [, mixed $arg [, mixed $... [, array $... ]]] )

Returns TRUE on success or FALSE on failure. array_multisort() can be used to sort several
arrays at once, or a multi-dimensional array by one or more dimensions.

Associative (string) keys will be maintained, but numeric keys will be re-indexed.
array array_pad ( array $input , int $pad_size , mixed $pad_value )
array_pad() returns a copy of the input padded to size specified by pad_size with value
pad_value . If pad_size is positive then the array is padded on the right, if it's negative then on
the left. If the absolute value of pad_size is less than or equal to the length of the input then no
padding takes place. It is possible to add most 1048576 elements at a time.
mixed array_pop ( array &$array )
array_pop() pops and returns the last value of the array , shortening the array by one element.
If array is empty (or is not an array), NULL will be returned.
number array_product ( array $array )
array_product() returns the product of values in an array as an integer or float.

int array_push ( array &$array , mixed $var [, mixed $... ] )

Page 149 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

array_push() treats array as a stack, and pushes the passed variables onto the end of array .
The length of array increases by the number of variables pushed. Has the same effect as:
mixed array_rand ( array $input [, int $num_req ] )
array_rand() is rather useful when you want to pick one or more random entries out of an array.
It takes an input array and an optional argument num_req which specifies how many entries you
want to pick - if not specified, it defaults to 1.
mixed array_reduce ( array $input , callback $function [, int $initial ] )
array_reduce() applies iteratively the function function to the elements of the array input , so as
to reduce the array to a single value. If the optional initial is available, it will be used at the
beginning of the process, or as a final result in case the array is empty. If the array is empty and
initial is not passed, array_reduce() returns NULL.
array array_reverse ( array $array [, bool $preserve_keys ] )
array_reverse() takes input array and returns a new array with the order of the elements
reversed, preserving the keys if preserve_keys is TRUE.
mixed array_search ( mixed $needle , array $haystack [, bool $strict ] )
Searches haystack for needle and returns the key if it is found in the array, FALSE otherwise.
mixed array_shift ( array &$array )
array_shift() shifts the first value of the array off and returns it, shortening the array by one
element and moving everything down. All numerical array keys will be modified to start counting
from zero while literal keys won't be touched. If array is empty (or is not an array), NULL will be
returned.
array array_slice ( array $array , int $offset [, int $length [, bool $preserve_keys ]] )
array_slice() returns the sequence of elements from the array array as specified by the offset
and lengthparameters.
array array_splice ( array &$input , int $offset [, int $length [, array $replacement ]] )
array_splice() removes the elements designated by offset and length from the input array, and
replaces them with the elements of the replacement array, if supplied. It returns an array
containing the extracted elements. Note that numeric keys in input are not preserved
number array_sum ( array $array )
array_sum() returns the sum of values in an array as an integer or float.
array array_udiff_assoc ( array $array1 , array $array2 [, array $ ... ], callback
$data_compare_func )

array_udiff_assoc() returns an array containing all the values from array1 that are not present
in any of the other arguments. Note that the keys are used in the comparison unlike array_diff()
and array_udiff(). The comparison of arrays' data is performed by using an user-supplied
callback. In this aspect the behaviour is opposite to the behaviour of array_diff_assoc() which
uses internal function for comparison.
array array_udiff_uassoc ( array $array1 , array $array2 [, array $ ... ], callback
$data_compare_func , callback $key_compare_func )
array_udiff_uassoc — Computes the difference of arrays with additional index check, compares
data and indexes by a callback function

Page 150 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

array array_udiff ( array $array1 , array $array2 [, array $ ... ], callback $data_compare_func )
array_udiff — Computes the difference of arrays by using a callback function for data comparison

array array_uintersect_assoc ( array $array1 , array $array2 [, array $ ... ], callback


$data_compare_func )

array array_uintersect_uassoc ( array $array1 , array $array2 [, array $ ... ], callback


$data_compare_func , callback $key_compare_func )
array_uintersect_uassoc — Computes the intersection of arrays with additional index check,
compares data and indexes by a callback functions

array_uintersect — Computes the intersection of arrays, compares data by a callback function


array array_uintersect ( array $array1 , array $array2 [, array $ ... ], callback
$data_compare_func )

array array_unique ( array $array )

array_unique() takes input array and returns a new array without duplicate values.

array_unshift — Prepend one or more elements to the beginning of an array int


array_unshift ( array &$array , mixed $var [, mixed $... ] )

array array_values ( array $input )


array_values() returns all the values from the input array and indexes numerically the
array.array_walk_recursive — Apply a user function recursively to every member of an array
bool array_walk_recursive ( array &$input , callback $funcname [, mixed $userdata ] )

bool array_walk ( array &$array , callback $funcname [, mixed $userdata ] )


array_walk — Apply a user function to every member of an array

bool arsort ( array &$array [, int $sort_flags ] )This function sorts an array such that array
indices maintain their correlation with the array elements they are associated with. This is used
mainly when sorting associative arrays where the actual element order is significant.

bool asort ( array &$array [, int $sort_flags ] )This function sorts an array such that array indices
maintain their correlation with the array elements they are associated with. This is used mainly
when sorting associative arrays where the actual element order is significant.

array compact ( mixed $varname [, mixed $... ] )compact() takes a variable number of
parameters. Each parameter can be either a string containing the name of the variable, or an
array of variable names. The array can contain other arrays of variable names inside it;
compact() handles it recursively. mixed current ( array &$array )Every array has an internal
pointer to its "current" element, which is initialized to the first element inserted into the array.
array each ( array &$array )Returns the current key and value pair from the array array and
advances the array cursor. This pair is returned in a four-element array, with the keys 0, 1, key,
and value. Elements 0 and key contain the key name of the array element, and 1 and value
contain the data. mixed end ( array &$array )end() advances array 's internal pointer to the last
element, and returns its value.

Page 151 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

int extract ( array $var_array [, int $extract_type [, string $prefix ]] )This function is used to
import variables from an array into the current symbol table. It takes an associative array
var_array and treats keys as variable names and values as variable values. For each key/value
pair it will create a variable in the current symbol table, subject to extract_type and prefix
parameters. bool in_array ( mixed $needle , array $haystack [, bool $strict ] )Searches haystack
for needle and returns TRUE if it is found in the array, FALSE otherwise.
mixed key ( array &$array )key() returns the index element of the current array position.

bool krsort ( array &$array [, int $sort_flags ] )Sorts an array by key in reverse order,
maintaining key to data correlations. This is useful mainly for associative arrays.

bool ksort ( array &$array [, int $sort_flags ] )Sorts an array by key, maintaining key to data
correlations. This is useful mainly for associative arrays.

void list ( mixed $varname , mixed $... )Like array(), this is not really a function, but a
language construct. list() is used to assign a list of variables in one operation.

bool natcasesort ( array &$array )This function implements a sort algorithm that orders
alphanumeric strings in the way a human being would while maintaining key/value associations.
This is described as a "natural ordering".

natsort — Sort an array using a "natural order" algorithmbool natsort ( array &$array )
This function implements a sort algorithm that orders alphanumeric strings in the way a human
being would while maintaining key/value associations. This is described as a "natural ordering". An
example of the difference between this algorithm and the regular computer string sorting
algorithms (used in sort()) can be seen below:

mixed next ( array &$array )Returns the array value in the next place that's pointed to by the
internal array pointer, or FALSE if there are no more elements.pos — Alias of current()This
function is an alias of: current() mixed prev ( array &$array )Returns the array value in the
previous place that's pointed to by the internal array pointer, or FALSE if there are no more
elements. array range ( mixed $low , mixed $high [, number $step ] )range() returns an array
of elements from low to high , inclusive. If low > high, the sequence will be from high to low.

mixed reset ( array &$array )reset() rewinds array 's internal pointer to the first element and
returns the value of the first array element, or FALSE if the array is empty.

bool rsort ( array &$array [, int $sort_flags ] )This function sorts an array in reverse order
(highest to lowest).

bool shuffle ( array &$array )


This function shuffles (randomizes the order of the elements in) an array. bool sort ( array
&$array [, int $sort_flags ] )This function sorts an array. Elements will be arranged from lowest to

Page 152 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

highest when this function has completed.


uasort — Sort an array with a user-defined comparison function and maintain index
associationbool uasort ( array &$array , callback $cmp_function )bool uksort ( array &$array ,
callback $cmp_function )uksort() will sort the keys of an array using a user-supplied comparison
function. If the array you wish to sort needs to be sorted by some non-trivial criteria, you should
use this function.

bool usort ( array &$array , callback $cmp_function )This function will sort an array by its values
using a user-supplied comparison function. If the array you wish to sort needs to be sorted by
some non-trivial criteria, you should use this function. sizeof — Alias of count()This function is an
alias of: count().
<xmp> tag

The <xmp> tag is used to display the entire html designed page in a text format. Delimiter syntax
is : <xmp> your html codes here </xmp>

Hide the IE javascript errors on the status bar left side

<script type="text/javascript">
window.onerror =function handleError(){ return true;};
</script>

How to make a download page in own site, which i can know that how many file has
been loaded by particular user or particular ipaddress

header("Content-Disposition: attachment; filename=".$file_name1); header("Content-type:


application/octet-stream"); readfile($file_path1);

Remove HTML codes

$description = preg_replace("/<.*?>/", "", $description);

Get Browser Name and Version in JavaScript

var browser = navigator.appName;


var b_version = navigator.appVersion;
var version = parseFloat(b_version);
alert(browser);
alert(version);

Get form attributes with IE support

<html>
<head>
<script>
function alert_stat()
{
var f = document.getElementById("f");
var a = "";
a += "form.method = " + f.method + "\n\r\n\r";

Page 153 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

a += "form.action = " + f.action + "\n\r";


a += "form.action.value = " + f.action.value + "\n\r\n\r";
a += "form.getAttribute('action') = " + f.getAttribute('action') + "\n\r";
a += "form.getAttribute('action').value = " + f.getAttribute('action').value + "\n\r\n\r";
a += "form.attributes['action'] = " + f.attributes['action'] + "\n\r";
a += "form.attributes['action'].value = " + f.attributes['action'].value + "\n\r\n\r";
a += "form.getAttributeNode('action') = " + f.getAttributeNode('action') + "\n\r";
a += "form.getAttributeNode('action').value = " + f.getAttributeNode('action').value +
"\n\r\n\r";
a += "form.getAttribute('customName') = " + f.getAttribute('customName') + "\n\r";
a += "form.getAttribute('customName').value = " + f.getAttribute('customName').value +
"\n\r";
alert(a);
}
</script>
</head>
<body>
<form action="sample.html" id="f" customName="value of form's custom attribute"
method='post'>
<input name="action" value="value of input (name='action')" />
<input name="customName" value="value of input (name='cusomName') ">
</form>
<input type='button' onClick="javascript:alert_stat()" value='click me'>
</body>
</html>

XML Parsing
userdetail.xml file structure

<?xml version="1.0" encoding="UTF-8"?>


<totalitem>
<item>
<userlist>
<user name="cHJlbWt1bWFy"/>
<user emailid="cHJlbWt1bWFyLmFAYWpzcXVhcmUuY29t"/>
<user password="eWFtYWhh"/>
<user username="a3VtYXJkZXNr"/>
<user userid="NQ=="/>
<user noofstaff="Ng=="/>
<user dbsize="NSBHQg=="/>
<user nooffilesize="NSBHQg=="/>
</userlist>
</item>
</totalitem>

XML Parsing with PHP (Edit, Remove the existing node attribute values and Add a new
Node and attribute)

<?php
$file = "userdetail.xml";
$fp = fopen($file, "rb") or die("cannot open file");
$str = fread($fp, filesize($file));

Page 154 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

$xml = new DOMDocument();


$xml->formatOutput = true;
$xml->preserveWhiteSpace = false;
$xml->loadXML($str) or die("Error");

// original
//echo "<xmp>OLD:\n". $xml->saveXML() ."</xmp>";

// get document element


$root = $xml->documentElement;
$fnode = $root->firstChild;
$xmlobj = simplexml_load_file("userdetail.xml");
for($i=0;$i<count($xmlobj->item->userlist);$i++)
{

if(base64_decode($xmlobj->item->userlist[$i]->user[3][username][0]) ==
―Node exising username value‖)
{

$ori = $fnode->childNodes->item(0);

$id1 = $xml->createElement("user");
//$book->appendChild($id1);
$id12 = $xml->createAttribute("name");
$id1->appendChild($id12);
$namevalue = $xml->createTextNode($xmlobj->item->userlist[$i]-
>user[0][name][0]);
$id12->appendChild($namevalue);

$id2 = $xml->createElement("user");
//$book->appendChild($id2);
$id22 = $xml->createAttribute("emailid");
$id2->appendChild($id22);
$emailvalue = $xml->createTextNode($xmlobj->item->userlist[$i]-
>user[1][emailid][0]);
$id22->appendChild($emailvalue);

$id3 = $xml->createElement("user");
//$book->appendChild($id3);
$id33 = $xml->createAttribute("password");
$id3->appendChild($id33);
$passvalue = $xml->createTextNode($xmlobj->item->userlist[$i]-
>user[2][password][0]);
$id33->appendChild($passvalue);

$id4 = $xml->createElement("user");
//$book->appendChild($id4);
$id44 = $xml->createAttribute("username");
$id4->appendChild($id44);
$uservalue = $xml->createTextNode($xmlobj->item->userlist[$i]-
>user[3][username][0]);

Page 155 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

$id44->appendChild($uservalue);

$id5 = $xml->createElement("user");
//$book->appendChild($id5);
$id55 = $xml->createAttribute("userid");
$id5->appendChild($id55);
$idvalue = $xml->createTextNode($xmlobj->item->userlist[$i]-
>user[4][userid][0]);
$id55->appendChild($idvalue);

$id6 = $xml->createElement("user");
//$book->appendChild($id6);
$id66 = $xml->createAttribute("noofstaff");
$id6->appendChild($id66);
$nostaff = $xml->createTextNode($noofstaffvalue);
$id66->appendChild($nostaff);

$title = $xml->createElement("user");
//$book->appendChild($title);
$title1 = $xml->createAttribute("dbsize");
$title->appendChild($title1);
$dbvalue = $xml->createTextNode($dbsizevalue);
$title1->appendChild($dbvalue);

$author = $xml->createElement("user");
//$book->appendChild($author);
$author1 = $xml->createAttribute("nooffilesize");
$author->appendChild($author1);

$sizevalue = $xml->createTextNode($filesizevalue);
$author1->appendChild($sizevalue);

$book = $xml->createElement("userlist");
$book->appendChild($id1);
$book->appendChild($id2);
$book->appendChild($id3);
$book->appendChild($id4);
$book->appendChild($id5);
$book->appendChild($id6);
$book->appendChild($title);
$book->appendChild($author);
$fnode->replaceChild($book,$ori);
// $xml->saveXML();
}
}

@exec("chmod 777 userdetail.xml");


$fp = @fopen("userdetail.xml","w");
@fwrite($fp,$xml->saveXML());
fclose($fp);

Page 156 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

?>

Find the File Size code in PHP

function file_size_info($filesize) // $fileseze argument is a file path


{
$bytes = array('KB', 'KB', 'MB', 'GB', 'TB'); # values are always displayed
if ($filesize < 1024) $filesize = 1; # in at least kilobytes.
for ($i = 0; $filesize > 1024; $i++) $filesize /= 1024;
$file_size_info['size'] = ceil($filesize);
$file_size_info['type'] = $bytes[$i];
//print_r($file_size_info);exit;
return $file_size_info;
}

Find the Folder Size code in PHP

function folder_size_info()
{

$folder ="foldername"; // folder name with folder path. Except the end ‗/‘ slash
$ filesize = exec("du -s -k $folder"); //summary
$bytes = array('KB', 'KB', 'MB', 'GB', 'TB'); # values are always displayed
if ($filesize < 1024) $filesize = 1; # in at least kilobytes.
for ($i = 0; $filesize > 1024; $i++)
{
$filesize /= 1024;
}
$file_size_info['size'] = number_format($filesize,2);
$file_size_info['type'] = $bytes[$i+1];
//print_r($file_size_info);exit;
return $file_size_info;
}

How many types of ready states in AJAX?

5 ready states
1. Uninitialized
2. Loading
3. Loaded
4. Interactive
5. Complete
Introduction

Thus far when retrieving stored data we have simply displayed the results of any query. MySQL
can do more that this and has many built in functions that can transform data to meet our
requirements. These include:

 Date Functions - used to manipulate the display format of a date as well as calculate
time.

 String Functions - can manipulate a text string

Page 157 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

 Numeric Functions - can manipulate figures

 Summarising Functions - output meta results from a query

There are also Control Functions that can be used to give conditionality to queries.

Date Functions

Before looking at the date functions in detail it is worth revisiting the various date datatypes to
gain a better understanding of the limitations of date formatting.

Date Datatypes

There are 5 MySQL date datatypes these are:

Datatype Format Info


DATETIME YYYY-MM-DD HH:MM:SS This stores both date and time.
DATE YYYY-MM-DD This only stores the date
TIMESTAMP(length) Varies See Below
TIME HH:MM:SS This stores only the time
YEAR YYYY Stores only the year

The timestamp datatype is somewhat different as it stores the time that a row was last changed.
The format also varies according to the length. For example to store the same information as
DATETIME, you would specify a length of 14 whereas to store the DATE you would specify a length
of 8.

Timestamp
Format
Definition
TIMESTAMP(2) YY
TIMESTAMP(4) YYYY
TIMESTAMP(6) YYMMDD
TIMESTAMP(8) YYYYMMDD
TIMESTAMP(10) YYMMDDHHMM
TIMESTAMP(12) YYMMDDHHMMSS
TIMESTAMP(14) YYYYMMDDHHMMSS

In the 'cds' table we have used the DATE for the 'bought' field.
mysql> SELECT cds.title, cds.bought
-> FROM cds;
+------------------------------+------------+
| title | bought |
+------------------------------+------------+
| A Funk Odyssey | 2001-10-10 |
| Now 49 | 2001-10-15 |
| Eurovision Song contest 2001 | 2000-09-08 |
| Abbas Greatest Hits | 2000-11-05 |
| Space Cowboy | 2001-10-10 |
| Sign of the times | 1987-11-07 |
| The White Album | 1994-07-20 |

Page 158 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

| The Hits | 1993-10-07 |


| westlife | 2000-06-09 |
+------------------------------+------------+
9 rows in set (0.02 sec)
So to begin with let's look at how we can manipulate these dates using MySQL's date functions.

DATE_FORMAT()

This function allows the developer to format the date anyway that they wish by specifying a
sequence of format strings. A string is composed of the percentage symbol '%' followed by a
letter that signifies how you wish to display part of the date. These are some of the more common
strings to use:

String Displays Example


%d The numeric day of the month 01....10....17....24 etc
The day of the month with a
%D 1st, 2nd, 3rd.... etc
suffix
%m The numeric month 01....04....08....11 etc
%M The Month name January....April....August etc
%b The Abbreviated Month Name Jan....Apr....Aug....Nov etc
%y Two digit year 98, 99, 00, 01, 02, 03 etc
%Y Four digit year 1998, 2000, 2002, 2003 etc
Monday.... Wednesday....Friday
%W Weekday name
etc
%a Abbreviated Weekday name Mon....Wed....Fri etc
%H Hour (24 hour clock) 07....11....16....23 etc
%h Hour (12 hour clock) 07....11....04....11 etc
%p AM or PM AM....PM
%i Minutes 01....16....36....49 etc
%s Seconds 01....16....36....49 etc

There are more, but that should be enough for now. There are a couple of things to note. Upper
and Lowercase letters in the string make a difference and also that when arranging these strings
into a sequence you can intersperse 'normal' characters. For example:

The sequence '%d/%m/%y', with forward slashes separating the strings, would be displayed as
01/06/03.

The next stage is to use the function DATE_FORMAT() to convert a stored time to a format we
want.

Syntax:
DATE_FORMAT(date, sequence)
Thus to change the format of the cds.bought field to DD-MM-YYYY we specify the field as the
date and the sequence as '%d-%m-%Y'.
DATE_FORMAT(cds.bought, '%d-%m-%Y')
This function is then incorporated into our SQL statement in place of the exiting cds.bought field.

Page 159 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

mysql> SELECT cds.title, DATE_FORMAT(cds.bought, '%d-%m-%Y')


-> FROM cds;
+------------------------------+-------------------------------------+
| title | DATE_FORMAT(cds.bought, '%d-%m-%Y') |
+------------------------------+-------------------------------------+
| A Funk Odyssey | 10-10-2001 |
| Now 49 | 15-10-2001 |
| Eurovision Song contest 2001 | 08-09-2000 |
| Abbas Greatest Hits | 05-11-2000 |
| Space Cowboy | 10-10-2001 |
| Sign of the times | 07-11-1987 |
| The White Album | 20-07-1994 |
| The Hits | 07-10-1993 |
| westlife | 09-06-2000 |
+------------------------------+-------------------------------------+
9 rows in set (0.00 sec)
Dates can also be formatted in 'plain english'.
mysql> SELECT cds.title, DATE_FORMAT(cds.bought, '%W the %D of %M %Y')
-> FROM cds;
+------------------------------+-----------------------------------------------+
| title | DATE_FORMAT(cds.bought, '%W the %D of %M %Y') |
+------------------------------+-----------------------------------------------+
| A Funk Odyssey | Wednesday the 10th of October 2001 |
| Now 49 | Monday the 15th of October 2001 |
| Eurovision Song contest 2001 | Friday the 8th of September 2000 |
| Abbas Greatest Hits | Sunday the 5th of November 2000 |
| Space Cowboy | Wednesday the 10th of October 2001 |
| Sign of the times | Saturday the 7th of November 1987 |
| The White Album | Wednesday the 20th of July 1994 |
| The Hits | Thursday the 7th of October 1993 |
| westlife | Friday the 9th of June 2000 |
+------------------------------+-----------------------------------------------+
9 rows in set (0.01 sec)
Note: DATE_FORMAT() only works with datatypes that include the date. This means DATE,
DATETIME and TIMESTAMP. There is a similar function called TIME_FORMAT() that works with
TIME as well as DATETIME and TIMESTAMP.

Extraction Functions

As well as using DATE_FORMAT() there are other functions that allow you to extract specific
information about a date (year, month, day etc). These include:

Function Displays Example


The numeric day of the
DAYOFMONTH(date) 01....10....17....24 etc
month
Monday.... Wednesday....Friday
DAYNAME(date) The Name of the day
etc
MONTH(date) The numeric month 01....04....08....11 etc
MONTHNAME(date) The Month name January....April....August etc
YEAR(date) Four digit year 1998, 2000, 2002, 2003 etc

Page 160 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

HOUR(time) Hour (24 hour clock) 07....11....16....23 etc


MINUTE(time) Minutes 01....16....36....49 etc
SECOND(time) Seconds 01....16....36....49 etc
DAYOFYEAR(date) Numeric day of the year 1.....366

To give an example of one of these you can use DAYNAME() to work out which day you were born
on. To do this you can specify the date directly to the function without referring to any tables or
field. So for my birthday (20th July 1973):
mysql> SELECT DAYNAME('1973-07-20');
+-----------------------+
| DAYNAME('1973-07-20') |
+-----------------------+
| Friday |
+-----------------------+
1 row in set (0.00 sec)
Or you could even SELECT two or three date items.
mysql> SELECT DAYNAME('1973-07-20'), MONTHNAME('1973-07-20'), YEAR('1973-07-20');
+-----------------------+-------------------------+--------------------+
| DAYNAME('1973-07-20') | MONTHNAME('1973-07-20') | YEAR('1973-07-20') |
+-----------------------+-------------------------+--------------------+
| Friday | July | 1973 |
+-----------------------+-------------------------+--------------------+
1 row in set (0.02 sec)
Getting the Current Date and Time

There are three functions that you can use to get the current date and time. NOW() - which gets
both date and time, CURDATE() which works with only the date and CURTIME() for the time.
mysql> SELECT NOW(), CURTIME(), CURDATE();
+---------------------+-----------+------------+
| NOW() | CURTIME() | CURDATE() |
+---------------------+-----------+------------+
| 2003-06-02 19:44:51 | 19:44:51 | 2003-06-02 |
+---------------------+-----------+------------+
1 row in set (0.01 sec)
Changing Date Values

There are two functions that allow you to add and subtract time to a date. These are DATE_ADD()
and DATE_SUB().

Syntax:
DATE_ADD(date,INTERVAL expr type)
DATE_SUB(date,INTERVAL expr type)
The date - is a standard DATE or DATETIME value, next come the command INTERVAL followed
by the time period (expr) and finally what type period it is (Month, Day, Year etc). Therefore to
work out the date 60 days in the future:
mysql> SELECT DATE_ADD(CURDATE(), INTERVAL 60 DAY);
+--------------------------------------+
| DATE_ADD(CURDATE(), INTERVAL 60 DAY) |

Page 161 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

+--------------------------------------+
| 2003-08-01 |
+--------------------------------------+
1 row in set (0.00 sec)
Or 6 months in the past:
mysql> SELECT DATE_SUB(CURDATE(), INTERVAL 6 MONTH);
+---------------------------------------+
| DATE_SUB(CURDATE(), INTERVAL 6 MONTH) |
+---------------------------------------+
| 2002-12-02 |
+---------------------------------------+
1 row in set (0.00 sec)
We can also format this result as well using DATE_FORMAT() and using an alias to tidy up the
title:
mysql> SELECT
-> DATE_FORMAT(DATE_SUB(CURDATE(), INTERVAL 6 MONTH), '%W the %D of %M %Y')
-> AS 'Six Months Ago';
+---------------------------------+
| Six Months Ago |
+---------------------------------+
| Monday the 2nd of December 2002 |
+---------------------------------+
1 row in set (0.01 sec)
By now you should have the idea and thus I'm not going to carry on and extensively cover all the
functions, the MySQL manual is probably the best place to look to see all the date functions.

String Functions

String values are can be explained as 'bits of text' and much like the date functions, the string
functions allow us to manipulate these values before they are displayed. Although there are once
more many different functions, I'm going to concentrate on the functions that fall into a few broad
categories.

 Adding text to an existing value

 Changing Part of a String

 Extracting Text from a String

 Finding a piece of text in a string

Adding text to an existing value

There are two simple ways to add more text to an existing value - either at the start or end of the
text. Placing the text at either end is best achieved with the CONCAT() function.

Syntax:
CONCAT(string1,string2,...)
Thus we can take an existing value (say string2) and place a new value (string1) at the
beginning to get string1string2. To see this in action let's retrieve the title of The Beatles 'The
White Album' (which was entered in part 8).

Page 162 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

mysql> SELECT cds.title


-> FROM cds WHERE cdID='20';
+-----------------+
| title |
+-----------------+
| The White Album |
+-----------------+
1 row in set (0.00 sec)
If we wanted to add the text "The Beatles' " at the beginning.
+-----------------------------------+
| CONCAT("The Beatles' ",cds.title) |
+-----------------------------------+
| The Beatles' The White Album |
+-----------------------------------+
1 row in set (0.04 sec)
Or if we wanted to say "By The Beatles" at the end.
mysql> SELECT CONCAT(cds.title," By The Beatles")
-> FROM cds WHERE cdID='20';
+-------------------------------------+
| CONCAT(cds.title," By The Beatles") |
+-------------------------------------+
| The White Album By The Beatles |
+-------------------------------------+
1 row in set (0.00 sec)
Changing Part of a String

As well as add text we can replace it or overwrite it completely. To replace an instance of text
within a string we can use the REPLACE() function.

Syntax:
REPLACE(whole_string,to_be_replaced,replacement)
Therefore if we wanted to replace the word 'White' with the word 'Black' in the cds.title:
mysql> SELECT REPLACE(cds.title,'White','Black')
-> FROM cds WHERE cdID='20';
+------------------------------------+
| REPLACE(cds.title,'White','Black') |
+------------------------------------+
| The Black Album |
+------------------------------------+
1 row in set (0.02 sec)
Or just to be silly (and to demonstrate that each occurrence in the string is changed) let's swap
the 'e' for an 'a'.
mysql> SELECT REPLACE(cds.title,'e','a')
-> FROM cds WHERE cdID='20';
+----------------------------+
| REPLACE(cds.title,'e','a') |
+----------------------------+
| Tha Whita Album |
+----------------------------+

Page 163 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

1 row in set (0.00 sec)


Another Function we can use to add text is the INSERT() function that overwrites any text in the
string from a start point for a certain length.

Syntax:
INSERT(string,start_position,length,newstring)
In this case the crucial bits of information are the position to start (how many characters from the
begriming) and the length. So again to replace 'White' (which starts at character 5 in the string)
with 'Black' in the title we need to start at position 5 for a length of 5.
mysql> SELECT INSERT(cds.title,5,5,'Black')
-> FROM cds WHERE cdID='20';
+-------------------------------+
| INSERT(cds.title,5,5,'Black') |
+-------------------------------+
| The Black Album |
+-------------------------------+
1 row in set (0.01 sec)
If we alter the position (say to 3) you can see that the exchange doesn't work properly.
mysql> SELECT INSERT(cds.title,3,5,'Black')
-> FROM cds WHERE cdID='20';
+-------------------------------+
| INSERT(cds.title,3,5,'Black') |
+-------------------------------+
| ThBlackte Album |
+-------------------------------+
1 row in set (0.00 sec)
Similarly if we were to shorten the length to 3 (resetting the position to 5) not all of the word
'White' gets overwritten.
mysql> SELECT INSERT(cds.title,5,3,'Black')
-> FROM cds WHERE cdID='20';
+-------------------------------+
| INSERT(cds.title,5,3,'Black') |
+-------------------------------+
| The Blackte Album |
+-------------------------------+
1 row in set (0.00 sec)
Thus using this knowledge we can insert text into the middle of a string by setting the length to
'0' (so it doesn't overwrite anything). Let's make the title 'Black and White':
mysql> SELECT INSERT(cds.title,5,0,'Black and ')
-> FROM cds WHERE cdID='20';
+------------------------------------+
| INSERT(cds.title,5,0,'Black and ') |
+------------------------------------+
| The Black and White Album |
+------------------------------------+
1 row in set (0.00 sec)
Extracting Text from a String.

Page 164 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

As well as adding text to a string we can also use functions to extract specific data from a string.
To begin with lets look at three LEFT(), RIGHT() and MID().

Syntax:
LEFT(string,length)
RIGHT(string,length)
MID(string,start_position,length)
The first two, LEFT() and RIGHT(), are fairly straight forward. You specify the string and the
length of the string to keep, relative to either the left or right depending on which function you are
using. So to keep the words 'The' (which occupies 3 characters on the left) and 'Album' (5
characters on the right) we would specify:
mysql> SELECT LEFT(cds.title,3), RIGHT(cds.title,5)
-> FROM cds WHERE cdID='20';
+-------------------+--------------------+
| LEFT(cds.title,3) | RIGHT(cds.title,5) |
+-------------------+--------------------+
| The | Album |
+-------------------+--------------------+
1 row in set (0.00 sec)
The MID() function is only slightly complex. You still specify the length, but also a starting
position. So to keep the work 'White', you would start at position 5 and have a length of 5.
mysql> SELECT MID(cds.title,5,5)
-> FROM cds WHERE cdID='20';
+--------------------+
| MID(cds.title,5,5) |
+--------------------+
| White |
+--------------------+
1 row in set (0.03 sec)
There is also another extraction function that is is worth mentioning; SUBSTRING().

Syntax:
SUBSTRING(string,position)
This returns all of the string after the position. Thus to return 'White Album' you would start at
'5'.
mysql> SELECT SUBSTRING(cds.title,5)
-> FROM cds WHERE cdID='20';
+------------------------+
| SUBSTRING(cds.title,5) |
+------------------------+
| White Album |
+------------------------+
1 row in set (0.00 sec)
Finding a piece of text in a string.

In some of the string functions we have seen so far it has been necessary to provide a starting
position as part of the function This position can be found using the LOCATE() function specifying
the text to find (substring) as well as the string to search in.

Page 165 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

Syntax:
LOCATE(substring,string)
So to find the location of 'White':
mysql> SELECT LOCATE('White',cds.title)
-> FROM cds WHERE cdID='20';
+---------------------------+
| LOCATE('White',cds.title) |
+---------------------------+
| 5|
+---------------------------+
1 row in set (0.06 sec)
If a substring is not present then '0' is returned.
mysql> SELECT LOCATE('Black',cds.title)
-> FROM cds WHERE cdID='20';
+---------------------------+
| LOCATE('Black',cds.title) |
+---------------------------+
| 0|
+---------------------------+
1 row in set (0.00 sec)
It is also possible to automatically calculate the length of a piece of text using LENGTH().

Syntax:
LENGTH(string)
So with the word 'White'.
mysql> SELECT LENGTH('White');
+-----------------+
| LENGTH('White') |
+-----------------+
| 5|
+-----------------+
1 row in set (0.03 sec)
Therefore with these results who these can be combined with one of the other functions. For
example with the MID() function.
mysql> SELECT MID(cds.title,LOCATE('White',cds.title),LENGTH('White'))
-> FROM cds WHERE cdID='20';
+----------------------------------------------------------+
| MID(cds.title,LOCATE('White',cds.title),LENGTH('White')) |
+----------------------------------------------------------+
| White |
+----------------------------------------------------------+
1 row in set (0.01 sec)
The LENGTH() of 'White' is worked out, the position of 'White' is worked out using LOCATE() and
these values are included within the MID() function. The result is that White is returned.

Transforming Strings

The final group of string functions this workshop will look at are those that transform the string in

Page 166 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

some way. The first two change the case of the string to either uppercase - UCASE() - or to
lowercase - LCASE().

Syntax:
LCASE(string)
UCASE(string)
As you can imagine the usage of these are fairly straightforward.
mysql> SELECT LCASE(cds.title), UCASE(cds.title)
-> FROM cds WHERE cdID='20';
+------------------+------------------+
| LCASE(cds.title) | UCASE(cds.title) |
+------------------+------------------+
| the white album | THE WHITE ALBUM |
+------------------+------------------+
1 row in set (0.01 sec)
The last string function this workshop will examine is REVERSE().

Syntax:
REVERSE(string)
This rather obviously reverses the order of the letters. For example the alphabet.
mysql> SELECT REVERSE('abcdefghijklmnopqrstuvwxyz');
+---------------------------------------+
| REVERSE('abcdefghijklmnopqrstuvwxyz') |
+---------------------------------------+
| zyxwvutsrqponmlkjihgfedcba |
+---------------------------------------+
1 row in set (0.00 sec)
Once more there are more string functions that the MySQL Manual documents.

Numeric Functions

Before talking about the specific numeric functions, it is probably worth mentioning that MySQL
can perform simple math functions using mathematical operators.

Operator Function
+ Add
- Subtract
* Multiply
/ Divide

Examples:
mysql> SELECT 6+3;
+-----+
| 6+3 |
+-----+
| 9|
+-----+
1 row in set (0.00 sec)

Page 167 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

mysql> SELECT 6-3;


+-----+
| 6-3 |
+-----+
| 3|
+-----+
1 row in set (0.01 sec)

mysql> SELECT 6*3;


+-----+
| 6*3 |
+-----+
| 18 |
+-----+
1 row in set (0.00 sec)

mysql> SELECT 6/3;


+------+
| 6/3 |
+------+
| 2.00 |
+------+
1 row in set (0.22 sec)
There are also other functions that serve a more specific math function and we shall have a look
at a few of these.

FLOOR()

This reduces any number containing decimals to the lowest whole number.

Syntax:
SELECT FLOOR(number)
Example:
mysql> SELECT FLOOR(4.84);
+-------------+
| FLOOR(4.84) |
+-------------+
| 4|
+-------------+
1 row in set (0.00 sec)
CEILING()

Raises a number containing decimals to the highest whole number.

Syntax:
SELECT CEILING(number)
Example:
mysql> SELECT CEILING(4.84);

Page 168 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

+---------------+
| CEILING(4.84) |
+---------------+
| 5|
+---------------+
1 row in set (0.01 sec)
ROUND()

This function, as you may have guessed, rounds the figures up or down to the nearest whole
number (or to a specified number of decimal places).

Syntax:
ROUND(number,[Decimal Places])
'Decimal Places' is optional and omitting it will mean that the figure is rounded to a whole
number.

Examples:
mysql> SELECT ROUND(14.537);
+---------------+
| ROUND(14.537) |
+---------------+
| 15 |
+---------------+
1 row in set (0.01 sec)

mysql> SELECT ROUND(14.537,2);


+-----------------+
| ROUND(14.537,2) |
+-----------------+
| 14.54 |
+-----------------+
1 row in set (0.00 sec)
TRUNCATE()

This function, rather than rounding, simply shortens the number to a required decimal place.

Syntax:
TRUNCATE(number,places)
Example:
mysql> SELECT TRUNCATE(14.537,2);
+--------------------+
| TRUNCATE(14.537,2) |
+--------------------+
| 14.53 |
+--------------------+
1 row in set (0.00 sec)
The interesting thing about truncate is that if you specify a negative number for the 'places', it
replaces the existing numbers in those places with zeros. So for example 545 to '-2' becomes
500.

Page 169 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

mysql> SELECT TRUNCATE(545,-2);


+------------------+
| TRUNCATE(545,-2) |
+------------------+
| 500 |
+------------------+
1 row in set (0.00 sec)
Summary Functions

The MySQL manual describes this group of functions as ' Functions for Use with GROUP BY
Clauses' which I think is a little misleading as they can be used in queries where there are no
GROUP BY clauses (see Part 3 for a refresher on GROUP BY). Thus is it is perhaps better (if
probably not strictly correct) to think of them as functions that report information about a query
(for example the number of rows), rather than simply display or manipulate directly the data
retrieved.

COUNT()

This counts the number of times a row (or field) is returned.

Syntax:
COUNT(field)
The most common usage for this is just to specify an asterisks as the field to count the number of
rows (or in this case cds).
mysql> SELECT COUNT(*) as 'Number of Cds'
-> FROM cds;
+---------------+
| Number of Cds |
+---------------+
| 9|
+---------------+
1 row in set (0.00 sec)
You could also choose to count just one field:
mysql> SELECT COUNT(cds.title) as 'Number of Cds'
-> FROM cds;
+---------------+
| Number of Cds |
+---------------+
| 9|
+---------------+
1 row in set (0.00 sec)
There may be occasions that we would want to count the DISTINCT occurrences in a field. Let's
look at the artist ID field to demonstrate.
mysql> SELECT COUNT(cds.artistID)
-> FROM cds;
+-----------------+
| COUNT(artist ID) |
+-----------------+
| 9|
+-----------------+

Page 170 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

1 row in set (0.00 sec)


Now my database contain two artists that have 2 cds in the database (Various and Prince) each
of whom have been counted twice. Thus we could try using DISTINCT as part of the query to find
out how many artists have cds in the database.
mysql> SELECT DISTINCT COUNT(cds.artistID)
-> FROM cds;
+-----------------+
| COUNT(artist ID) |
+-----------------+
| 9|
+-----------------+
1 row in set (0.00 sec)
As we can see this doesn't work as each row is indeed unique and thus returns the total of cds
again. However if we include DISTINCT as part of the COUNT() function it does work.
mysql> SELECT COUNT(DISTINCT cds.artistID)
-> FROM cds;
+--------------------------+
| COUNT(DISTINCT artist ID) |
+--------------------------+
| 7|
+--------------------------+
1 row in set (0.00 sec)
AVG()

The next function we are going to look at is the AVG() which unsurprisingly is the average
function.

Syntax:
AVG(field)
Lets look that the tracks field and work out the average number of tracks per CD.
mysql> SELECT AVG(cds.tracks)
-> FROM cds;
+-------------+
| AVG(tracks) |
+-------------+
| 25.6667 |
+-------------+
1 row in set (0.01 sec)
As that is simply but AVG() can work out more that one value at a time when used with a GROUP
BY clause.
mysql> SELECT cds.artistID,AVG(cds.tracks)
-> FROM cds
-> GROUP BY cds.artistID;
+----------+-------------+
| artist ID | AVG(tracks) |
+----------+-------------+
| 1| 11.5000 |
| 2| 40.0000 |
| 3| 17.0000 |

Page 171 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

| 4| 23.0000 |
| 5| 24.0000 |
| 17 | 30.0000 |
| 18 | 37.0000 |
+----------+-------------+
7 rows in set (0.01 sec)
As you can see an average is produced for each artist (not that we know who they are yet) when
the artist ID is specified in the GROUP BY clause. Although AVG() is fairly straight forward, lets
take this opportunity to 'tidy things up' and see how it can work with other functions and also with
a join. So first left's round the averages to one decimal place:
mysql> SELECT cds.artistID, ROUND(AVG(cds.tracks),1)
-> FROM cds
-> GROUP BY cds.artistID;
+----------+----------------------+
| artist ID | ROUND(AVG(tracks),1) |
+----------+----------------------+
| 1| 11.5 |
| 2| 40.0 |
| 3| 17.0 |
| 4| 23.0 |
| 5| 24.0 |
| 17 | 30.0 |
| 18 | 37.0 |
+----------+----------------------+
7 rows in set (0.04 sec)
...then perform a join on the artists table to retrieve and display the artists' names in place of the
artist ID:
mysql> SELECT artists.Artist, ROUND(AVG(cds.tracks),1)
-> FROM cds
-> LEFT JOIN artists
-> USING (artist ID)
-> GROUP BY artists.Artist;
+-------------+--------------------------+
| Artist | ROUND(AVG(cds.tracks),1) |
+-------------+--------------------------+
| Abba | 24.0 |
| Jamiroquai | 11.5 |
| Prince | 37.0 |
| The Beatles | 30.0 |
| Various | 31.5 |
| westlife | 17.0 |
+-------------+--------------------------+
6 rows in set (0.01 sec)
MIN() and MAX()

These functions are very similar and select the lowest and highest figure respectively from a result
set.

Syntax:
MIN(field)

Page 172 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

MAX(field)
So a simple example would be to display the least number and most number of tracks that any cd
in the database has.
mysql> SELECT MIN(cds.tracks), MAX(cds.tracks)
-> FROM cds;
+-----------------+-----------------+
| MIN(cds.tracks) | MAX(cds.tracks) |
+-----------------+-----------------+
| 11 | 58 |
+-----------------+-----------------+
1 row in set (0.00 sec)
SUM()

The final summary function that we will look at is the SUM() function which adds rows of one field
in the results set together.

Syntax:
SUM(field)
So another simple example would be to add the total number of tracks in the CD collection.
mysql> SELECT SUM(tracks)
-> FROM cds;
+-------------+
| SUM(tracks) |
+-------------+
| 231 |
+-------------+
1 row in set (0.03 sec)
Control Functions

The final set of functions that this workshop will look at are the control functions that allow us a
degree of conditionality when returning result sets.

IF()

The IF() function is fairly straight forward and consists of 3 elements. A condition and values for
the condition being evaluated either true or false.

Syntax:
IF(condition,true_value,false_value)
So using a simple comparison (is a number greater than 10) to return either 'yup' or 'nope'.
mysql> SELECT IF(15>10,'Yup','Nope');
+------------------------+
| IF(15>10,'Yup','Nope') |
+------------------------+
| Yup |
+------------------------+
1 row in set (0.03 sec)

Page 173 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

mysql> SELECT IF(5>10,'Yup','Nope');


+-----------------------+
| IF(5>10,'Yup','Nope') |
+-----------------------+
| Nope |
+-----------------------+
1 row in set (0.01 sec)
As well as returned a string value, a number can also be returned. Thus if we wanted to count
how many cds had more that 15 tracks we could return '1' for a true match and a NULL value for
a false match.
mysql> SELECT IF(cds.tracks>15,1,NULL)
-> FROM cds;
+--------------------------+
| IF(cds.tracks>15,1,NULL) |
+--------------------------+
| NULL |
| 1|
| 1|
| 1|
| NULL |
| 1|
| 1|
| 1|
| 1|
+--------------------------+
9 rows in set (0.00 sec)
We can then use COUNT() to give us a total as it ignores NULL values.
mysql> SELECT COUNT(IF(cds.tracks>15,1,NULL))
-> FROM cds;
+---------------------------------+
| COUNT(IF(cds.tracks>15,1,NULL)) |
+---------------------------------+
| 7|
+---------------------------------+
1 row in set (0.01 sec)
CASE

Slightly more advanced from IF() is the CASE function that allows for than one comparison to be
made. It is slightly different as the actual value is specified first, then a series of comparisons are
made for a potential match that then returns a value.

Syntax:
CASE actual_value
WHEN potential_value1 THEN return_value1
WHEN potential_value2 THEN return_value2...
etc
END
Thus if we were to evaluate numeric values and return their string values.
mysql> SELECT CASE 2
-> WHEN 1 THEN 'One'

Page 174 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

-> WHEN 2 THEN 'Two'


-> WHEN 3 THEN 'Three'
-> END;
+--------------------------------------------------------------------+
| CASE 2 WHEN 1 THEN 'One' WHEN 2 THEN 'Two' WHEN 3 THEN 'Three' END |
+--------------------------------------------------------------------+
| Two |
+--------------------------------------------------------------------+
1 row in set (0.01 sec)

mysql> SELECT CASE 1


-> WHEN 1 THEN 'One'
-> WHEN 2 THEN 'Two'
-> WHEN 3 THEN 'Three'
-> END;
+--------------------------------------------------------------------+
| CASE 1 WHEN 1 THEN 'One' WHEN 2 THEN 'Two' WHEN 3 THEN 'Three' END |
+--------------------------------------------------------------------+
| One |
+--------------------------------------------------------------------+
1 row in set (0.00 sec)

mysql> SELECT CASE 3


-> WHEN 1 THEN 'One'
-> WHEN 2 THEN 'Two'
-> WHEN 3 THEN 'Three'
-> END;
+--------------------------------------------------------------------+
| CASE 3 WHEN 1 THEN 'One' WHEN 2 THEN 'Two' WHEN 3 THEN 'Three' END |
+--------------------------------------------------------------------+
| Three |
+--------------------------------------------------------------------+
1 row in set (0.01 sec)
Notice that the actual_value is the only thing that changes in the statement. Again you could also
return numeric values. Consider the following short example in which I have competed in various
competitions around Scotland (sport undetermined ;-).
mysql> SELECT * FROM comp;
+------+-----------+----------+
| id | location | position |
+------+-----------+----------+
| 1 | Aberdeen | 2|
| 2 | Edinburgh | 1|
| 3 | Glasgow | 1|
| 4 | Dundee | 3|
+------+-----------+----------+
4 rows in set (0.00 sec)
I know that 10 points are awarded for 1st, 7 points for second and 5 points for third. I can use the
case statement to work out the total points I have.
mysql> SELECT CASE comp.position
-> WHEN 1 THEN 10
-> WHEN 2 THEN 7

Page 175 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

-> WHEN 3 THEN 5


-> END
-> AS points
-> FROM comp;
+--------+
| points |
+--------+
| 7|
| 10 |
| 10 |
| 5|
+--------+
4 rows in set (0.00 sec)
A SUM() function can be added to this statement to give us the total.
mysql> SELECT SUM(CASE comp.position
-> WHEN 1 THEN 10
-> WHEN 2 THEN 7
-> WHEN 3 THEN 5
-> END)
-> AS points
-> FROM comp;
+--------+
| points |
+--------+
| 32 |
+--------+
1 row in set (0.00 sec)
IFNULL()

The Final function we will look at is IFNULL and unsurprisingly this is a very simple syntax that is
similar to IF(). The difference is that that instead of there being TRUE and FALSE return values
based on a condition, the original value is returned if it is not NULL and a different new value is
returned if it is NULL.

Syntax:
IFNULL(original_value, new_value)
To quickly demonstrate test one query with a NULL value and another with a real value.
mysql> SELECT IFNULL(NULL,'The value is Null');
+----------------------------------+
| IFNULL(NULL,'The value is Null') |
+----------------------------------+
| The value is Null |
+----------------------------------+
1 row in set (0.00 sec)

mysql> SELECT IFNULL(10,'The value is Null');


+--------------------------------+
| IFNULL(10,'The value is Null') |
+--------------------------------+
| 10 |

Page 176 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

+--------------------------------+
1 row in set (0.00 sec)
This is particularly useful for converting NULL values to actual numeric zeros. To illustrate let's set
the track value from 'The White Album' to NULL.
mysql> UPDATE cds
-> SET cds.tracks = NULL
-> WHERE (cdID = "20");
Query OK, 1 row affected (0.03 sec)
Rows matched: 1 Changed: 1 Warnings: 0

mysql> SELECT cds.title, cds.tracks


-> FROM cds;
+------------------------------+--------+
| title | tracks |
+------------------------------+--------+
| A Funk Odyssey | 11 |
| Now 49 | 40 |
| Eurovision Song contest 2001 | 23 |
| Abbas Greatest Hits | 24 |
| Space Cowboy | 12 |
| Sign of the times | 16 |
| The White Album | NULL |
| The Hits | 58 |
| westlife | 17 |
+------------------------------+--------+
9 rows in set (0.00 sec)
So we can use the IFNULL() function to specify a zero in place of the NULL figure.
mysql> SELECT cds.title, IFNULL(cds.tracks,0)
-> FROM cds;
+------------------------------+----------------------+
| title | IFNULL(cds.tracks,0) |
+------------------------------+----------------------+
| A Funk Odyssey | 11 |
| Now 49 | 40 |
| Eurovision Song contest 2001 | 23 |
| Abbas Greatest Hits | 24 |
| Space Cowboy | 12 |
| Sign of the times | 16 |
| The White Album | 0|
| The Hits | 58 |
| westlife | 17 |
+------------------------------+----------------------+
9 rows in set (0.00 sec)

MYSQL – More Features


1. Mysql –h hostname –u username –p password .
2. Union – we can access common fields only in both tables

Page 177 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

a. Ex ((select uid from user_det where uid>1) union (select uid from group_det)
order by uid desc)
b. The group by is not allowed in union
3. First, some sample data:
Mr Brown, Person number 1, has a phone number 01225 708225
Miss Smith, Person number 2, has a phone number 01225 899360
Mr Pullen, Person number 3, has a phone number 01380 724040
and also:
Person number 1 is selling property number 1 - Old House Farm
Person number 3 is selling property number 2 - The Willows
Person number 3 is (also) selling property number 3 - Tall Trees
Person number 3 is (also) selling property number 4 - The Melksham Florist
Person number 4 is selling property number 5 - Dun Roamin.
mysql> select * from demo_people;
+------------+--------------+------+
| name | phone | pid |
+------------+--------------+------+
| Mr Brown | 01225 708225 | 1|
| Miss Smith | 01225 899360 | 2|
| Mr Pullen | 01380 724040 | 3|
+------------+--------------+------+
3 rows in set (0.00 sec)
mysql> select * from demo_property;
+------+------+----------------------+
| pid | spid | selling |
+------+------+----------------------+
| 1| 1 | Old House Farm |
| 3| 2 | The Willows |
| 3| 3 | Tall Trees |
| 3| 4 | The Melksham Florist |
| 4| 5 | Dun Roamin |
+------+------+----------------------+
5 rows in set (0.00 sec)
If I do a regular JOIN (with none of the keywords INNER, OUTER, LEFT or RIGHT), then I
get all records that match in the appropriate way in the two tables, and records in both

Page 178 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

incoming tables that do not match are not reported:


mysql> select name, phone, selling from demo_people join demo_property on
demo_people.pid = demo_property.pid;
+-----------+--------------+----------------------+
| name | phone | selling |
+-----------+--------------+----------------------+
| Mr Brown | 01225 708225 | Old House Farm |
| Mr Pullen | 01380 724040 | The Willows |
| Mr Pullen | 01380 724040 | Tall Trees |
| Mr Pullen | 01380 724040 | The Melksham Florist |
+-----------+--------------+----------------------+
4 rows in set (0.01 sec)
If I do a LEFT JOIN, I get all records that match in the same way and IN ADDITION I get
an extra record for each unmatched record in the left table of the join - thus ensuring (in
my example) that every PERSON gets a mention:
mysql> select name, phone, selling from demo_people left join demo_property
on demo_people.pid = demo_property.pid;
+------------+--------------+----------------------+
| name | phone | selling |
+------------+--------------+----------------------+
| Mr Brown | 01225 708225 | Old House Farm |
| Miss Smith | 01225 899360 | NULL |
| Mr Pullen | 01380 724040 | The Willows |
| Mr Pullen | 01380 724040 | Tall Trees |
| Mr Pullen | 01380 724040 | The Melksham Florist |
+------------+--------------+----------------------+
5 rows in set (0.00 sec)
If I do a RIGHT JOIN, I get all the records that match and IN ADDITION I get an extra
record for each unmatched record in the right table of the join - in my example, that
means that each property gets a mention even if we don't have seller details:
mysql> select name, phone, selling from demo_people right join demo_property on
demo_people.pid = demo_property.pid;
+-----------+--------------+----------------------+
| name | phone | selling |
+-----------+--------------+----------------------+

Page 179 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

| Mr Brown | 01225 708225 | Old House Farm |


| Mr Pullen | 01380 724040 | The Willows |
| Mr Pullen | 01380 724040 | Tall Trees |
| Mr Pullen | 01380 724040 | The Melksham Florist |
| NULL | NULL | Dun Roamin |
+-----------+--------------+----------------------+
5 rows in set (0.00 sec)
An INNER JOIN does a full join, just like the first example, and the word OUTER may be
added after the word LEFT or RIGHT in the last two examples - it's provided for ODBC
compatibility and doesn't add an extra capabilities.
Another Example
mysql> select * from user_det;
+-----+-----------+-----------+
| uid | uname | pwd |
+-----+-----------+-----------+
| 1 | ramasubbu | ramasubbu |
| 2 | kumar | kumar |
| 3 | ranjith | ranjith |
| 4 | james | james |
| 5 | hari | hari |
+-----+-----------+-----------+
5 rows in set (0.00 sec)
mysql> select * from group_det;
+-----+-----+----------+
| gid | uid | gname |
+-----+-----+----------+
| 1| 1 | first |
| 2| 1 | second |
| 3| 3 | firstt |
| 4| 4 | firsttt |
| 5| 4 | seconddd |
| 6| 4 | thirddd |
+-----+-----+----------+
6 rows in set (0.04 sec)
Select the username and those users total no of groups using join query.

Page 180 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

mysql> select uname,count(gid) as totgroup from user_det left join group_det on


user_det.uid = group_det.uid group by user_det.uid;
+-----------+----------+
| uname | totgroup |
+-----------+----------+
| ramasubbu | 2|
| kumar | 0|
| ranjith | 1|
| james | 3|
| hari | 0|
+-----------+----------+
5 rows in set (0.01 sec)

4. Stored Procedures
a. Block of mysql codes like functions.
b. Ex. create procedure p1() select * from tablename with condition;
c. Ex. create procedure p2() insert into tablename (fields) values (values);
Alter Queries
d. Change the data type value like varchar(10) to varchar(15).
ALTER TABLE group_det CHANGE gname gname VARCHAR( 15 ) CHARACTER SET
latin1 COLLATE latin1_swedish_ci NOT NULL
e. Change the data type like varchar(15) to text
ALTER TABLE group_det CHANGE gname gname TEXT CHARACTER SET latin1
COLLATE latin1_swedish_ci NOT NULL
f. Add a new field
ALTER TABLE group_det ADD sam VARCHAR( 10 ) NOT NULL AFTER uid ;
g. Delete a field
ALTER TABLE group_det DROP sam
h. Set the primary key to a field
ALTER TABLE table-name ADD PRIMARY KEY(field-name)
i. Set auto increment to a field
ALTER TABLE table-name CHANGE field-name field-name INT( 23 ) NOT NULL
AUTO_INCREMENT

Page 181 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

j. Set Unique key to a field


ALTER TABLE table-name ADD UNIQUE (field-name )
k. Set INDEX to a field
ALTER TABLE table-name ADD INDEX ( field-name )
l. Set FULL TEXT to a field
ALTER TABLE table-name ADD FULLTEXT (field-name )
m. Drop FULL TEXT from a field
ALTER TABLE table-name DROP INDEX field-name
n. Drop INDEX from a field
ALTER TABLE table-name DROP INDEX field-name
o. Drop UNIQUE Key from a field
ALTER TABLE table-name DROP INDEX field-name
p. Drop Primary Key
ALTER TABLE table-name DROP PRIMARY KEY

 Service Component Architecture (SCA) provides a very easy way to create


and access services

 Service Data Object (SDO) provides a uniform interface for handling


different forms of data and provides a mechanism for tracking changes in
data.
INNODB Engine – Foreign Key
CREATE TABLE parent (id INT NOT NULL,
PRIMARY KEY (id)
) ENGINE=INNODB;

CREATE TABLE child (id INT, parent_id INT,


INDEX par_ind (parent_id),
FOREIGN KEY (parent_id) REFERENCES parent(id)
ON DELETE CASCADE
) ENGINE=INNODB;
(OR)
CREATE TABLE child (id INT, parent_id INT,
INDEX par_ind (parent_id),
FOREIGN KEY (parent_id) REFERENCES parent(id)
ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=INNODB

Business Logic: To Store or not to Store that is the Question?

A lot of people in the database and programming professions are vehemently in favor or opposed
to the use of stored procedures and the like in databases. They will argue that all access to the

Page 182 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

database should go thru stored procedures because it is more secure and shields applications
from changing logic. The other side will vehemently argue that you should avoid this because not
all databases support this and the way each supports it is different so your code is less portable.

I would start by saying those individuals who are vehemently on one side or the other should
open their minds a little. One approach is not strictly the best solution for all business
requirements. In the next couple of sections we'll outline what are the important questions to
consider when choosing one approach over another. Often you will find that even in a single
application a mixture of approaches works best.

Best Practices vs. Best approach to achieve the goal

Before dismissing one approach over another, it is important to map out what you are trying to
achieve and then determine how using one approach aligns with your objectives.

You will often hear the term Best Practices used in Application Architecture. The danger of such
a term is that it gives one a sense that there is no need to question a practice because it is always
best. Just follow Best Practices outlined by an authority in the subject matter and things will
magically fall into place. Rather than just focus on Best Practices, I would like to propose that one
should think about what they are trying to achieve and why one approach is better than another
to get there.

What to consider?

In this section, we will talk about considerations on a very elemental functional level rather than a
more macro application level. We think it is important to consider each functional task of an
application separately rather than thinking of an application as a whole. Example you may have
one part of an application that needs to talk to a mainframe database or run scheduled tasks, and
given that it doesn‘t make sense to drive your whole application structure based on the need of
this single functionality.

 Does this function need to work in various kinds of databases?

 Is this function used in multiple parts of an application or applications?

 Does this function require many arguments and return one set of values in form of single
table or scalar value?

 Does this function require few arguments passed to the database, but require lots of data
from the database to arrive at results?

 Is the function data intensive or processor intensive? E.g. is it an encryption function or


one to get results of a complex query - is it more SQL intensive or more procedural
intensive

 Are the parameters passed into the function consistently the same or can they vary? E.g. a
complex search form will not always need to pass the same parameters, but a simple one
will just have a single search field and always pass just that.

 Does the function require page long batches of SQL statements or is it a one line SQL
statement?

 Are the fields of the result set always the same or do they need to vary. For example do
you always find yourself joining the same set of tables varying slightly by the need for
different fields or subsets of data?

Page 183 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

Database Objects

I always find it amusing that when people talk about database logic they are very focused on
stored procedures and its almost like nothing else exists. Makes me wonder if these people have
ever worked with modern databases. Stored procedures are one of the oldest methods of
encapsulating database logic, but they are not the only method available. Many relational
databases nowadays have views, constraints, referential integrity with cascading update, delete,
stored functions, triggers and the like. These are extremely powerful tools when used
appropriately.

In the next couple of sections we‘ll cover stored procedures and these other kinds of database
objects and detail the strengths and weaknesses of each for encapsulating logic. We will give a
rating of 0-5 for each feature 0 meaning the feature is non-existent, 5 meaning this object is one
of the best suited objects for implementing this kind of task.

Stored Procedures

Stored procedures are one of numerous mechanisms of encapsulating database logic in the
database. They are similar to regular programming language procedures in that they take
arguments, do something, and sometimes return results and sometimes even change the values
of the arguments they take when arguments are declared as output parameters. You will find that
they are very similar to stored functions in that they can return data; however stored procedures
can not be used in queries. Since stored procedures have the mechanism of taking arguments
declared as OUTPUT they can in theory return more than one output.
Feature Rating
Works in various kinds of 3 (many databases such as DB II, Oracle, SQL Server, MySQL 5,
databases PostGreSQL, FireBird support them). There are also a lot that don‘t
e.g. MySQL < 5.0, MS Access (although parameterized queries serve a
similar role)
Can be called by multiple 4 (generally they can be called, but the use of OUTPUT arguments is
applications and interfaces not always usable)
Can take an undefined 2 (note most databases allow to define optional arguments, but this
number of arguments can become very unwieldy to maintain if there are a lot because you
end up duplicating logic even within the stored procedure so is
generally avoided)
Reusability within the 3 (you can not reuse them in views, rarely in stored functions and
database other stored procedures unless the stored procedure using it does not
require a return value or result query). This varies slightly from DBMS
to DBMS.
Can be used to change 4 In general true for most DBMSs that support them.
data in a table without
giving rights to a user to
change table directly
Can return varying number 3 –again in theory it can, but very hard to maintain since you would
of fields given different often be duplicating logic to say return one field in one situation and
arguments. other set of fields in another situation or update a field when the field
is passed in as an argument. Note that in many databases such as for
example SQL Server and Oracle, one can return multiple result sets
with a stored procedure, but the receiving end needs to be able to do
a next result set call and know the sequence in which the result sets

Page 184 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

are being sent.


Long stretches of SQL easy 5 (one of the great strengths of stored procedures is that you can have
to read and maintain long transactions of sql statements and conditional loops which can be
all committed at once or rolled back as a unit. This also saves on
network traffic.
Stored Functions

Stored Functions are very similar to stored procedures except in 3 major ways.

1. Unlike stored procedures, they can be used in views, stored procedures, and other stored
functions.

2. In many databases they are prohibited from changing data or have ddl/dml limitations.
Note for databases such as PostGreSQL this is not true since the line between a stored
function and a stored procedure is very greyed

3. They generally can not take output arguments (placeholders) that are then passed back
out with changed values.
Feature Rating
Works in various kinds of 3 (many databases such as DB II, Oracle, SQL Server support them,
databases MySQL 5, PostGreSQL). There are also a lot that don‘t e.g. MySQL <
5.0, MS Access
Can be called by multiple 4 (generally they can be called, but the use of OUTPUT arguments is
applications and interfaces not always usable)
Can take an undefined 2 (note most databases allow to define optional arguments, but this
number of arguments can become very unwieldy to maintain if there are a lot because you
end up duplicating logic even within the stored function so is generally
avoided)
Reusability within the 5 (you can reuse them in views, in other stored functions and stored
database procedures). This varies slightly from DBMS to DBMS.
Can be used to change 3 Many databases do not allow changing of data in stored functions
data in a table without except temp table data, but those that do in general support this.
giving rights to a user to
change table directly
Can return varying number 4 –For databases such as SQL Server, PostgreSQL, DB 2, Oracle that
of fields given different allow return tables and sets, you can selectively pick fields you want
arguments. from within a query. So although the function always outputs the same
number of fields, you can selectively use only some similar to what
you can do with views. This is not true for scalar functions (MySQL
5.1- only supports scalar functions).
Long stretches of SQL easy 5 - yes - you can do fairly intensive multi-line processing which in the
to read end returns one value or table to the user.
Views

Views are one of the greatest things invented since sliced bread. The main beauty of a view is that
it can be used like a table in most situations, but unlike a table, it can encapsulate very complex
calculations and commonly used joins. It can also use pretty much any object in the db except for
stored procedures. Views are most useful when you always need to join the same set of tables say
an Order with an Order Detail to get summary calculation fields etc.
Feature Rating

Page 185 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

Works in various kinds of 4 (many databases such as DB II, Oracle, SQL Server support them,
databases MySQL 5, PostGreSQL, SQLite, MSAccess (calls it a query)). There are
also some that don‘t e.g. MySQL < 5.0
Can be called by multiple 5 (generally they can be called anywhere where you can call a table
applications and which is pretty much everywhere)
interfaces
Can take an undefined 5 (you can select subsets of columns and rows from a view just like you
number of arguments can from a table)
Reusability within the 5 (you can reuse them in other views, in stored functions and stored
database procedures).
Can be used to change 3 In many databases Views are read-only and complex views are
data in a table without rarely updateable. Note that for example some databases such as
giving rights to a user to Oracle,PostgreSQL, MS SQL Server , SQLite will allow you to update
change table directly. even a complex view by using an instead of trigger or rule against the
view. MySQL 5, MS SQL Server and some others automatically make
one table views updateable. MS Access has a fairly sophisticated
update algorithm for queries in that it automatically makes one table
and even multi-table queries updateable and allows deletes if you
define primary keys appropriately. Also depending on the field a column
comes from it will update that and also automatically create child
records in child tables if you try to update a child column when there is
no record.
Can return varying 4 – (you can select subsets of columns and rows from a view just like
number of fields given you can from a table). However you can't change the underlying
different arguments. structure e.g. return records from a different set of tables like you can
with a stored procedure or function.
Long stretches of SQL 3 (A view can often be defined with an administrative designer or using
easy to read. a color coded sql editor so is fairly easy to read) - in general though it
is limited to only one select statement or unioned select statements.
Triggers And Rules

Triggers are objects generally tied to a table or view that run code based on certain events such
as inserting data, before inserting data, updating/deleting data and before these events happen.

Triggers can be very great things and very dangerous things. Dangerous in the sense that they
are tricky to debug, but powerful because no update to a table with a trigger can easily escape the
trigger.

They are useful for making sure certain events always happen when data is inserted or updated -
e.g. set complex default values of fields, inserting logging records into other tables.

Triggers are especially useful for one particular situation and that is for implementing instead of
logic. For example as we said earlier, many views involving more than one table are not
updateable. However in DBMS such as PostgreSQL, you can define a rule on a view that occurs
when someone tries to update or insert into the view and will occur instead of the insert. The rule
can be fairly complex and can layout how the tables should be updated in such a situation. MS
SQL Server and SQLite let you do something similar with INSTEAD OF triggers. Note the term Rule
is a little confusing in DBMS because they mean quite different things. In Microsoft SQL Server for
example a Rule is an obsolete construct that was used to define constraints on tables. In
PostgreSQL a Rule is very similar to a trigger except that it does not get triggered per row event
and is defined without need of a handling function.

Page 186 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

Feature Rating
Works in various kinds of databases 2 (many databases such as DB II, Oracle, SQL
Server support them, MySQL 5, PostGreSQL,).
There are lots that don't e.g. MySQL < 5.0, MySQL
5 limited, MS Access
Can be called by multiple applications and 5 (it just happens behind the scenes. No
interfaces application can escape them)
Can take an undefined number of arguments 0 ( strictly for updating data and against a table or
view )
Reusability within the database 0 - No
Can be used to change data in a table without 4 In general yes for databases that support them
giving rights to a user to change table directly.
Can return varying number of fields given 0 –Triggers are strictly for updating data
different arguments.
Long stretches of SQL easy to read. A trigger 5
can often be defined with an administrative
designer or using a color coded sql editor so is
fairly easy to read

Foreign Key Constraints, Primary Key Constraints, Referential Integrity, Cascade


Update/Delete

No true database should be without Constraints, Referential Integrity, and Cascade Update/Delete.
You can define them with SQL DDL statements or using a relational designer. The use of these
tools are limited but the purpose they serve can not be easily replicated with other database
objects. These tools serve 2 main purposes.

 Provide a declarative model of the database and how the data is related to each other. A
self-documenting tool.

 Insure that you don't mistakenly do something stupid in your coding to violate your model.
If your model is sound, errors in your code signal a flaw in your programming logic. If you
get errors in your programming logic, then verify that your model is sound.
Feature Rating
Works in various kinds of databases 3 (many databases such as DB II, Oracle, SQL Server
support them, MySQL 4+ (4 is limited, 3 very limited and
varies depending on storage engine (InnoDB vs MyISAM)),
PostGreSQL, MS Access). There are lots that don't e.g.
MySQL < 5.0
Can be called by multiple 5 (it just happens behind the scenes. No application can
applications and interfaces escape them)
Can take an undefined number of 0 (they take no arguments )
arguments
Reusability within the database 5 - Yes - no matter where your updates, inserts occur, they
can not escape the iron-fist of the Key Constraints and
Cascade Update/Delete rules next to disabling them.
Can be used to change data in a 4 Really only applies to cascade update/delete rules Yes -
table without giving rights to a user cascade update/delete rules are a special kind of trigger so to
to change table directly. speak that kick in when a potential referential integrity

Page 187 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

constraint can be violated. Example if you update a key field,


a cascade update on the foreign keys will force an update on
the foreign key field to correct the situation so you don't end
up with orphan data.
Can return varying number of fields 0 –not relevant
given different arguments.
Long stretches of SQL easy to read. 0 - not relevant
A trigger can often be defined with
an administrative designer or using
a color coded sql editor so is fairly
easy to read

Dynamically Generated SQL

In this section we discuss the pros and cons of using dynamically generated sql vs. only using
stored procedures, view, etc.
Feature Rating
Works in various kinds of 4 (guaranteed to work for any database, although the syntax may
databases vary from database.)
Can be called by multiple 3 (Will only work in the application where the dynamic sql is defined or
applications and interfaces if the application is wrapped as a shared library. The use of shared
library is often limited as to where you can use it. However your logic
can be applied to multiple databases without needing to alter the db
by adding stored procs etc. if you are always using the same app to
access these databases.)
Can take an undefined 5 (you can select subsets of columns and rows from tables, change
number of arguments tables you are reading from etc.)
Reusability within the 2 (non-existent except in some very rare situations and databases
database that allow you to load shared libraries).
Can be used to change 4 You can have the application control the security so in that sense
data in a table without the application only needs to have rights
giving rights to a user to
change table directly.
Can return varying number 5 – (you can select subsets of columns and rows, do complex joins ).
of fields given different You can change the underlying structure e.g. return records from a
arguments. different set of tables.
Long stretches of SQL easy 2 - SQL often sits interspersed with other programming logic which
to read. makes it somewhat difficult to read depending on the application
language and also difficult to write complex transactional sql.
What about Security?

In the above criteria, we didn't put Security in as a feature/benefit even though many people will
argue that dynamic SQL and the like are not secure. This actually varies depending on how you
implement Dynamic SQL, e.g. if you are using an O/R Mapper or built-in dataadapters (supported
in .NET),prepared statements, or are very careful to sanitize inputs you are using in your sql then
your Dynamic SQL will probably be just as secure or sometimes more so than using stored
procedures since some people are of the mindset that stored procedures are a magic bullet for
protecting against SQL Injection and other attacks (such as script injection) regardless of how
they are implemented and called and thus neglect other necessary precautions.

Page 188 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

How to Configure Name Virtual Host in XAMPP’s Apache Server


Updated for XAMPP version 1.6.5

Some time ago, I decided to start phasing out static xhtml in favor of pages using PHP includes.
To test these new pages, I used apachefriends.org‘s wonderful XAMPP (which I really can‘t
recommend highly enough) to install Apache, MySQL, and PHP (among other things). Once I had
my local server running, I put each dev site into its own folder in \htdocs\ and navigated to them
by http://127.0.0.1/foldername/.

This setup was functional but far from ideal, as the index pages for these local sites weren‘t in
what could be considered a root directory, which lead to some tip-toeing around when creating
links.

Then I discovered the NameVirtualHost feature in Apache. NameVirtualHost allows the server
admin to set up multiple domains/hostnames on a single Apache installation by using VirtualHost
containers. In other words, you can run more than one web site on a single machine. This means
that each dev site (or domain) can then consider itself to have a root directory. You will be able to
access each local site as a subdomain of ―localhost‖ by making a change to the HOSTS file. For
example, I access the local dev version of this site at http://ardamis.localhost/.

This works great for all sorts of applications that rely on the site having a discernible root
directory, such as WordPress.

Unfortunately, setting up NameVirtualHost can be kind of tricky. If you are having problems
configuring your Apache installation to use the NameVirtualHost feature, you‘re in good company.
Here‘s how I managed to get it working:

For XAMPP version 1.6.5

1. Create a folder in drive:\xampp\htdocs\ for each dev site (adjust for your directory
structure). For example, if I‘m creating a development site for ardamis.com on my d:
drive, I‘d create a folder at:
d:\xampp\htdocs\ardamis\

2. Edit your HOSTS file (in Windows XP, the HOSTS file is located in
C:\WINDOWS\system32\drivers\etc\) to add the following line, where sitename is the
name of the folder you created in step 1.
3. 127.0.0.1 sitename.localhost

Add a new line for each dev site folder you create. Don’t change or delete the existing
“127.0.0.1 localhost” line.

Continuing with the example, I‘ve added the line:


127.0.0.1 ardamis.localhost
4. Open your drive:\xampp\apache\conf\extra\httpd-vhosts.conf file and add the following
lines to the end of the file, using the appropriate letter in place of drive. Do this step only
once. We‘ll add code for each dev site‘s folder in the next step. (Yes, keep the asterisk.)
5. NameVirtualHost *:80

Page 189 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

6. <VirtualHost *:80>
7. DocumentRoot "drive:/xampp/htdocs"
8. ServerName localhost
9. </VirtualHost>
My DocumentRoot line would be:
DocumentRoot "d:/xampp/htdocs"
10. Immediately after that, add the following lines, changing sitename to the name of the new
dev site‘s folder, again using the appropriate letter in place of drive. Repeat this step for
every folder you‘ve created.
11. <VirtualHost *:80>
12. DocumentRoot "drive:/xampp/htdocs/sitename"
13. ServerName sitename.localhost
14. </VirtualHost>
My DocumentRoot line would be:
DocumentRoot "d:/xampp/htdocs/ardamis"
My ServerName line would be:
ServerName ardamis.localhost
15. Reboot your computer to be sure it‘s using the new HOSTS file (you‘ll have to at least
restart Apache). You should now be able to access each dev domain by way of:
http://sitename.localhost/

For XAMPP version 1.4

If you are using an older version of XAMPP (like XAMPP version 1.4) without the httpd-vhosts.conf
file, use the instructions below.

1. Create a folder in your drive:\apachefriends\xampp\htdocs\ for each local version of your


site. For example, if I‘m creating a development site for ardamis.com on my f: drive, I‘d
create a folder at:
f:\apachefriends\xampp\htdocs\ardamis\

2. Open your HOSTS file (in Windows XP, the HOSTS file is located in
C:\WINDOWS\system32\drivers\etc\) and add the following line, where sitename is the
name of the folder you created in step 1. Repeat this step, as necessary, for each folder
you create. Don’t change or delete the existing “127.0.0.1 localhost” line.
3. 127.0.0.1 sitename.localhost
Continuing with the example, I‘ve added the line:
127.0.0.1 ardamis.localhost
4. Open your drive:\apachefriends\xampp\apache\conf\httpd.conf file and add the following
lines to the end of the file, using the appropriate letter for drive. Do this step only once.
We‘ll add code for each dev site‘s folder in the next step. (Yes, keep the asterisk.)
5. NameVirtualHost *:80
6. <VirtualHost *:80>
7. DocumentRoot "drive:/apachefriends/xampp/htdocs"
8. ServerName localhost
9. </VirtualHost>
My DocumentRoot line would be:
DocumentRoot "f:/apachefriends/xampp/htdocs"

Page 190 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

10. Immediately after that, add the following lines, changing sitename to the name of the new
folder, using the appropriate letter for drive and repeating this step for every folder you‘ve
created.
11. <VirtualHost *:80>
12. DocumentRoot "drive:/apachefriends/xampp/htdocs/sitename"
13. ServerName sitename.localhost
14. </VirtualHost>
My DocumentRoot line would be:
DocumentRoot "f:/apachefriends/xampp/htdocs/ardamis"
15. Reboot and restart Apache. Open a browser; you should now be able to access each folder
by way of:
http://sitename.localhost

I‘m assuming that you could change the DocumentRoot line to point to any folder on any drive. I‘ll
experiment with pointing this at a folder on another drive later.

The official Apache.org documentation for VirtualHost is at


http://httpd.apache.org/docs/2.2/vhosts/. You may want to read that for further details before
you try to set up virtual hosts.

If you have any questions about the above instructions, the Apache NameVirtualHost function,
XAMPP, or anything in between, post a comment, but I can‘t promise that I‘ll be able to help. I‘m
learning as I go along, too.

PHP cURL functions tutorial


cURL is a library which allows you to connect and communicate to many different types of servers
with many different types of protocols. Using cURL you can:

 Implement payment gateways‘ payment notification scripts.

 Download and upload files from remote servers.

 Login to other websites and access members only sections.

PHP cURL library is definitely the odd man out. Unlike other PHP libraries where a whole plethora
of functions is made available, PHP cURL wraps up a major parts of its functionality in just four
functions.

A typical PHP cURL usage follows the following sequence of steps.

curl_init – Initializes the session and returns a cURL handle which can be passed to other cURL
functions.

curl_opt – This is the main work horse of cURL library. This function is called multiple times and
specifies what we want the cURL library to do.

curl_exec – Executes a cURL session.

curl_close – Closes the current cURL session.

Below are some examples which should make the working of cURL more clearer.

Page 191 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

Download file or web page using PHP cURL

The below piece of PHP code uses cURL to download Google‘s RSS feed.

<?php

/**

* Initialize the cURL session

*/

$ch = curl_init();

/**

* Set the URL of the page or file to download.

*/

curl_setopt($ch, CURLOPT_URL,

'http://news.google.com/news?hl=en&topic=t&output=rss');

/**

* Ask cURL to return the contents in a variable

* instead of simply echoing them to the browser.

*/

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

/**

* Execute the cURL session

*/

$contents = curl_exec ($ch);

/**

* Close cURL session

*/

curl_close ($ch);

?>

As you can see, curl_setopt is the pivot around which the main cURL functionality revolves. cURL
functioning is controlled by way of passing predefined options and values to this function.

The above code uses two such options.

Page 192 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

 CURLOPT_URL: Use it to specify the URL which you want to process. This could be the
URL of the file you want to download or it could be the URL of the script to which you want
to post some data.

 CURLOPT_RETURNTRANSFER: Setting this option to 1 will cause the curl_exec function


to return the contents instead of echoing them to the browser.

Download file or web page using PHP cURL and save it to file

The below PHP code is a slight variation of the above code. It not only downloads the contents of
the specified URL but also saves it to a file.

<?php

/**

* Initialize the cURL session

*/

$ch = curl_init();

/**

* Set the URL of the page or file to download.

*/

curl_setopt($ch, CURLOPT_URL,

'http://news.google.com/news?hl=en&topic=t&output=rss');

/**

* Create a new file

*/

$fp = fopen('rss.xml', 'w');

/**

* Ask cURL to write the contents to a file

*/

curl_setopt($ch, CURLOPT_FILE, $fp);

/**

* Execute the cURL session

*/

curl_exec ($ch);

/**

Page 193 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

* Close cURL session and file

*/

curl_close ($ch);

fclose($fp);

?>

Here we have used another of the cURL options, CURLOPT_FILE. Obtain a file handler by creating
a new file or opening an existing one and then pass this file handler to the curl_set_opt function.

cURL will now write the contents to a file as it downloads a web page or file.
MYSQL group by aggregate functions list

Name Description
AVG() Return the average value of the argument
BIT_AND() Return bitwise and
BIT_OR() Return bitwise or
BIT_XOR() Return bitwise xor
COUNT(DISTINCT) Return the count of a number of different values
COUNT() Return a count of the number of rows returned
GROUP_CONCAT() Return a concatenated string
MAX() Return the maximum value
MIN() Return the minimum value
STD() Return the population standard deviation
STDDEV_POP() Return the population standard deviation
STDDEV_SAMP() Return the sample standard deviation
STDDEV() Return the population standard deviation
SUM() Return the sum
VAR_POP() Return the population standard variance
VAR_SAMP() Return the sample variance
VARIANCE() Return the population standard variance

This section describes group (aggregate) functions that operate on sets of values. Unless
otherwise stated, group functions ignore NULL values.

If you use a group function in a statement containing no GROUP BY clause, it is equivalent to


grouping on all rows. For more information, see Section 11.15.3, ―GROUP BY and HAVING with
Hidden Columns‖.

For numeric arguments, the variance and standard deviation functions return a DOUBLE value.
The SUM() and AVG() functions return a DECIMAL value for exact-value arguments (integer or
DECIMAL), and a DOUBLE value for approximate-value arguments (FLOAT or DOUBLE). (Before
MySQL 5.0.3, SUM() and AVG() return DOUBLE for all numeric arguments.)

Page 194 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

The SUM() and AVG() aggregate functions do not work with temporal values. (They convert the
values to numbers, losing everything after the first nonnumeric character.) To work around this
problem, you can convert to numeric units, perform the aggregate operation, and convert back to
a temporal value. Examples:
SELECT SEC_TO_TIME(SUM(TIME_TO_SEC(time_col))) FROM tbl_name;
SELECT FROM_DAYS(SUM(TO_DAYS(date_col))) FROM tbl_name;
Functions such as SUM() or AVG() that expect a numeric argument cast the argument to a
number if necessary. For SET or ENUM values, the cast operation causes the underlying numeric
value to be used.

 AVG([DISTINCT] expr)

Returns the average value of expr. The DISTINCT option can be used as of MySQL 5.0.3 to
return the average of the distinct values of expr.

AVG() returns NULL if there were no matching rows.


mysql> SELECT student_name, AVG(test_score)
-> FROM student
-> GROUP BY student_name;
 BIT_AND(expr)

Returns the bitwise AND of all bits in expr. The calculation is performed with 64-bit
(BIGINT) precision.

This function returns 18446744073709551615 if there were no matching rows. (This is the
value of an unsigned BIGINT value with all bits set to 1.)

 BIT_OR(expr)

Returns the bitwise OR of all bits in expr. The calculation is performed with 64-bit (BIGINT)
precision.

This function returns 0 if there were no matching rows.

 BIT_XOR(expr)

Returns the bitwise XOR of all bits in expr. The calculation is performed with 64-bit
(BIGINT) precision.

This function returns 0 if there were no matching rows.

 COUNT(expr)

Returns a count of the number of non-NULL values of expr in the rows retrieved by a
SELECT statement. The result is a BIGINT value.

COUNT() returns 0 if there were no matching rows.


mysql> SELECT student.student_name,COUNT(*)
-> FROM student,course
-> WHERE student.student_id=course.student_id
-> GROUP BY student_name;
COUNT(*) is somewhat different in that it returns a count of the number of rows retrieved,
whether or not they contain NULL values.

Page 195 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

COUNT(*) is optimized to return very quickly if the SELECT retrieves from one table, no
other columns are retrieved, and there is no WHERE clause. For example:
mysql> SELECT COUNT(*) FROM student;
This optimization applies only to MyISAM tables only, because an exact row count is stored
for this storage engine and can be accessed very quickly. For transactional storage engines
such as InnoDB and BDB, storing an exact row count is more problematic because multiple
transactions may be occurring, each of which may affect the count.

 COUNT(DISTINCT expr,[expr...])

Returns a count of the number of rows with different non-NULL expr values.

COUNT(DISTINCT) returns 0 if there were no matching rows.


mysql> SELECT COUNT(DISTINCT results) FROM student;
In MySQL, you can obtain the number of distinct expression combinations that do not
contain NULL by giving a list of expressions. In standard SQL, you would have to do a
concatenation of all expressions inside COUNT(DISTINCT ...).

 GROUP_CONCAT(expr)

This function returns a string result with the concatenated non-NULL values from a group.
It returns NULL if there are no non-NULL values. The full syntax is as follows:
GROUP_CONCAT([DISTINCT] expr [,expr ...]
[ORDER BY {unsigned_integer | col_name | expr}
[ASC | DESC] [,col_name ...]]
[SEPARATOR str_val])
mysql> SELECT student_name,
-> GROUP_CONCAT(test_score)
-> FROM student
-> GROUP BY student_name;
Or:
mysql> SELECT student_name,
-> GROUP_CONCAT(DISTINCT test_score
-> ORDER BY test_score DESC SEPARATOR ' ')
-> FROM student
-> GROUP BY student_name;
In MySQL, you can get the concatenated values of expression combinations. To eliminate
duplicate values, use the DISTINCT clause. To sort values in the result, use the ORDER BY
clause. To sort in reverse order, add the DESC (descending) keyword to the name of the
column you are sorting by in the ORDER BY clause. The default is ascending order; this
may be specified explicitly using the ASC keyword. The default separator between values in
a group is comma (―,‖). To specify a separator explicitly, use SEPARATOR followed by the
string value that should be inserted between group values. To eliminate the separator
altogether, specify SEPARATOR ''.

The result is truncated to the maximum length that is given by the group_concat_max_len
system variable, which has a default value of 1024. The value can be set higher, although
the effective maximum length of the return value is constrained by the value of
max_allowed_packet. The syntax to change the value of group_concat_max_len at runtime
is as follows, where val is an unsigned integer:

Page 196 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

SET [GLOBAL | SESSION] group_concat_max_len = val;


The return value is a nonbinary or binary string, depending on whether the arguments are
nonbinary or binary strings. The result type is TEXT or BLOB unless group_concat_max_len
is less than or equal to 512, in which case the result type is VARCHAR or VARBINARY.
(Prior to MySQL 5.0.19, GROUP_CONCAT() returned TEXT or BLOB group_concat_max_len
greater than 512 only if the query included an ORDER BY clause.)

See also CONCAT() and CONCAT_WS(): Section 11.5, ―String Functions‖.

 MAX([DISTINCT] expr)

Returns the maximum value of expr. MAX() may take a string argument; in such cases, it
returns the maximum string value. See Section 7.4.4, ―How MySQL Uses Indexes‖. The
DISTINCT keyword can be used to find the maximum of the distinct values of expr,
however, this produces the same result as omitting DISTINCT.

MAX() returns NULL if there were no matching rows.


mysql> SELECT student_name, MIN(test_score), MAX(test_score)
-> FROM student
-> GROUP BY student_name;
For MAX(), MySQL currently compares ENUM and SET columns by their string value rather
than by the string's relative position in the set. This differs from how ORDER BY compares
them. This is expected to be rectified in a future MySQL release.

 MIN([DISTINCT] expr)

Returns the minimum value of expr. MIN() may take a string argument; in such cases, it
returns the minimum string value. See Section 7.4.4, ―How MySQL Uses Indexes‖. The
DISTINCT keyword can be used to find the minimum of the distinct values of expr,
however, this produces the same result as omitting DISTINCT.

MIN() returns NULL if there were no matching rows.


mysql> SELECT student_name, MIN(test_score), MAX(test_score)
-> FROM student
-> GROUP BY student_name;
For MIN(), MySQL currently compares ENUM and SET columns by their string value rather
than by the string's relative position in the set. This differs from how ORDER BY compares
them. This is expected to be rectified in a future MySQL release.

 STD(expr)

Returns the population standard deviation of expr. This is an extension to standard SQL. As
of MySQL 5.0.3, the standard SQL function STDDEV_POP() can be used instead.

This function returns NULL if there were no matching rows.

 STDDEV(expr)

Returns the population standard deviation of expr. This function is provided for
compatibility with Oracle. As of MySQL 5.0.3, the standard SQL function STDDEV_POP()
can be used instead.

This function returns NULL if there were no matching rows.

Page 197 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

 STDDEV_POP(expr)

Returns the population standard deviation of expr (the square root of VAR_POP()). This
function was added in MySQL 5.0.3. Before 5.0.3, you can use STD() or STDDEV(), which
are equivalent but not standard SQL.

STDDEV_POP() returns NULL if there were no matching rows.

 STDDEV_SAMP(expr)

Returns the sample standard deviation of expr (the square root of VAR_SAMP(). This
function was added in MySQL 5.0.3.

STDDEV_SAMP() returns NULL if there were no matching rows.

 SUM([DISTINCT] expr)

Returns the sum of expr. If the return set has no rows, SUM() returns NULL. The DISTINCT
keyword can be used in MySQL 5.0 to sum only the distinct values of expr.

SUM() returns NULL if there were no matching rows.

 VAR_POP(expr)

Returns the population standard variance of expr. It considers rows as the whole
population, not as a sample, so it has the number of rows as the denominator. This
function was added in MySQL 5.0.3. Before 5.0.3, you can use VARIANCE(), which is
equivalent but is not standard SQL.

VAR_POP() returns NULL if there were no matching rows.

 VAR_SAMP(expr)

Returns the sample variance of expr. That is, the denominator is the number of rows minus
one. This function was added in MySQL 5.0.3.

VAR_SAMP() returns NULL if there were no matching rows.

 VARIANCE(expr)

Returns the population standard variance of expr. This is an extension to standard SQL. As
of MySQL 5.0.3, the standard SQL function VAR_POP() can be used instead.

VARIANCE() returns NULL if there were no matching rows.

SIMPLE USAGE

Get the main page from Netscape's web-server:

curl http://www.netscape.com/

Get the README file the user's home directory at funet's ftp-server:

curl ftp://ftp.funet.fi/README

Page 198 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

Get a web page from a server using port 8000:

curl http://www.weirdserver.com:8000/

Get a list of a directory of an FTP site:

curl ftp://cool.haxx.se/

Get the definition of curl from a dictionary:

curl dict://dict.org/m:curl

Fetch two documents at once:

curl ftp://cool.haxx.se/ http://www.weirdserver.com:8000/

Get a file off an FTPS server:

curl ftps://files.are.secure.com/secrets.txt

or use the more appropriate FTPS way to get the same file:

curl --ftp-ssl ftp://files.are.secure.com/secrets.txt

Get a file from an SSH server using SFTP:

curl -u username sftp://shell.example.com/etc/issue

Get a file from an SSH server using SCP using a private key to authenticate:

curl -u username: --key ~/.ssh/id_dsa --pubkey ~/.ssh/id_dsa.pub


scp://shell.example.com/~/personal.txt

Get the main page from an IPv6 web server:

curl -g "http://[2001:1890:1112:1::20]/"

DOWNLOAD TO A FILE

Get a web page and store in a local file:

curl -o thatpage.html http://www.netscape.com/

Get a web page and store in a local file, make the local file get the name
of the remote document (if no file name part is specified in the URL, this
will fail):

curl -O http://www.netscape.com/index.html

Fetch two files and store them with their remote names:

curl -O www.haxx.se/index.html -O curl.haxx.se/download.html

Page 199 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

USING PASSWORDS

FTP

To ftp files using name+passwd, include them in the URL like:

curl ftp://name:[email protected]:port/full/path/to/file

or specify them with the -u flag like

curl -u name:passwd ftp://machine.domain:port/full/path/to/file

FTPS

It is just like for FTP, but you may also want to specify and use
SSL-specific options for certificates etc.

Note that using FTPS:// as prefix is the "implicit" way as described in the
standards while the recommended "explicit" way is done by using FTP:// and
the --ftp-ssl option.

SFTP / SCP

This is similar to FTP, but you can specify a private key to use instead of
a password. Note that the private key may itself be protected by a password
that is unrelated to the login password of the remote system. If you
provide a private key file you must also provide a public key file.

HTTP

Curl also supports user and password in HTTP URLs, thus you can pick a file
like:

curl http://name:[email protected]/full/path/to/file

or specify user and password separately like in

curl -u name:passwd http://machine.domain/full/path/to/file

HTTP offers many different methods of authentication and curl supports


several: Basic, Digest, NTLM and Negotiate. Without telling which method to
use, curl defaults to Basic. You can also ask curl to pick the most secure
ones out of the ones that the server accepts for the given URL, by using
--anyauth.

NOTE! Since HTTP URLs don't support user and password, you can't use that
style when using Curl via a proxy. You _must_ use the -u style fetch
during such circumstances.

HTTPS

Page 200 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

Probably most commonly used with private certificates, as explained below.

PROXY

Get an ftp file using a proxy named my-proxy that uses port 888:

curl -x my-proxy:888 ftp://ftp.leachsite.com/README

Get a file from a HTTP server that requires user and password, using the
same proxy as above:

curl -u user:passwd -x my-proxy:888 http://www.get.this/

Some proxies require special authentication. Specify by using -U as above:

curl -U user:passwd -x my-proxy:888 http://www.get.this/

A comma-separated list of hosts and domains which do not use the proxy can
be specified as:

curl --noproxy localhost,get.this -x my-proxy:888 http://www.get.this/

If the proxy is specified with --proxy1.0 instead of --proxy or -x, then


curl will use HTTP/1.0 instead of HTTP/1.1 for any CONNECT attempts.

curl also supports SOCKS4 and SOCKS5 proxies with --socks4 and --socks5.

See also the environment variables Curl support that offer further proxy
control.

RANGES

With HTTP 1.1 byte-ranges were introduced. Using this, a client can request
to get only one or more subparts of a specified document. Curl supports
this with the -r flag.

Get the first 100 bytes of a document:

curl -r 0-99 http://www.get.this/

Get the last 500 bytes of a document:

curl -r -500 http://www.get.this/

Curl also supports simple ranges for FTP files as well. Then you can only
specify start and stop position.

Get the first 100 bytes of a document using FTP:

curl -r 0-99 ftp://www.get.this/README

UPLOADING

Page 201 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

FTP / FTPS / SFTP / SCP

Upload all data on stdin to a specified server:

curl -T - ftp://ftp.upload.com/myfile

Upload data from a specified file, login with user and password:

curl -T uploadfile -u user:passwd ftp://ftp.upload.com/myfile

Upload a local file to the remote site, and use the local file name remote
too:

curl -T uploadfile -u user:passwd ftp://ftp.upload.com/

Upload a local file to get appended to the remote file:

curl -T localfile -a ftp://ftp.upload.com/remotefile

Curl also supports ftp upload through a proxy, but only if the proxy is
configured to allow that kind of tunneling. If it does, you can run curl in
a fashion similar to:

curl --proxytunnel -x proxy:port -T localfile ftp.upload.com

HTTP

Upload all data on stdin to a specified http site:

curl -T - http://www.upload.com/myfile

Note that the http server must have been configured to accept PUT before
this can be done successfully.

For other ways to do http data upload, see the POST section below.

VERBOSE / DEBUG

If curl fails where it isn't supposed to, if the servers don't let you in,
if you can't understand the responses: use the -v flag to get verbose
fetching. Curl will output lots of info and what it sends and receives in
order to let the user see all client-server interaction (but it won't show
you the actual data).

curl -v ftp://ftp.upload.com/

To get even more details and information on what curl does, try using the
--trace or --trace-ascii options with a given file name to log to, like
this:

curl --trace trace.txt www.haxx.se

Page 202 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

DETAILED INFORMATION

Different protocols provide different ways of getting detailed information


about specific files/documents. To get curl to show detailed information
about a single file, you should use -I/--head option. It displays all
available info on a single file for HTTP and FTP. The HTTP information is a
lot more extensive.

For HTTP, you can get the header information (the same as -I would show)
shown before the data by using -i/--include. Curl understands the
-D/--dump-header option when getting files from both FTP and HTTP, and it
will then store the headers in the specified file.

Store the HTTP headers in a separate file (headers.txt in the example):

curl --dump-header headers.txt curl.haxx.se

Note that headers stored in a separate file can be very useful at a later
time if you want curl to use cookies sent by the server. More about that in
the cookies section.

POST (HTTP)

It's easy to post data using curl. This is done using the -d <data>
option. The post data must be urlencoded.

Post a simple "name" and "phone" guestbook.

curl -d "name=Rafael%20Sagula&phone=3320780"
http://www.where.com/guest.cgi

How to post a form with curl, lesson #1:

Dig out all the <input> tags in the form that you want to fill in. (There's
a perl program called formfind.pl on the curl site that helps with this).

If there's a "normal" post, you use -d to post. -d takes a full "post


string", which is in the format

<variable1>=<data1>&<variable2>=<data2>&...

The 'variable' names are the names set with "name=" in the <input> tags, and
the data is the contents you want to fill in for the inputs. The data *must*
be properly URL encoded. That means you replace space with + and that you
write weird letters with %XX where XX is the hexadecimal representation of
the letter's ASCII code.

Example:

(page located at http://www.formpost.com/getthis/

Page 203 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

<form action="post.cgi" method="post">


<input name=user size=10>
<input name=pass type=password size=10>
<input name=id type=hidden value="blablabla">
<input name=ding value="submit">
</form>

We want to enter user 'foobar' with password '12345'.

To post to this, you enter a curl command line like:

curl -d "user=foobar&pass=12345&id=blablabla&ding=submit" (continues)


http://www.formpost.com/getthis/post.cgi

While -d uses the application/x-www-form-urlencoded mime-type, generally


understood by CGI's and similar, curl also supports the more capable
multipart/form-data type. This latter type supports things like file upload.

-F accepts parameters like -F "name=contents". If you want the contents to


be read from a file, use <@filename> as contents. When specifying a file,
you can also specify the file content type by appending ';type=<mime type>'
to the file name. You can also post the contents of several files in one
field. For example, the field name 'coolfiles' is used to send three files,
with different content types using the following syntax:

curl -F "[email protected];type=image/gif,fil2.txt,fil3.html"
http://www.post.com/postit.cgi

If the content-type is not specified, curl will try to guess from the file
extension (it only knows a few), or use the previously specified type (from
an earlier file if several files are specified in a list) or else it will
using the default type 'text/plain'.

Emulate a fill-in form with -F. Let's say you fill in three fields in a
form. One field is a file name which to post, one field is your name and one
field is a file description. We want to post the file we have written named
"cooltext.txt". To let curl do the posting of this data instead of your
favourite browser, you have to read the HTML source of the form page and
find the names of the input fields. In our example, the input field names
are 'file', 'yourname' and 'filedescription'.

curl -F "[email protected]" -F "yourname=Daniel" -F "filedescription=Cool text


file with cool text inside" http://www.post.com/postit.cgi

To send two files in one post you can do it in two ways:

1. Send multiple files in a single "field" with a single field name:

curl -F "[email protected],cat.gif"

Page 204 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

2. Send two fields with two field names:

curl -F "[email protected]" -F "[email protected]"

To send a field value literally without interpreting a leading '@'


or '<', or an embedded ';type=', use --form-string instead of
-F. This is recommended when the value is obtained from a user or
some other unpredictable source. Under these circumstances, using
-F instead of --form-string would allow a user to trick curl into
uploading a file.

REFERRER

A HTTP request has the option to include information about which address
that referred to actual page. Curl allows you to specify the
referrer to be used on the command line. It is especially useful to
fool or trick stupid servers or CGI scripts that rely on that information
being available or contain certain data.

curl -e www.coolsite.com http://www.showme.com/

NOTE: The Referer: [sic] field is defined in the HTTP spec to be a full URL.

USER AGENT

A HTTP request has the option to include information about the browser
that generated the request. Curl allows it to be specified on the command
line. It is especially useful to fool or trick stupid servers or CGI
scripts that only accept certain browsers.

Example:

curl -A 'Mozilla/3.0 (Win95; I)' http://www.nationsbank.com/

Other common strings:


'Mozilla/3.0 (Win95; I)' Netscape Version 3 for Windows 95
'Mozilla/3.04 (Win95; U)' Netscape Version 3 for Windows 95
'Mozilla/2.02 (OS/2; U)' Netscape Version 2 for OS/2
'Mozilla/4.04 [en] (X11; U; AIX 4.2; Nav)' NS for AIX
'Mozilla/4.05 [en] (X11; U; Linux 2.0.32 i586)' NS for Linux

Note that Internet Explorer tries hard to be compatible in every way:


'Mozilla/4.0 (compatible; MSIE 4.01; Windows 95)' MSIE for W95

Mozilla is not the only possible User-Agent name:


'Konqueror/1.0' KDE File Manager desktop client
'Lynx/2.7.1 libwww-FM/2.14' Lynx command line browser

COOKIES

Cookies are generally used by web servers to keep state information at the
client's side. The server sets cookies by sending a response line in the

Page 205 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

headers that looks like 'Set-Cookie: <data>' where the data part then
typically contains a set of NAME=VALUE pairs (separated by semicolons ';'
like "NAME1=VALUE1; NAME2=VALUE2;"). The server can also specify for what
path the "cookie" should be used for (by specifying "path=value"), when the
cookie should expire ("expire=DATE"), for what domain to use it
("domain=NAME") and if it should be used on secure connections only
("secure").

If you've received a page from a server that contains a header like:


Set-Cookie: sessionid=boo123; path="/foo";

it means the server wants that first pair passed on when we get anything in
a path beginning with "/foo".

Example, get a page that wants my name passed in a cookie:

curl -b "name=Daniel" www.sillypage.com

Curl also has the ability to use previously received cookies in following
sessions. If you get cookies from a server and store them in a file in a
manner similar to:

curl --dump-header headers www.example.com

... you can then in a second connect to that (or another) site, use the
cookies from the 'headers' file like:

curl -b headers www.example.com

While saving headers to a file is a working way to store cookies, it is


however error-prone and not the preferred way to do this. Instead, make curl
save the incoming cookies using the well-known netscape cookie format like
this:

curl -c cookies.txt www.example.com

Note that by specifying -b you enable the "cookie awareness" and with -L
you can make curl follow a location: (which often is used in combination
with cookies). So that if a site sends cookies and a location, you can
use a non-existing file to trigger the cookie awareness like:

curl -L -b empty.txt www.example.com

The file to read cookies from must be formatted using plain HTTP headers OR
as netscape's cookie file. Curl will determine what kind it is based on the
file contents. In the above command, curl will parse the header and store
the cookies received from www.example.com. curl will send to the server the
stored cookies which match the request as it follows the location. The
file "empty.txt" may be a nonexistent file.

Alas, to both read and write cookies from a netscape cookie file, you can
set both -b and -c to use the same file:

Page 206 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

curl -b cookies.txt -c cookies.txt www.example.com

PROGRESS METER

The progress meter exists to show a user that something actually is


happening. The different fields in the output have the following meaning:

% Total % Received % Xferd Average Speed Time Curr.


Dload Upload Total Current Left Speed
0 151M 0 38608 0 0 9406 0 4:41:43 0:00:04 4:41:39 9287

From left-to-right:
% - percentage completed of the whole transfer
Total - total size of the whole expected transfer
% - percentage completed of the download
Received - currently downloaded amount of bytes
% - percentage completed of the upload
Xferd - currently uploaded amount of bytes
Average Speed
Dload - the average transfer speed of the download
Average Speed
Upload - the average transfer speed of the upload
Time Total - expected time to complete the operation
Time Current - time passed since the invoke
Time Left - expected time left to completion
Curr.Speed - the average transfer speed the last 5 seconds (the first
5 seconds of a transfer is based on less time of course.)

The -# option will display a totally different progress bar that doesn't
need much explanation!

SPEED LIMIT

Curl allows the user to set the transfer speed conditions that must be met
to let the transfer keep going. By using the switch -y and -Y you
can make curl abort transfers if the transfer speed is below the specified
lowest limit for a specified time.

To have curl abort the download if the speed is slower than 3000 bytes per
second for 1 minute, run:

curl -Y 3000 -y 60 www.far-away-site.com

This can very well be used in combination with the overall time limit, so
that the above operation must be completed in whole within 30 minutes:

curl -m 1800 -Y 3000 -y 60 www.far-away-site.com

Forcing curl not to transfer data faster than a given rate is also possible,
which might be useful if you're using a limited bandwidth connection and you
don't want your transfer to use all of it (sometimes referred to as

Page 207 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

"bandwidth throttle").

Make curl transfer data no faster than 10 kilobytes per second:

curl --limit-rate 10K www.far-away-site.com

or

curl --limit-rate 10240 www.far-away-site.com

Or prevent curl from uploading data faster than 1 megabyte per second:

curl -T upload --limit-rate 1M ftp://uploadshereplease.com

When using the --limit-rate option, the transfer rate is regulated on a


per-second basis, which will cause the total transfer speed to become lower
than the given number. Sometimes of course substantially lower, if your
transfer stalls during periods.

CONFIG FILE

Curl automatically tries to read the .curlrc file (or _curlrc file on win32
systems) from the user's home dir on startup.

The config file could be made up with normal command line switches, but you
can also specify the long options without the dashes to make it more
readable. You can separate the options and the parameter with spaces, or
with = or :. Comments can be used within the file. If the first letter on a
line is a '#'-symbol the rest of the line is treated as a comment.

If you want the parameter to contain spaces, you must enclose the entire
parameter within double quotes ("). Within those quotes, you specify a
quote as \".

NOTE: You must specify options and their arguments on the same line.

Example, set default time out and proxy in a config file:

#We want a 30 minute timeout:


-m 1800
#. .. and we use a proxy for all accesses:
proxy = proxy.our.domain.com:8080

White spaces ARE significant at the end of lines, but all white spaces
leading up to the first characters of each line are ignored.

Prevent curl from reading the default file by using -q as the first command
line parameter, like:

curl -q www.thatsite.com

Force curl to get and display a local help page in case it is invoked

Page 208 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

without URL by making a config file similar to:

#default url to get


url = "http://help.with.curl.com/curlhelp.html"

You can specify another config file to be read by using the -K/--config
flag. If you set config file name to "-" it'll read the config from stdin,
which can be handy if you want to hide options from being visible in process
tables etc:

echo "user = user:passwd" | curl -K - http://that.secret.site.com

EXTRA HEADERS

When using curl in your own very special programs, you may end up needing
to pass on your own custom headers when getting a web page. You can do
this by using the -H flag.

Example, send the header "X-you-and-me: yes" to the server when getting a
page:

curl -H "X-you-and-me: yes" www.love.com

This can also be useful in case you want curl to send a different text in a
header than it normally does. The -H header you specify then replaces the
header curl would normally send. If you replace an internal header with an
empty one, you prevent that header from being sent. To prevent the Host:
header from being used:

curl -H "Host:" www.server.com

FTP and PATH NAMES

Do note that when getting files with the ftp:// URL, the given path is
relative the directory you enter. To get the file 'README' from your home
directory at your ftp site, do:

curl ftp://user:[email protected]/README

But if you want the README file from the root directory of that very same
site, you need to specify the absolute file name:

curl ftp://user:[email protected]//README

(I.e with an extra slash in front of the file name.)

SFTP and SCP and PATH NAMES

With sftp: and scp: URLs, the path name given is the absolute name on the
server. To access a file relative to the remote user's home directory,
prefix the file with /~/ , such as:

Page 209 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

curl -u $USER sftp://home.example.com/~/.bashrc

FTP and firewalls

The FTP protocol requires one of the involved parties to open a second
connection as soon as data is about to get transfered. There are two ways to
do this.

The default way for curl is to issue the PASV command which causes the
server to open another port and await another connection performed by the
client. This is good if the client is behind a firewall that don't allow
incoming connections.

curl ftp.download.com

If the server for example, is behind a firewall that don't allow connections
on other ports than 21 (or if it just doesn't support the PASV command), the
other way to do it is to use the PORT command and instruct the server to
connect to the client on the given (as parameters to the PORT command) IP
number and port.

The -P flag to curl supports a few different options. Your machine may have
several IP-addresses and/or network interfaces and curl allows you to select
which of them to use. Default address can also be used:

curl -P - ftp.download.com

Download with PORT but use the IP address of our 'le0' interface (this does
not work on windows):

curl -P le0 ftp.download.com

Download with PORT but use 192.168.0.10 as our IP address to use:

curl -P 192.168.0.10 ftp.download.com

NETWORK INTERFACE

Get a web page from a server using a specified port for the interface:

curl --interface eth0:1 http://www.netscape.com/

or

curl --interface 192.168.1.10 http://www.netscape.com/

HTTPS

Secure HTTP requires SSL libraries to be installed and used when curl is
built. If that is done, curl is capable of retrieving and posting documents
using the HTTPS protocol.

Page 210 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

Example:

curl https://www.secure-site.com

Curl is also capable of using your personal certificates to get/post files


from sites that require valid certificates. The only drawback is that the
certificate needs to be in PEM-format. PEM is a standard and open format to
store certificates with, but it is not used by the most commonly used
browsers (Netscape and MSIE both use the so called PKCS#12 format). If you
want curl to use the certificates you use with your (favourite) browser, you
may need to download/compile a converter that can convert your browser's
formatted certificates to PEM formatted ones. This kind of converter is
included in recent versions of OpenSSL, and for older versions Dr Stephen
N. Henson has written a patch for SSLeay that adds this functionality. You
can get his patch (that requires an SSLeay installation) from his site at:
http://www.drh-consultancy.demon.co.uk/

Example on how to automatically retrieve a document using a certificate with


a personal password:

curl -E /path/to/cert.pem:password https://secure.site.com/

If you neglect to specify the password on the command line, you will be
prompted for the correct password before any data can be received.

Many older SSL-servers have problems with SSLv3 or TLS, that newer versions
of OpenSSL etc is using, therefore it is sometimes useful to specify what
SSL-version curl should use. Use -3, -2 or -1 to specify that exact SSL
version to use (for SSLv3, SSLv2 or TLSv1 respectively):

curl -2 https://secure.site.com/

Otherwise, curl will first attempt to use v3 and then v2.

To use OpenSSL to convert your favourite browser's certificate into a PEM


formatted one that curl can use, do something like this (assuming netscape,
but IE is likely to work similarly):

You start with hitting the 'security' menu button in netscape.

Select 'certificates->yours' and then pick a certificate in the list

Press the 'export' button

enter your PIN code for the certs

select a proper place to save it

Run the 'openssl' application to convert the certificate. If you cd to the


openssl installation, you can do it like:

#. /apps/openssl pkcs12 -in [file you saved] -clcerts -out [PEMfile]

Page 211 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

RESUMING FILE TRANSFERS

To continue a file transfer where it was previously aborted, curl supports


resume on http(s) downloads as well as ftp uploads and downloads.

Continue downloading a document:

curl -C - -o file ftp://ftp.server.com/path/file

Continue uploading a document(*1):

curl -C - -T file ftp://ftp.server.com/path/file

Continue downloading a document from a web server(*2):

curl -C - -o file http://www.server.com/

(*1) = This requires that the ftp server supports the non-standard command
SIZE. If it doesn't, curl will say so.

(*2) = This requires that the web server supports at least HTTP/1.1. If it
doesn't, curl will say so.

TIME CONDITIONS

HTTP allows a client to specify a time condition for the document it


requests. It is If-Modified-Since or If-Unmodified-Since. Curl allow you to
specify them with the -z/--time-cond flag.

For example, you can easily make a download that only gets performed if the
remote file is newer than a local copy. It would be made like:

curl -z local.html http://remote.server.com/remote.html

Or you can download a file only if the local file is newer than the remote
one. Do this by prepending the date string with a '-', as in:

curl -z -local.html http://remote.server.com/remote.html

You can specify a "free text" date as condition. Tell curl to only download
the file if it was updated since January 12, 2012:

curl -z "Jan 12 2012" http://remote.server.com/remote.html

Curl will then accept a wide range of date formats. You always make the date
check the other way around by prepending it with a dash '-'.

DICT

For fun try

Page 212 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

curl dict://dict.org/m:curl
curl dict://dict.org/d:heisenbug:jargon
curl dict://dict.org/d:daniel:web1913

Aliases for 'm' are 'match' and 'find', and aliases for 'd' are 'define'
and 'lookup'. For example,

curl dict://dict.org/find:curl

Commands that break the URL description of the RFC (but not the DICT
protocol) are

curl dict://dict.org/show:db
curl dict://dict.org/show:strat

Authentication is still missing (but this is not required by the RFC)

LDAP

If you have installed the OpenLDAP library, curl can take advantage of it
and offer ldap:// support.

LDAP is a complex thing and writing an LDAP query is not an easy task. I do
advice you to dig up the syntax description for that elsewhere. Two places
that might suit you are:

Netscape's "Netscape Directory SDK 3.0 for C Programmer's Guide Chapter 10:
Working with LDAP URLs":
http://developer.netscape.com/docs/manuals/dirsdk/csdk30/url.htm

RFC 2255, "The LDAP URL Format" http://curl.haxx.se/rfc/rfc2255.txt

To show you an example, this is now I can get all people from my local LDAP
server that has a certain sub-domain in their email address:

curl -B "ldap://ldap.frontec.se/o=frontec??sub?mail=*sth.frontec.se"

If I want the same info in HTML format, I can get it by not using the -B
(enforce ASCII) flag.

ENVIRONMENT VARIABLES

Curl reads and understands the following environment variables:

http_proxy, HTTPS_PROXY, FTP_PROXY

They should be set for protocol-specific proxies. General proxy should be


set with

ALL_PROXY

Page 213 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

A comma-separated list of host names that shouldn't go through any proxy is


set in (only an asterisk, '*' matches all hosts)

NO_PROXY

If the host name matches one of these strings, or the host is within the
domain of one of these strings, transactions with that node will not be
proxied.

The usage of the -x/--proxy flag overrides the environment variables.

NETRC

Unix introduced the .netrc concept a long time ago. It is a way for a user
to specify name and password for commonly visited ftp sites in a file so
that you don't have to type them in each time you visit those sites. You
realize this is a big security risk if someone else gets hold of your
passwords, so therefore most unix programs won't read this file unless it is
only readable by yourself (curl doesn't care though).

Curl supports .netrc files if told so (using the -n/--netrc and


--netrc-optional options). This is not restricted to only ftp,
but curl can use it for all protocols where authentication is used.

A very simple .netrc file could look something like:

machine curl.haxx.se login iamdaniel password mysecret

CUSTOM OUTPUT

To better allow script programmers to get to know about the progress of


curl, the -w/--write-out option was introduced. Using this, you can specify
what information from the previous transfer you want to extract.

To display the amount of bytes downloaded together with some text and an
ending newline:

curl -w 'We downloaded %{size_download} bytes\n' www.download.com

KERBEROS FTP TRANSFER

Curl supports kerberos4 and kerberos5/GSSAPI for FTP transfers. You need
the kerberos package installed and used at curl build time for it to be
used.

First, get the krb-ticket the normal way, like with the kinit/kauth tool.
Then use curl in way similar to:

curl --krb private ftp://krb4site.com -u username:fakepwd

There's no use for a password on the -u switch, but a blank one will make

Page 214 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

curl ask for one and you already entered the real password to kinit/kauth.

TELNET

The curl telnet support is basic and very easy to use. Curl passes all data
passed to it on stdin to the remote server. Connect to a remote telnet
server using a command line similar to:

curl telnet://remote.server.com

And enter the data to pass to the server on stdin. The result will be sent
to stdout or to the file you specify with -o.

You might want the -N/--no-buffer option to switch off the buffered output
for slow connections or similar.

Pass options to the telnet protocol negotiation, by using the -t option. To


tell the server we use a vt100 terminal, try something like:

curl -tTTYPE=vt100 telnet://remote.server.com

Other interesting options for it -t include:

- XDISPLOC=<X display> Sets the X display location.

- NEW_ENV=<var,val> Sets an environment variable.

NOTE: the telnet protocol does not specify any way to login with a specified
user and password so curl can't do that automatically. To do that, you need
to track when the login prompt is received and send the username and
password accordingly.

PERSISTENT CONNECTIONS

Specifying multiple files on a single command line will make curl transfer
all of them, one after the other in the specified order.

libcurl will attempt to use persistent connections for the transfers so that
the second transfer to the same host can use the same connection that was
already initiated and was left open in the previous transfer. This greatly
decreases connection time for all but the first transfer and it makes a far
better use of the network.

Note that curl cannot use persistent connections for transfers that are used
in subsequence curl invokes. Try to stuff as many URLs as possible on the
same command line if they are using the same host, as that'll make the
transfers faster. If you use a http proxy for file transfers, practically
all transfers will be persistent.

MULTIPLE TRANSFERS WITH A SINGLE COMMAND LINE

As is mentioned above, you can download multiple files with one command line

Page 215 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

by simply adding more URLs. If you want those to get saved to a local file
instead of just printed to stdout, you need to add one save option for each
URL you specify. Note that this also goes for the -O option (but not
--remote-name-all).

For example: get two files and use -O for the first and a custom file
name for the second:

curl -O http://url.com/file.txt ftp://ftp.com/moo.exe -o moo.jpg

You can also upload multiple files in a similar fashion:

curl -T local1 ftp://ftp.com/moo.exe -T local2 ftp://ftp.com/moo2.txt

IPv6

curl will connect to a server with IPv6 when a host lookup returns an IPv6
address and fall back to IPv4 if the connection fails. The --ipv4 and --ipv6
options can specify which address to use when both are available. IPv6
addresses can also be specified directly in URLs using the syntax:

http://[2001:1890:1112:1::20]/overview.html

When this style is used, the -g option must be given to stop curl from
interpreting the square brackets as special globbing characters. Link local
and site local addresses including a scope identifier, such as fe80::1234%1,
may also be used, but the scope portion must be numeric and the percent
character must be URL escaped. The previous example in an SFTP URL might
look like:

sftp://[fe80::1234%251]/

IPv6 addresses provided other than in URLs (e.g. to the --proxy, --interface
or --ftp-port options) should not be URL encoded.

MAILING LISTS

For your convenience, we have several open mailing lists to discuss curl,
its development and things relevant to this. Get all info at
http://curl.haxx.se/mail/. Some of the lists available are:

curl-users

Users of the command line tool. How to use it, what doesn't work, new
features, related tools, questions, news, installations, compilations,
running, porting etc.

curl-library

Developers using or developing libcurl. Bugs, extensions, improvements.

Page 216 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

curl-announce

Low-traffic. Only receives announcements of new public versions. At worst,


that makes something like one or two mails per month, but usually only one
mail every second month.

curl-and-php

Using the curl functions in PHP. Everything curl with a PHP angle. Or PHP
with a curl angle.

curl-and-python

Python hackers using curl with or without the python binding pycurl.

Please direct curl questions, feature requests and trouble reports to one of
these mailing lists instead of mailing any individual.

Codeigniter PHP Framework Work Manual (MVC)

1. The below options values are change in - /system/application/config/config.php

Configure the domain name with path, new directory index file name, query string on/off
option, site language, meta charset, url protocol, controller and function trigger values
2. Update the DB Details

/system/application/config/database.php
3. How to display your name

a. First create a Controller file in /system/application/controllers/ - your desired


filename.

b. Must save the file name with same that file class name. The file name is case
sensitive in Linux. But it‘s not a case sensitive in windows.

c. Example code below

<?php
class First extends Controller
{
public function __construct()
{
parent::Controller(); // Mandatory line to all
classes.
}
function displayname()
{
echo "Ramasubbu";
}
}
?>

Page 217 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

4. How to run the above code file.

a. http://localhost/codeigniter/index.php/First/displayname

i. After the index.php file comes with the class name and that class particular
function name.

5. Another method to write a code

a. Example code

<?php
class First extends Controller
{
public function __construct()
{
parent::Controller(); // Mandatory line to all
classes.
}
function index()
{
echo "Index function";
}
}
?>
Run the above code using the below url structure
http://localhost/codeigniter/index.php/First/

6. Works in forms

a. $this->load->helper(array('form','url')); - This line is used to create the form


elements.

b. $this->load->library('form_validation'); - This line is used to implement the


predefined server side validation functions.

7. Sample Controller File

<?php
class First extends Controller
{
public function __construct()
{
parent::Controller();
$this->load->helper(array('form','url'));
$this->load->library('form_validation');
}

function displayname()
{
echo "Ramasubbu";
}

Page 218 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

function index()
{
echo "function index";
}

function displayLogin()
{
$this->benchmark->mark('code_start');
$data1['title']='Site Login';
$data1['showstatus'] = '';
$this->load->view('login',$data1);
$this->benchmark->mark('code_end');
echo $this->benchmark->elapsed_time('code_start', 'code_end');
}

function checkLogin()
{
if($this->loginValidation() === FALSE)
{
$this->displayLogin();
return;
}
else
{
$this->load->model('Login');
$data1['showstatus'] = $this->Login->checkLogin();
$this->load->view('login',$data1);
}
}

private function loginValidation()


{

$this->form_validation->set_rules('username', 'Username',
'required|valid_email');
$this->form_validation->set_rules('password', 'Password',
'required|alpha_numeric|min_length[3]|max_length[12]');

return $this->form_validation->run();
}
}
?>
8. Sample Model File

<?php
class Login extends Model
{
function __construct()
{
parent::Model();
}
function checkLogin()

Page 219 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

{
$this->load->database();
$sql = "SELECT * FROM members WHERE emailid='".$_POST['username']."'
and password = '".$_POST['password']."'";
$query = $this->db->query($sql);
$total = intval($query->num_rows());
if($total > 0)
{
$rec=$query->result_array();
print_r($rec);
}
else
return "Invalid Username and Password";
}
}
?>
9. Sample View (template) file

<?php
require 'header.php';
?>
<form name="loginfrm" method="post" action="checkLogin" onSubmit="return
validation();">
<?php echo validation_errors('<p class="error">','</p>'); ?>
<?php if($showstatus) echo $showstatus;?>
<table width="100%" border="0">
<tr>
<td>Username</td>
<td><label>
<?php echo form_input('username',set_value('username')); ?><?php echo
form_error('username'); ?>
</label></td>
</tr>
<tr>
<td>Password</td>
<td><label>
<?php echo form_password('password'); ?><?php echo form_error('password'); ?>
</label></td>
</tr>
<tr>
<td>&nbsp;</td>
<td><label>

Page 220 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

<input type="submit" name="button" id="button" value="Submit">


</label></td>
</tr>
</table>
</form>
<?php
require 'footer.php';
?>
<script language="javascript">
function validation()
{

if(document.loginfrm.username.value == "")
{
alert("Please enter your Username");
document.loginfrm.username.focus();
return false;
}
}
</script>

10.Form Components Samples

a. Combo Box

<select class="cmb_bx" id="country" name="country">


<option value="">Select</option>
<option value="1" <?php echo set_select('country', '1'); ?> >United
States</option>
<option value="2" <?php echo set_select('country', '2'); ?>
>Canada</option>
<option value="3" <?php echo set_select('country', '3'); ?>>United
Kingdom</option>
</select>
b. Text Box

<input type="text" value="<?php echo set_value('zip'); ?>" name="zip" id="zip"


/>
c. Check Box

<input type="checkbox" name="check" value="1" <?php echo


set_checkbox('check', 'check2'); ?> />
d. Radio Box

Male
<input type="radio" name="radio" value="1" <?php echo set_radio('radio', '1',
TRUE); ?> />
Female
<input type="radio" name="radio" value="2" <?php echo set_radio('radio', '2'); ?>
/>

Page 221 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

Default set the selection option


e. How to Use Captcha Code

function _make_captcha()
{
$this->load ->plugin('captcha_pi');
$vals = array(
'img_path' => '../captcha/', // PATH for captcha ( *Must mkdir
(htdocs)/captcha )
'img_url' => '/captcha/', // URL for captcha img
'img_width' => 200, // width
'img_height' => 60, // height
'expiration'=> 7200 ,
);
$cap = create_captcha($vals);
return $cap['image'] ;
}
public function index()
{
$data1['cap_img'] = $this -> _make_captcha();
$data1['title']='user registration';
$this->load->view('view-template-name',$data1);
}
f. How to call Captcha Code – (Inside the view – template)

<?php echo "<p>".$cap_img."</p>" ;?>


g. How to use the file upload control codes

$uploadpath='';
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png|jpeg|bmp';
$config['max_size'] = '100';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$this->load->library('upload', $config);
if(! $this->upload->do_upload(‗FileBrowse Control Name Here – Optional
also‘))
{
$error = array('error' => $this->upload->display_errors());
}
else
{
$imgdata = array('upload_data' => $this->upload->data());
$apk=explode('/',$imgdata['upload_data']['full_path']);
$a=count($apk)-2;
$b=count($apk)-1;
$uploadpath=$apk[$a].'/'.$apk[$b];
}
$data=$this->demo_model->insert_user($uploadpath);
11. Sample Form Validations

private function form_validation()


{

Page 222 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

$this->form_validation->set_rules('username', 'Username','required|valid_email');
$this->form_validation->set_rules('firstname', 'Firstname',
'required|alpha_numeric|min_length[3]|max_length[12]');

$this->form_validation->set_rules('lastname', 'lastname',
'required|alpha_numeric|min_length[3]|max_length[12]');

$this->form_validation->set_rules('password', 'Password',
'required|min_length[6]|max_length[12]');

$this->form_validation->set_rules('passconf', 'Confirm Password',


'required|matches[password]');

$this->form_validation->set_rules('zip', 'ZIP Code', 'required');


$this->form_validation->set_rules('country', 'country', 'required');
$this->form_validation->set_rules('address', 'Address', 'required');
$this->form_validation->set_rules('phone', 'phone', 'required');
$this->form_validation->set_rules('zip', 'ZIP Code', 'required');
$this->form_validation->set_rules('captcha', 'Capture Code',
required|captcha[captcha]');

$this->form_validation->set_rules('radio', 'Sex', 'required');

return $this->form_validation->run();
}
12. Controller File Path

a. /system/application/controllers/filename&sameclassname.php

13. Model File Path

a. /system/application/models/filename&sameclassname.php

14. Libraries Path

a. /system/libraries/ filename.php

15. Plugins Path

a. /system/plugins/filename&sameclassname.php

16. Change the source configuration

a. /system/application/config/config.php

17. Change the DB Detials

a. /system/application/config/database.php

Page 223 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

Drupal V6.17

1. Create a page

a. Create Content->Page (Title, Select the Menu Settings : Menu Title, Parent Item,
weight : default – 0, Page Body content in : Body, select the : Input format (Filtered
HTML and Full HTML), Revision information, Comment Settings (Disabled, Read
Only, Read/Writer), Authoring information (Authored By and Authored On),
Publishing options (Published, Promoted to front page, sticky at top of lists.)

2. Administer -> Site Building -> Menus -> Primary Links used to create the top menus.

3. Administer -> Site Building -> Menus -> Navigation used to create left menus.

4. Create a Story

a. Create Content -> Story (Same page creation fields)

b. Difference between Page and Story

i. Page is like a web page

ii. Story is like an article. The story allowed giving the comments on the story
page and display with the posting on & posting by details.

iii. The all stories are comes the index page like www.domainname.com/ page.
The home or other pages are comes with ―Page option‖. Automatically set
this option, we want to update this option also possible. Hide from index
page.

5. Administer -> Site Building -> Menus -> Secondary Menu used to create the top most
menu. It‘s comes upper the top menu.

6. Important Themes Files

a. page.tpl.php

b. node.tpl.php

c. comment.tpl.php

d. box.tpl.php

e. themename.info

f. block.tpl.php

7. page.tpl.php

a. It‘s a theme html page source file.

Page 224 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

8. node.tpl.php

a. This file is used to display the site contents.

9. comment.tpl.php

a. This file is used to display the ―Story‖ page comments listing with styles.

10. box.tpl.php

a. This file is mandatory file. But this file contents is optional.

11. themename.info

a. This file is used to display the

12. Syndicate – Block is used to set the RSS feed on the page

GD Library References

Crop an Image

<?php
// Set the path to the image to rotate
$input_image = "img/aj_matrix.gif";
//How many degrees you wish to rotate
$degrees = 180;
// Create the canvas
$canvas = imagecreatefromgif( $input_image ) ;
// Rotates the image
$rotate = imagerotate( $canvas, $degrees, 0 ) ;
// Save the image as output.jpg
imagegif( $rotate, "img/aj_matrix.gif" );
// Clear the memory of the tempory image
imagedestroy( $canvas );
?>
<img src="img/aj_matrix.gif">

Page 225 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

Output

Resize the Image save as another one name

(ajmatrix.gif)

<?php
function reduce_image($file,$nwidth,$nheight,$file_path)
{
$image_type=array('gif'=>1,'jpg'=>2,'png'=>3,'bmp'=>6);
$uploadedfile = $file;
list($width,$height,$type)=getimagesize($uploadedfile);

// echop $%
if($width>$nwidth)
{
switch($type)
{
case $image_type['gif']: $src = imagecreatefromgif($uploadedfile); break;
case $image_type['jpg']: $src = imagecreatefromjpeg($uploadedfile); break;
case $image_type['png']: $src = imagecreatefrompng($uploadedfile); break;
}

// For our purposes, I have resized the image to be 600 pixels wide, and maintain
the original aspect
// ratio. This prevents the image from being "stretched" or "squashed". If you
prefer some max width other than
// 600, simply change the $newwidth variable

$newwidth=$nwidth;
$newheight=$nheight;//($height/$width)*$size;
$tmp=imagecreatetruecolor($newwidth,$newheight);

// this line actually does the image resizing, copying from the original image into the
$tmp image
imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);

// now write the resized image to disk. I have assumed that you want the
// resized, uploaded image file to reside in the ./images subdirectory.
//$file_path = "upload_images/".date('Ymdhs').$_FILES[$file]['name'];

Page 226 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

switch($type)
{
case $image_type['gif']: $ret=imagegif($tmp,$file_path); break;
case $image_type['jpg']: $ret=imagejpeg($tmp,$file_path,100); break;
case $image_type['png']: $ret=imagepng($tmp,$file_path); break;
//case $image_type['bmp']: imagewbmp($tmp,$file_path); break;
}

imagedestroy($src);
imagedestroy($tmp);
}
return $ret;
}
reduce_image("img/ajmatrix.gif",50,50,"img/aj_ajmatrix.gif");
?>
<img src="img/aj_ajmatrix.gif">

Output

(aj_ajmatrix.gif)

Rotate an Image

<?php
// Set the path to the image to rotate
$input_image = "img/aj_matrix.gif";
//How many degrees you wish to rotate
$degrees = 180;
// Create the canvas
$canvas = imagecreatefromgif( $input_image ) ;
// Rotates the image
$rotate = imagerotate( $canvas, $degrees, 0 ) ;
// Save the image as output.jpg
imagegif( $rotate, "img/aj_matrix.gif" );
// Clear the memory of the tempory image
imagedestroy( $canvas );
?>
<img src="img/aj_matrix.gif">

Page 227 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

Output

Water mark Text on an Image

<?php
$orginalimg = "img/ajmatrix.gif";
$watermark = imagecreatefromjpeg("img/dr.jpg");
$text_color = imagecolorallocate($watermark, 0, 0, 0);
imagefttext($watermark,10,0,5,15,$text_color,"monofont.ttf","AJS");

$im=imagejpeg($watermark,$orginalimg);
?>
<img src="<?php echo $orginalimg?>">
Output

Page 228 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

OOPS (Object Oriented Programming)

Encapsulation

Encapsulation is one of the four fundamental OOP concepts. The other three are
inheritance, polymorphism, and abstraction.

Encapsulation is the technique of making the fields in a class private and providing access to the
fields via public methods. If a field is declared private, it cannot be accessed by anyone outside
the class, thereby hiding the fields within the class. For this reason, encapsulation is also referred
to as data hiding.

Encapsulation can be described as a protective barrier that prevents the code and data being
randomly accessed by other code defined outside the class. Access to the data and code is tightly
controlled by an interface.

The main benefit of encapsulation is the ability to modify our implemented code without breaking
the code of others who use our code. With this feature Encapsulation gives maintainability,
flexibility and extensibility to our code.

Example:

Let us look at an example that depicts encapsulation:

/* File name : EncapTest.java */


public class EncapTest{

private String name;


private String idNum;
private int age;

public int getAge(){


return age;
}

public String getName(){


return name;
}

public String getIdNum(){


return idNum;
}

public void setAge( int newAge){


age = newAge;
}

public void setName(String newName){


name = newName;
}

public void setIdNum( String newId){

Page 229 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

idNum = newId;
}
}

The public methods are the access points to this class.s fields from the outside java world.
Normally these methods are referred as getters and setters. Therefore any class that wants to
access the variables should access them through these getters and setters.

The variables of the EncapTest class can be access as below::

/* File name : RunEncap.java */


public class RunEncap{

public static void main(String args[]){


EncapTest encap = new EncapTest();
encap.setName("James");
encap.setAge(20);
encap.setIdNum("12343ms");

System.out.print("Name : " + encap.getName()+


" Age : "+ encap.getAge());
}
}

This would produce following result:

Name : James Age : 20

Benefits of Encapsulation:

 The fields of a class can be made read-only or write-only.

 A class can have total control over what is stored in its fields.

 The users of a class do not know how the class stores its data. A class can change the data
type of a field, and users of the class do not need to change any of their code.

Inheritance
Inheritance can be defined as the process where one object acquires the properties of
another. With the use of inheritance the information is made manageable in a hierarchical order.

When we talk about inheritance the most commonly used key words would be extends and
implements. These words would determine whether one object IS-A type of another. By using
these keywords we can make one object acquire the properties of another object.

IS-A Relationship:

IS-A is a way of saying : This object is a type of that object. Let us see how the extends keyword
is used to achieve inheritance.

public class Animal{

Page 230 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

public class Mammal extends Animal{


}

public class Reptile extends Animal{


}

public class Dog extends Mammal{


}

Now based on the above example, In Object Oriented terms following are true:

 Animal is the superclass of Mammal class.

 Animal is the superclass of Reptile class.

 Mammal and Reptile are sub classes of Animal class.

 Dog is the subclass of both Mammal and Animal classes.

Now if we consider the IS-A relationship we can say:

 Mammal IS-A Animal

 Reptile IS-A Animal

 Dog IS-A Mammal

 Hence : Dog IS-A Animal as well

With use of the extends keyword the subclasses will be able to inherit all the properties of the
superclass except for the private properties of the superclass.

We can assure that Mammal is actually an Animal with the use of the instance operator.

Example:

public class Dog extends Mammal{


public static void main(String args[]){

Animal a = new Animal();


Mammal m = new Mammal();
Dog d = new Dog();

System.out.println(m instanceof Animal);


System.out.println(d instanceof Mammal);
System.out.println(d instanceof Animal);
}
}

This would produce following result:

Page 231 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

true
true
true

Since we have a good understanding of the extends keyword let us look into how the implements
keyword is used to get the IS-A relationship.

The implements keyword is used by classes by inherit from interfaces. Interfaces can never be
extended.

Example:

public interface Animal {}

public class Mammal implements Animal{


}

public class Dog extends Mammal{


}

The instanceof Keyword:

Let us use the instanceof operator to check determine whether Mammal is actually an Animal,
and dog is actually an Animal

interface Animal{}

class Mammal implements Animal{}

class Dog extends Mammal{


public static void main(String args[]){

Mammal m = new Mammal();


Dog d = new Dog();

System.out.println(m instanceof Animal);


System.out.println(d instanceof Mammal);
System.out.println(d instanceof Animal);
}
}

This would produce following result:

true
true
true

HAS-A relationship:

These relationships are mainly based on the usage. This determines whether a certain class HAS-
A certain thing. This relationship helps to reduce duplication of code as well as bugs.

Page 232 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

Lets us look into an example:

public class Vehicle{}


public class Speed{}
public class Van extends Vehicle{
private Speed sp;
}

This shows that class Van HAS-A Speed. By having a separate class for Speed we do not have to
put the entire code that belongs to speed inside the Van class., which makes it possible to reuse
the Speed class in multiple applications.

In Object Oriented feature the users do not need to bother about which object is doing the real
work. To achieve this, the Van class hides the implementation details from the users of the Van
class. SO basically what happens is the users would ask the Van class to do a certain action and
the Vann class will either do the work by itself or ask another class to perform the action.

A very important fact to remember is that Java only supports only single inheritance. This means
that a class cannot extend more than one class. Therefore following is illegal:

public class extends Animal, Mammal{}

Polymorphism
Polymorphism is the ability of an object to take on many forms.Polymorphism is different
implementations of methods with same signatures in a class hierarchy.
Ploymorphisms may be classified as

1. Interface based -- achieved when two classes implement the same interface providing
different implementations of the interface methods

2. Inheritance based -- achieved when a derived class provides a different implementation of


a overridable method of a base class.

OR

1. Compile time polymorphism -- achieved when a derived class overrides a base class
method or implements an interface method.

2. Runtime polymorphism -- achieved when a derived class provides a different


implementation of a 'virtual' method of the base class.

Example:

Let us look at an example.

public interface Vegetarian{}


public class Animal{}S
public class Deer extends Animal implements Vegetarian{}

Now the Deer class is considered to be polymorphic since this has multiple inheritance. Following
are true for the above example:

Page 233 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

 A Deer IS-A aAnimal

 A Deer IS-A Vegetarian

 A Deer IS-A Deer

 A Deer IS-A Object

When we apply the reference variable facts to a Deer object reference, the following declarations
are legal:Deer d = new Deer();
Animal a = d;
Vegetarian v = d;
Object o = d;

All the reference variables d,a,v,o refer to the same Deer object in the heap.
Abstraction

Abstraction refers to the ability to make a class abstract in OOP. An abstract class is one that
cannot be instantiated. All other functionality of the class still exists, and its fields, methods, and
constructors are all accessed in the same manner. You just cannot create an instance of the
abstract class.

If a class is abstract and cannot be instantiated, the class does not have much use unless it is
subclassed. This is typically how abstract classes come about during the design phase. A parent
class contains the common functionality of a collection of child classes, but the parent class itself
is too abstract to be used on its own.

Abstract Class:

Use the abstract keyword to declare a class abstract. The keyword appears in the class
declaration somewhere before the class keyword.

/* File name : Employee.java */


public abstract class Employee
{
private String name;
private String address;
private int number;
public Employee(String name, String address, int number)
{
System.out.println("Constructing an Employee");
this.name = name;
this.address = address;
this.number = number;
}
public double computePay()
{
System.out.println("Inside Employee computePay");

Page 234 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

return 0.0;
}
public void mailCheck()
{
System.out.println("Mailing a check to " + this.name
+ " " + this.address);
}
public String toString()
{
return name + " " + address + " " + number;
}
public String getName()
{
return name;
}
public String getAddress()
{
return address;
}
public void setAddress(String newAddress)
{
address = newAddress;
}
public int getNumber()
{
return number;
}
}

Notice that nothing is different in this Employee class. The class is now abstract, but it still has
three fields, seven methods, and one constructor.

Now if you would try as follows:

/* File name : AbstractDemo.java */


public class AbstractDemo
{
public static void main(String [] args)
{

/* Following is not allowed and would raise error */


Employee e = new Employee("George W.", "Houston, TX", 43);

System.out.println("\n Call mailCheck using


Employee reference--");
e.mailCheck();
}
}

Page 235 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

When you would compile above class then you would get following error:

Employee.java:46: Employee is abstract; cannot be instantiated


Employee e = new Employee("George W.", "Houston, TX", 43);
^
1 error1

Extending Abstract Class:

We can extend Employee class in normal way as follows:

/* File name : Salary.java */


public class Salary extends Employee
{
private double salary; //Annual salary
public Salary(String name, String address, int number, double
salary)
{
super(name, address, number);
setSalary(salary);
}
public void mailCheck()
{
System.out.println("Within mailCheck of Salary class ");
System.out.println("Mailing check to " + getName()
+ " with salary " + salary);
}
public double getSalary()
{
return salary;
}
public void setSalary(double newSalary)
{
if(newSalary >= 0.0)
{
salary = newSalary;
}
}
public double computePay()
{
System.out.println("Computing salary pay for " + getName());
return salary/52;
}
}

Here we cannot instantiate a new Employee, but if we instantiate a new Salary object, the Salary
object will inherit the three fields and seven methods from Employee.

Page 236 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

/* File name : AbstractDemo.java */


public class AbstractDemo
{
public static void main(String [] args)
{
Salary s = new Salary("Mohd Mohtashim", "Ambehta, UP",
3, 3600.00);
Salary e = new Salary("John Adams", "Boston, MA",
2, 2400.00);

System.out.println("Call mailCheck using


Salary reference --");
s.mailCheck();
System.out.println("\n Call mailCheck using
Employee reference--");
e.mailCheck();
}
}

This would produce following result:

Constructing an Employee
Constructing an Employee
Call mailCheck using Salary reference --
Within mailCheck of Salary class
Mailing check to Mohd Mohtashim with salary 3600.0
Call mailCheck using Employee reference--
Within mailCheck of Salary class
Mailing check to John Adams with salary 2400.

Abstract Methods:

If you want a class to contain a particular method but you want the actual implementation of that
method to be determined by child classes, you can declare the method in the parent class as
abstract.

The abstract keyword is also used to declare a method as abstract.An abstract methods consist of
a method signature, but no method body.

Abstract method would have no definition, and its signature is followed by a semicolon, not curly
braces as follows:

public abstract class Employee

private String name;

private String address;

Page 237 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

private int number;

public abstract double computePay();

//Remainder of class definition

Declaring a method as abstract has two results:

 The class must also be declared abstract. If a class contains an abstract method, the class
must be abstract as well.

 Any child class must either override the abstract method or declare itself abstract.

A child class that inherits an abstract method must override it. If they do not, they must be
abstract,and any of their children must override it.

Eventually, a descendant class has to implement the abstract method; otherwise, you would have
a hierarchy of abstract classes that cannot be instantiated.

If Salary is extending Employee class then it is required to implement computePay() method as


follows:

/* File name : Salary.java */


public class Salary extends Employee
{
private double salary; //Annual salary

public double computePay()


{
System.out.println("Computing salary pay for " + getName());
return salary/52;
}

//Remainder of class definition


}

Interface
An interface is a collection of abstract methods. Aclass implements an interface, thereby inheriting
the abstract methods of the interface.

An interface is not a class. Writing an interface is similar to writing a class, but they are two
different concepts. A class describes the attributes and behaviors of an object. An interface
contains behaviors that a class implements.

Unless the class that implements the interface is abstract, all the methods of the interface need to
be defined in the class.

An interface is similar to a class in the following ways:

Page 238 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

 An interface can contain any number of methods.

 An interface is written in a file with a .java extension, with the name of the interface
matching the name of the file.

 The bytecode of an interface appears in a .class file.

 Interfaces appear in packages, and their corresponding bytecode file must be in a directory
structure that matches the package name.

However, an interface is different from a class in several ways, including:

 You cannot instantiate an interface.

 An interface does not contain any constructors.

 All of the methods in an interface are abstract.

 An interface cannot contain instance fields. The only fields that can appear in an interface
must be declared both static and final.

 An interface is not extended by a class; it is implemented by a class.

 An interface can extend multiple interfaces.

Declaring Interfaces:

The interface keyword is used to declare an interface. Here is a simple example to declare an
interface:

Encapsulation can be described as a protective barrier that prevents the code and data being
randomly accessed by other code defined outside the class. Access to the data and code is tightly
controlled by an interface.

The main benefit of encapsulation is the ability to modify our implemented code without breaking
the code of others who use our code. With this feature Encapsulation gives maintainability,
flexibility and extensibility to our code.

Example:

Let us look at an example that depicts encapsulation:

/* File name : NameOfInterface.java */


import java.lang.*;
//Any number of import statements

public interface NameOfInterface


{
//Any number of final, static fields
//Any number of abstract method declarations\
}

Interfaces have the following properties:

Page 239 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

 An interface is implicitly abstract. You do not need to use the abstract keyword when
declaring an interface.

 Each method in an interface is also implicitly abstract, so the abstract keyword is not
needed.

 Methods in an interface are implicitly public.

Example:

/* File name : Animal.java */


interface Animal {

public void eat();


public void travel();
}

Implementing Interfaces:

When a class implements an interface, you can think of the class as signing a contract, agreeing
to perform the specific behaviors of the interface. If a class does not perform all the behaviors of
the interface, the class must declare itself as abstract.

Aclass uses the implements keyword to implement an interface. The implements keyword
appears in the class declaration following the extends portion of the declaration.

/* File name : MammalInt.java */


public class MammalInt implements Animal{

public void eat(){


System.out.println("Mammal eats");
}

public void travel(){


System.out.println("Mammal travels");
}

public int noOfLegs(){


return 0;
}

public static void main(String args[]){


MammalInt m = new MammalInt();
m.eat();
m.travel();
}
}

This would produce following result:

Mammal eats

Page 240 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

Mammal travels

When overriding methods defined in interfaces there are several rules to be followed:

 Checked exceptions should not be declared on implementation methods other than the
ones declared by the interface method or subclasses of those declared by the interface
method.

 The signature of the interface method and the same return type or subtype should be
maintained when overriding the methods.

 An implementation class itself can be abstract and if so interface methods need not be
implemented.

When implementation interfaces there are several rules:

 A class can implement more than one interface at a time.

 A class can extend only one class, but implement many interface.

 An interface itself can extend another interface. An interface cannot extend another
interface.

Extending Interfaces:

An interface can extend another interface, similarly to the way that a class can extend another
class. The extends keyword is used to extend an interface, and the child interface inherits the
methods of the parent interface.

The following Sports interface is extended by Hockey and Football interfaces.

//Filename: Sports.java
public interface Sports
{
public void setHomeTeam(String name);
public void setVisitingTeam(String name);
}

//Filename: Football.java
public interface Football extends Sports
{
public void homeTeamScored(int points);
public void visitingTeamScored(int points);
public void endOfQuarter(int quarter);
}

//Filename: Hockey.java
public interface Hockey extends Sports
{
public void homeGoalScored();
public void visitingGoalScored();
public void endOfPeriod(int period);
public void overtimePeriod(int ot);

Page 241 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

The Hockey interface has four methods, but it inherits two from Sports; thus, a class that
implements Hockey needs to implement all six methods. Similarly, a class that implements
Football needs to define the three methods from Football and the two methods from Sports.

Extending Multiple Interfaces:

A Java class can only extend one parent class. Multiple inheritance is not allowed. Interfaces are
not classes, however, and an interface can extend more than one parent interface.

The extends keyword is used once, and the parent interfaces are declared in a comma-separated
list.

For example, if the Hockey interface extended both Sports and Event, it would be declared as:

public interface Hockey extends Sports, Event

Tagging Interfaces:

The most common use of extending interfaces occurs when the parent interface does not contain
any methods. For example, the MouseListener interface in the java.awt.event package extended
java.util.EventListener, which is defined as:

package java.util;
public interface EventListener
{}

An interface with no methods in it is referred to as a tagging interface. There are two basic
design purposes of tagging interfaces:

Creates a common parent: As with the EventListener interface, which is extended by dozens of
other interfaces in the Java API, you can use a tagging interface to create a common parent
among a group of interfaces. For example, when an interface extends EventListener, the JVM
knows that this particular interface is going to be used in an event delegation scenario.

Adds a data type to a class: This situation is where the term tagging comes from. A class that
implements a tagging interface does not need to define any methods (since the interface does not
have any), but the class becomes an interface type through polymorphism.

Abstract Class and Insterface Examples

<?php

abstract class animal

abstract function getowned();

private $age;

protected function __construct($age) {

Page 242 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

$this->age = $age;

public function getage()

return $this->age;

interface insurable {

public function getvalue();

class pet extends animal implements insurable {

private $name;

public function __construct($name,$age) {

parent::__construct($age);

$this->name = $name;

public function getname() {

return $this->name;

public function getowned() {

return ("Owner String");

public function getvalue() {

return ("Priceless");

class house implements insurable {

public function getvalue() {

return ("Rising fast");

Page 243 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

?>

<body><h1>Abstract class code</h1>

<?php

$ram = new pet("Ramasubbu",6);

$catage = $ram -> getage();

$catname = $ram -> getname();

print "$catname is $catage years old!<br><br>";

if ($ram instanceof pet) print ("Ramasubbu is a pet<br>");

if ($ram instanceof animal) print ("Ramasubbu is an animal<br>");

if ($ram instanceof house) print ("Ramasubbu is a house<br>");

if ($ram instanceof insurable) print ("Ramasubbu is insurable<br>");

?>
Difference between abstract class and interface

A class implementing an interface must implement all of the methods defined in the interface,
while a class extending an abstract class need not implement any of the methods defined in the
abstract class. Additionally, a class extending an abstract class can implement an infinite number
of it's own methods.

Another key difference between abstract class and interface is that , in abstract class we can put
sharable code, but that is not possible in case of interface.

Another key difference between abstract class and interface is that, We can use interface as
marker, (we can use abstract class also as abstract but then we can't extends any other class,
so it is better always use interface as marker)

Marker===> An interface having no methods is called as a Marker Interface.


=======================================================
This should be a lot more obvious than people make it out to be.

The difference between an interface and an abstract class, is that an interface does not define the
behavior of an object.
Rather, it defines how you work with a class.

While Abstract Classes are made for other Class builders who are going to EXTEND a "abstract"
parent class.
The abstract class will tell what methods to use without changing it, and what methods you can
implement in your Child class.

Page 244 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

What ever the OOP language used, it should be the same concept.(Those are pure OOP concepts)

mysql_ping($connectionobject)

mysql_ping($connectionobject) — Ping a server connection or reconnect if there is no connection

How to get the arguments length

function sample($a)

echo func_num_args(); // Output - 1

How to get the function arguments

function sample($a)

print_r(func_get_args()); // Output display the given argument values in array format.

“Final” Keyword
PHP 5 introduces the final keyword, which prevents child classes from overriding a method by
prefixing the definition with final. If the class itself is being defined final then it cannot be
extended.

Example #1 Final methods example

<?php

class BaseClass {

public function test() {

echo "BaseClass::test() called\n";

final public function moreTesting() {

echo "BaseClass::moreTesting() called\n";

class ChildClass extends BaseClass {

Page 245 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

public function moreTesting() {

echo " BaseClass::moreTesting() called\n";

// Results in Fatal error: Cannot override final method BaseClass::moreTesting()

?>

Example #2 Final class example

<?php

final class BaseClass {

public function test() {

echo "BaseClass::test() called\n";

// Here it doesn't matter if you specify the function as final or not

final public function moreTesting() {

echo "BaseClass::moreTesting() called\n";

class ChildClass extends BaseClass {

// Results in Fatal error: Class ChildClass may not inherit from final class (BaseClass)

?>

“Static” Keyword
Declaring class properties or methods as static makes them accessible without needing an
instantiation of the class. A property declared as static can not be accessed with an instantiated
class object (though a static method can).

Because static methods are callable without an instance of the object created, the pseudo-variable
$this is not available inside the method declared as static.

Static properties cannot be accessed through the object using the arrow operator ->.

Page 246 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

Calling non-static methods statically generates an E_STRICT level warning.

Like any other PHP static variable, static properties may only be initialized using a literal or
constant; expressions are not allowed. So while you may initialize a static property to an integer
or array (for instance), you may not initialize it to another variable, to a function return value, or
to an object.

<?php

class Foo

public static $my_static = 'foo';

public function staticValue() {

return self::$my_static;

class Bar extends Foo

public function fooStatic() {

return parent::$my_static;

print 'Foo::$my_static - '.Foo::$my_static . "<br>";

$foo = new Foo();

print '$foo->staticValue() - '.$foo->staticValue() . "<br>";

print '$foo->my_static - '.$foo->my_static . "<br>"; // Undefined "Property" my_static (If

this variable is not Staic then the


error will come) – (We set the
Static variable – so this line output
is empty)

print 'Bar::$my_static - '.Bar::$my_static . "<br>";

$bar = new Bar();

Page 247 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

print '$bar->fooStatic() - '.$bar->fooStatic() . "<br>";

?>

Output

Foo::$my_static - foo
$foo->staticValue() - foo
$foo->my_static -
Bar::$my_static - foo
$bar->fooStatic() - foo

Overloading
Overloading in PHP provides means to dynamically "create" properties and methods. These
dynamic entities are processed via magic methods one can establish in a class for various action
types.

<?php
class Foo
{
public function __call($method, $args)
{
echo "Called method $method";
}
}

$foo = new Foo;

$foo->bar(); // Called method bar


$foo->baz(); // Called method baz
?>

Another one Good Example

<?php
class A
{
function A() { }
function ech() // 0 – arguments
{
$a = func_get_args();
for( $t=0;$t<count($a); $t++ )
{
echo $a[$t];
}
echo "<br />";
}

Page 248 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

}
$test = new A();
$test->ech(0,1,2,3,4,5,6,7,8,9); // 10 - Arguments
$test->ech("Ramasubbu"); // 1 - Argument
?>
The function defined place that function have no arguments. So the function callable place put
more than one arguments.

But the function defined place that function have 2 arguments, that function callable place the
function have 1 argument then the warning error will occur.

The below program is a error code. See the error place.

<?php

class A

function A() { }

function ech($a,$b) // 2 – arguments

$a = func_get_args();

for( $t=0;$t<count($a); $t++ )

echo $a[$t];

echo "<br />";

$test = new A();

$test->ech(0,1,2,3,4,5,6,7,8,9); // 10 – Arguments // Run very well


(10>2)

$test->ech("Ramasubbu"); // 1 – Argument // Warning: Missing argument 2 for


A::ech(), called in F:\xampp\htdocs\classdemo\overloading.php on line 35 and defined in
F:\xampp\htdocs\classdemo\overloading.php on line no

?>

Page 249 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

Overridding
<?php

class vehicle {

var $brand_name;

var $number_of_wheels;

var $seating_capacity;

function message() {

echo "the vehicle class";

class car extends vehicle {

var $doors;

var $rooftype;

var $powersteering;

var $powerwindows;

function message() {

echo "the car class";

parent::message() // or vehicle::message();

$merk= new car;

$merk->message();

?>

The Base and the Child classes have the same named member function then, its called function
overriding.

MYSQL - Views
VIEW is a virtual table, which acts like a table but actually it contains no data. That is based on
the result set of a SELECT statement. A VIEW consists rows and columns from one or more than
one tables. A VIEW is a query that‘s stored as an object. A VIEW is nothing more than a way to
select a subset of table‘s columns.

Page 250 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

When you defined a view then you can reference it like any other table in a database

A VIEW provides as a security mechanism also. VIEWS ensures that users are able to modify and
retrieve only that data which seen by them.

mysql> SELECT * FROM Client;

+------+---------------+----------+

| C_ID | Name | City |

+------+---------------+----------+

|1 | A K Ltd | Delhi |

|2 | V K Associate | Mumbai |

|3 | R K India | Banglore |

|4 | R S P Ltd | Kolkata |

|5 | A T Ltd | Delhi |

|6 | D T Info | Delhi |

+------+---------------+----------+

6 rows in set (0.00 sec)

mysql> SELECT * FROM Products;

+---------+-------------+------+

| Prod_ID | Prod_Detail | C_ID |

+---------+-------------+------+

| 111 | Monitor |1 |

| 112 | Processor |2 |

| 113 | Keyboard |2 |

| 114 | Mouse |3 |

| 115 | CPU |5 |

+---------+-------------+------+

5 rows in set (0.00 sec)

Example : Create View Statement

mysql> CREATE VIEW Supp_Client AS

-> SELECT * FROM Client

Page 251 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

-> WHERE C_ID IN (

-> SELECT C_ID FROM Products)

-> WITH CHECK OPTION;

Query OK, 0 rows affected (0.05 sec)

mysql> SELECT * FROM Supp_Client;

+------+---------------+----------+

| C_ID | Name | City |

+------+---------------+----------+

|1 | A K Ltd | Delhi |

|2 | V K Associate | Mumbai |

|3 | R K India | Banglore |

|5 | A T Ltd | Delhi |

+------+---------------+----------+

4 rows in set (0.03 sec)

In the following example we include the WHERE clause with the select statement of view. Then
MySQL adds this condition to the VIEW definition when executing the statement for further
restricting the result. Example :

mysql> SELECT * FROM Supp_Client WHERE City='Delhi';

+------+---------+-------+

| C_ID | Name | City |

+------+---------+-------+

|1 | A K Ltd | Delhi |

|5 | A T Ltd | Delhi |

+------+---------+-------+

2 rows in set (0.04 sec)

ALTER VIEW Statement

By the ALTER VIEW Statement we can change the definition of a view. This statement is useful to
modify a view without dropping it. ALTER VIEW statement syntax is similar to CREATE VIEW
Statement and effect is same as the CREATE OR REPLACE VIEW. The general syntax of ALTER
VIEW Statement is :

ALTER VIEW view_name [(column_list)] [WITH ENCRYPTION] AS


select_statement [WITH CHECK OPTION]

Page 252 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

In the following example we are altering the view definition that we have created above. In this
we add one more column by the name of Prod_Detail of Products table. Example of Altering the
View Statement :

mysql> ALTER VIEW Supp_Client AS

-> SELECT Client.C_ID, Client.Name, Client.City,

-> Products.Prod_Detail from Client, Products

-> WHERE Client.C_ID=Products.C_ID;

Query OK, 0 rows affected (0.01 sec)

mysql> SELECT * FROM Supp_Client;

+------+---------------+----------+-------------+

| C_ID | Name | City | Prod_Detail |

+------+---------------+----------+-------------+

|1 | A K Ltd | Delhi | Monitor |

|2 | V K Associate | Mumbai | Processor |

|2 | V K Associate | Mumbai | Keyboard |

|3 | R K India | Banglore | Mouse |

|5 | A T Ltd | Delhi | CPU |

+------+---------------+----------+-------------+

5 rows in set (0.02 sec)

DROP VIEW Statement

For dropping a view you can use the DROP VIEW Statement. When view is dropped but it has no
effect on the underlying tables. After dropping a view if you issue any query that reference a
dropped view then you get an error message. But dropping a table that reference any view does
not drop the view automatically you have to dropt the view explicitly. The general syntax of DROP
VIEW Statement is :

DROP VIEW view_name;

In the following example we are dropping the view that we have created above. Example of
Dropping the View Statement :

mysql> DROP VIEW Supp_Client;

Query OK, 0 rows affected (0.00 sec)

mysql> SELECT * FROM Supp_Client;

Page 253 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

ERROR 1146 (42S02): Table 'employee.supp_client' doesn't exist

MYSQL – Triggers
» MySQL Triggers » Create the First Trigger in MySQL

Create the First Trigger in MySQL

Let‘s start creating the first trigger in MySQL by following a simple scenario. In the sample
database, we have employees table as follows:

CREATE TABLE `employees` (

`employeeNumber` int(11) NOT NULL,

`lastName` varchar(50) NOT NULL,

`firstName` varchar(50) NOT NULL,

`extension` varchar(10) NOT NULL,

`email` varchar(100) NOT NULL,

`officeCode` varchar(10) NOT NULL,

`reportsTo` int(11) default NULL,

`jobTitle` varchar(50) NOT NULL,

PRIMARY KEY (`employeeNumber`)

Now you want to keep the changes of employee's data in another table whenever data of an
employee's record changed. In order to do so you create a new table called employees_audit to
keep track the changes.

CREATE TABLE employees_audit (

id int(11) NOT NULL AUTO_INCREMENT,

employeeNumber int(11) NOT NULL,

lastname varchar(50) NOT NULL,

changedon datetime DEFAULT NULL,

action varchar(50) DEFAULT NULL,

PRIMARY KEY (id)

In order to keep track the changes of last name of employee we can create a trigger that is fired
before we make any update on the employees table. Here is the source code of the trigger

Page 254 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

DELIMITER $$

CREATE TRIGGER before_employee_update

BEFORE UPDATE ON employees

FOR EACH ROW BEGIN

INSERT INTO employees_audit

SET action = 'update',

employeeNumber = OLD.employeeNumber,

lastname = OLD.lastname,

changedon = NOW(); END$$

DELIMITER ;

You can test the trigger which created by updating last name of any employee in employees table.
Suppose we update last name of employee which has employee number is 3:

UPDATE employees

SET lastName = 'Phan'

WHERE employeeNumber = 1056

Now when you can see the changes audited automatically in the employees_audit table by
executing the following query

SELECT *

FROM employees_audit

In order to create a trigger you use the following syntax:

CREATE TRIGGER trigger_name trigger_time trigger_event

ON table_name

FOR EACH ROW

BEGIN

...

END

* CREATE TRIGGER statement is used to create triggers.

* The trigger name should follow the naming convention [trigger time]_[table name]_[trigger
event], for example before_employees_update

Page 255 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

* Trigger activation time can be BEFORE or AFTER. You must specify the activation time when
you define a trigger. You use BEFORE when you want to process action prior to the change being
made in the table and AFTER if you need to process action after changes are made.

* Trigger event can be INSERT, UPDATE and DELETE. These events cause trigger to fire and
process logic inside trigger body. A trigger only can fire with one event. To define trigger which are
fired by multiple events, you have to define multiple triggers, one for each event. Be noted that
any SQL statements make update data in database table will cause trigger to fire. For example,
LOAD DATA statement insert records into a table will also cause the trigger associated with that
table to fire.

* A trigger must be associated with a specific table. Without a table trigger does not exist so
you have to specify the table name after the ON keyword.

* You can write the logic between BEGIN and END block of the trigger.

* MySQL gives you OLD and NEW keyword to help you write trigger more efficient. The OLD
keyword refers to the existing row before you update data and the NEW keyword refers to the
new row after you update data.

Regular Expersions in MYSQL


If you really want to force a REGEXP comparison to be case sensitive, use the BINARY keyword to
make one of the strings a binary
string. This query matches only lowercase ―b‖ at the beginning of a name:

mysql> SELECT * FROM pet WHERE name REGEXP BINARY '^b';

To find names ending with “fy”, use “$” to match the end of the name:
mysql> SELECT * FROM pet WHERE name REGEXP 'fy$';
+--------+--------+---------+------+------------+-------+
| name | owner | species | sex | birth | death |
+--------+--------+---------+------+------------+-------+
| Fluffy | Harold | cat | f | 1993-02-04 | NULL |
| Buffy | Harold | dog | f | 1989-05-13 | NULL |
+--------+--------+---------+------+------------+-------+

To find names containing a “w”, use this query:


mysql> SELECT * FROM pet WHERE name REGEXP 'w';

+----------+-------+---------+------+------------+------------+
| name | owner | species | sex | birth | death |
+----------+-------+---------+------+------------+------------+
| Claws | Gwen | cat | m | 1994-03-17 | NULL |
| Bowser | Diane | dog | m | 1989-08-31 | 1995-07-29 |
| Whistler | Gwen | bird | NULL | 1997-12-09 | NULL |
+----------+-------+---------+------+------------+------------+

Because a regular expression pattern matches if it occurs anywhere in the value, it is not
necessary in the previous query to put a
wildcard on either side of the pattern to get it to match the entire value like it would be if you
used an SQL pattern.

Page 256 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

To find names containing exactly five characters, use “^” and “$” to match the
beginning and end of the name, and five instances
of “.” in between:
mysql> SELECT * FROM pet WHERE name REGEXP '^.....$';

+-------+--------+---------+------+------------+-------+
| name | owner | species | sex | birth | death |
+-------+--------+---------+------+------------+-------+
| Claws | Gwen | cat | m | 1994-03-17 | NULL |
| Buffy | Harold | dog | f | 1989-05-13 | NULL |
+-------+--------+---------+------+------------+-------+

You could also write the previous query using the {n} (“repeat-n-times”) operator:
mysql> SELECT * FROM pet WHERE name REGEXP '^.{5}$';

+-------+--------+---------+------+------------+-------+
| name | owner | species | sex | birth | death |
+-------+--------+---------+------+------------+-------+
| Claws | Gwen | cat | m | 1994-03-17 | NULL |
| Buffy | Harold | dog | f | 1989-05-13 | NULL |
+-------+--------+---------+------+------------+-------+
Insert Bulk Data using Importing File option
LOAD DATA LOCAL INFILE '/path/pet.txt' INTO TABLE pet;

User Defined MYSQL Variables


mysql> SELECT @min_price:=MIN(price),@max_price:=MAX(price) FROM shop;
mysql> SELECT * FROM shop WHERE price=@min_price OR price=@max_price;
+---------+--------+-------+
| article | dealer | price |
+---------+--------+-------+
| 0003 | D | 1.25 |
| 0004 | D | 19.95 |
+---------+--------+-------+

Sample Critical Queies


Each twin has a status code called event. The query shown here is used to select all twin pairs
combined by event. This indicates in how many pairs both twins are finished, in how many pairs
one twin is finished and the other refused, and so on.

SELECT
t1.event,
t2.event,
COUNT(*)
FROM
lentus AS t1,
lentus AS t2,
twin_project AS tp

Page 257 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

WHERE
/* We are looking at one pair at a time */
t1.id = tp.id
AND t1.tvab=tp.tvab
AND t1.id = t2.id
/* Just the screening survey */
AND tp.survey_no = 5
/* This makes each pair only appear once */
AND t1.tvab='1' AND t2.tvab='2'
GROUP BY
t1.event, t2.event;

SELECT
CONCAT(p1.id, p1.tvab) + 0 AS tvid,
CONCAT(p1.christian_name, ' ', p1.surname) AS Name,
p1.postal_code AS Code,
p1.city AS City,
pg.abrev AS Area,
IF(td.participation = 'Aborted', 'A', ' ') AS A,
p1.dead AS dead1,
l.event AS event1,
td.suspect AS tsuspect1,
id.suspect AS isuspect1,
td.severe AS tsevere1,
id.severe AS isevere1,
p2.dead AS dead2,
l2.event AS event2,
h2.nurse AS nurse2,
h2.doctor AS doctor2,
td2.suspect AS tsuspect2,
id2.suspect AS isuspect2,
td2.severe AS tsevere2,
id2.severe AS isevere2,
l.finish_date
FROM
twin_project AS tp
/* For Twin 1 */
LEFT JOIN twin_data AS td ON tp.id = td.id
AND tp.tvab = td.tvab
LEFT JOIN informant_data AS id ON tp.id = id.id
AND tp.tvab = id.tvab
LEFT JOIN harmony AS h ON tp.id = h.id
AND tp.tvab = h.tvab
LEFT JOIN lentus AS l ON tp.id = l.id
AND tp.tvab = l.tvab
/* For Twin 2 */
LEFT JOIN twin_data AS td2 ON p2.id = td2.id
AND p2.tvab = td2.tvab
LEFT JOIN informant_data AS id2 ON p2.id = id2.id
AND p2.tvab = id2.tvab
LEFT JOIN harmony AS h2 ON p2.id = h2.id
AND p2.tvab = h2.tvab

Page 258 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

LEFT JOIN lentus AS l2 ON p2.id = l2.id


AND p2.tvab = l2.tvab,
person_data AS p1,
person_data AS p2,
postal_groups AS pg
WHERE
/* p1 gets main twin and p2 gets his/her twin. */
/* ptvab is a field inverted from tvab */
p1.id = tp.id AND p1.tvab = tp.tvab AND
p2.id = p1.id AND p2.ptvab = p1.tvab AND
/* Just the screening survey */
tp.survey_no = 5 AND
/* Skip if partner died before 65 but allow emigration (dead=9) */
(p2.dead = 0 OR p2.dead = 9 OR
(p2.dead = 1 AND
(p2.death_date = 0 OR
(((TO_DAYS(p2.death_date) - TO_DAYS(p2.birthday)) / 365)
>= 65))))
AND
(
/* Twin is suspect */
(td.future_contact = 'Yes' AND td.suspect = 2) OR
/* Twin is suspect - Informant is Blessed */
(td.future_contact = 'Yes' AND td.suspect = 1
AND id.suspect = 1) OR
/* No twin - Informant is Blessed */
(ISNULL(td.suspect) AND id.suspect = 1
AND id.future_contact = 'Yes') OR
/* Twin broken off - Informant is Blessed */
(td.participation = 'Aborted'
AND id.suspect = 1 AND id.future_contact = 'Yes') OR
/* Twin broken off - No inform - Have partner */
28
(td.participation = 'Aborted' AND ISNULL(id.suspect)
AND p2.dead = 0))
AND
l.event = 'Finished'
/* Get at area code */
AND SUBSTRING(p1.postal_code, 1, 2) = pg.code
/* Not already distributed */
AND (h.nurse IS NULL OR h.nurse=00 OR h.doctor=00)
/* Has not refused or been aborted */
AND NOT (h.status = 'Refused' OR h.status = 'Aborted'
OR h.status = 'Died' OR h.status = 'Other')
ORDER BY
tvid;

Page 259 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

Some explanations:

• CONCAT(p1.id, p1.tvab) + 0 AS tvid


We want to sort on the concatenated id and tvab in numerical order. Adding 0 to the result causes
MySQL to treat the result
as a number.

• Column id
This identifies a pair of twins. It is an index in all tables.

• Column tvab
This identifies a twin in a pair. It has a value of 1 or 2.

• Column ptvab
This is an inverse of tvab. When tvab is 1 this is 2, and vice versa. It exists to save typing and to
make it easier for MySQL to optimize the query.

This query demonstrates, among other things, how to do lookups on a table from the same table
with a join (p1 and p2). In the example, this is used to check whether a twin's partner died before
the age of 65. If so, the row is not returned.

All of the above exist in all tables with twin-related information. We have an index on both id,
tvab (all tables), and id, ptvab (person_data) to make queries faster.

When we did this work, our production machine was a 200MHz UltraSPARC, and on that
old hardware this query returned about 150 to 200 rows in less than one second. The
main table had 70,000 Rows.

Page 260 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

Page 261 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

Google API, Maps, Adwards, Adsense, Analytics and Visualization Code


URL Details
List Google all API links under : http://code.google.com/more/

Adwards

Adwards is used to give our own ads to google.

http://www.google.com/adwards

1. Signup in Google

2. Set your time zone and currency preferences (Automatically set the
below fields values)

1. Time zone country or territory: India

2. Time zone: (GMT+05:30) India Standard Time

3. Select a permanent currency for your account : Indian


Rupee (INR Rs.)
4. Click the ―Continue‖ button

3. Finally display the success message with ―Sign in to your AdWords account‖ url
and ―optimization tips.‖ url.

4. Optimization Tips url ->


http://adwords.google.com/support/aw/bin/static.py?hl=en&pa
ge=tips.html
Adsense

http://www.google.com/adsense

Fillup the personal detail form only. After confirmation from google, the adsense account will
active.

Maps

1. http://code.google.com/apis/maps/ - display the Maps API family

2. http://code.google.com/apis/maps/documentation/staticmaps/

Contents of the above url (2)


1. Audience
2. Usage Limits
3. Overview
4. URL Parameters
5. Parameter Usage
o Specifying Locations
 Latitudes and Longitudes

Page 262 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

 Addresses
o Denoting Sensor Usage
o Zoom Levels
o Image Sizes
o Image Formats
o Map Types
o Adding Markers
 Marker Styles
 Marker Locations
 Custom Icons
o Static Map Paths
 Path Styles
 Specifying Path Points
 Encoded Polylines
o Viewports
o Implicit Positioning of the Map Using Markers
6. More Information
Analytics

http://code.google.com/intl/en/apis/analytics/

Direct URL - http://www.google.com/analytics/

1. Click the ―Access Analytics‖ Button

2. Signup in Google

3. Create a new account with the below mentioned fields

1. Website's URL : http://www.sample.com

2. Account Name – Automatically comes from the Website‘s URL field


value

3. Time zone country or territory: India (―Select the Country‖)

4. Time zone: Automatically comes after selection the country.


5. Clickt the ―Continue‖ Button.

4. Fillup the Contact Information with below fields

1. Last Name

2. First Name

3. Country or territory

4. Click the ―Continue‖ button

5. Accept the User Aggrement – click the ―Create New Account‖ button

6. Copy and paste the code into your site.

Page 263 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

7. Note : Paste the google analytics api code before the </body> tag in your footer.

8. Click the ―Save and Finished‖ button

9. Display the registered site details page.

Visualization

Visual reference url -


http://code.google.com/apis/visualization/documentation/gallery.html

Display lot of chart designs

Select the desired design and get that design codes.

Payment Gateway APIs References


E-GOLD

<form action="https://www.e-gold.com/sci_asp/payments.asp" method=post>


<input type=hidden name="PAYMENT_AMOUNT" value="<AMOUNT>">
<input type=hidden name="SUGGESTED_MEMO" value = "<DESCRIPTION>">
<input type="hidden" name="PAYEE_ACCOUNT" value="<ACCOUNTNUMBER>">
<input type="hidden" name="PAYEE_NAME" value="<SITENAME>">
<input type=hidden name="PAYMENT_UNITS" value=1>
<input type=hidden name="PAYMENT_METAL_ID" value=1>
<input type="hidden" name="STATUS_URL" value="mailto:<ADMINEMAILID>">
<input type="hidden" name="NOPAYMENT_URL" value="<FAILUREURL>">
<input type="hidden" name="NOPAYMENT_URL_METHOD" value="POST">
<input type="hidden" name="PAYMENT_URL" value="<SUCCESSURL>">
<input type="hidden" name="PAYMENT_URL_METHOD" value="POST">
<input type="hidden" name="BAGGAGE_FIELDS" value="PROGL">
<input type="hidden" name="PROGL" value="01">
<input type=image src="../images/egoldlogo.gif" style="width:20%;height:50">
</form>
Normal Return Form

Hidden Text Field Name Hidden Text Field Value


PAYEE_ACCOUNT Same value sent by merchant system
PAYMENT_AMOUNT Same value sent by merchant system
PAYMENT_UNITS Same value sent by merchant system
PAYMENT_METAL_ID Value 1,2,3 or 4 indicating actual metal type
(Gold, Silver, Platinum, or Palladium) using in
purchase.
PAYMENT_BATCH_NUM The e-gold payment transaction Batch Number
(32 bit nonzero positive integer)
PAYER_ACCOUNT The Buyer‘s e-gold Account number

Page 264 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

Alternate Return Form

Hidden Text Field Name Hidden Text Field Value


PAYEE_ACCOUNT Same value sent by merchant system
PAYMENT_AMOUNT Same value sent by merchant system
PAYMENT_UNITS Same value sent by merchant system
PAYMENT_METAL_ID Same value sent by merchant.
PAYMENT_BATCH_NUM Zero (0)

INT GOLD

<form action="https://intgold.com/cgi-bin/webshoppingcart.cgi" target=_blank method="POST">


<input type="hidden" name="cmd" value="_xclick">
<input type="hidden" name="SELLERACCOUNTID" value="<ACCOUNTNUMBER>">
<input type="hidden" name="RETURNURL" value="<SUCCESSURL>">
<input type="hidden" name="CANCEL_RETURN" value="<FAILUREURL>">
<input type="hidden" name="CUSTOM1" value="amount">
<input type="hidden" name="CUSTOM2" value="status">
<input type="hidden" name="ITEM_NUMBER" value="<ITEMNUMBER>">
<input type="hidden" name="ITEM_NAME" value="<ITEMNAME>">
<input type="hidden" name="METHOD" value="POST">
<input type="hidden" name="RETURNPAGE" value="HTML">
<input type="hidden" name="AMOUNT" value=<AMOUNT>>
<input type=image src="../images/intgold_logo.gif" name="submit"
style="width:20%;height:50">
</form>

Return values:

$_POST['AMOUNT']
$_POST['TRANSACTION_ID']
$_POST['BUYERACCOUNTID']

PAYPAL REAL

<form action="https://www.paypal.com/cgi-bin/webscr" method="post">


<input type="hidden" name="cmd" value="_xclick">
<input type="hidden" name="business" value="<ACCOUNTNUMBER>">
<input type="hidden" name="item_name" value="<ITEMNAME>">
<input type="hidden" name="amount" value="<AMOUNT>">
<input type="hidden" name="no_note" value="1">
<input type="hidden" name="currency_code" value="<CURRENCYCODE>">
<input type="hidden" name="rm" value="2">
<input type="hidden" name="return" value="<SUCCESSURL>">
<input type="hidden" name="cancel_return" value="<FAILUREURL>">
<input type="image" src="https://www.paypal.com/en_US/i/btn/x-click-but6.gif"
name="submit">
</form>

Page 265 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

Return values

$_POST['payment_gross'] ->Amount
$_POST['txn_id'] -> Transaction ID
$_POST[‗mc_gross‘] -> Amount

PAYPAL TEST/SANDBOX

<form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post">


<input type="hidden" name="cmd" value="_xclick">
<input type="hidden" name="business" value="<ACCOUNTNUMBER>">
<input type="hidden" name="item_name" value="<ITEMNAME>">
<input type="hidden" name="amount" value="<AMOUNT>">
<input type="hidden" name="no_note" value="1">
<input type="hidden" name="currency_code" value="<CURRENCYCODE>">
<input type="hidden" name="rm" value="2">
<input type="hidden" name="return" value="<SUCCESSURL>">
<input type="hidden" name="cancel_return" value="<FAILUREURL>">
<input type="image" src="https://www.paypal.com/en_US/i/btn/x-click-but6.gif"
name="submit">
</form>

Return values

$_POST['payment_gross'] ->Amount
$_POST['txn_id'] -> Transaction ID
$_POST[‗mc_gross‘] -> Amount

STROM PAY

<form method="post" action="https://www.stormpay.com/stormpay/handle_gen.php">


<input type="hidden" name="generic" value="1">
<input type="hidden" name="payee_email" value=<ACCOUNTNUMBER> >
<input type="hidden" name="product_name" value="<PRODUCTNAME>">
<input type="hidden" name="user_id" value=1>
<input type="hidden" name="amount" value=<AMOUNT>>
<input type="hidden" name="quantity" value="1">
<input type="hidden" name="require_IPN" value="1">
<input type="hidden" name="notify_URL" value="<SITEURL>">
<input type="hidden" name="return_URL" value="<SUCCESSURL>">
<input type="hidden" name="cancel_URL" value="<FAILUREURL>">
<input type="hidden" name="subject_matter" value="CashCocktail Payment">
<input type=image src="../images/strompay.gif" style="width:75;height:30">
</form>

Return values:

$_POST['amount']
$_POST['transaction_id']
$_POST['payer_name']

Page 266 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

E BULLION

<form name="atip" method="post" action="https://atip.e-bullion.com/process.php">


<input type="hidden" name="ATIP_STATUS_URL" value="<SITEURL>">
<input type="hidden" name="ATIP_STATUS_URL_METHOD" value="POST">
<input type="hidden" name="ATIP_BAGGAGE_FIELDS" value="">
<input type="hidden" name="ATIP_SUGGESTED_MEMO" value="<DESCRIPTION>">
<input type="hidden" name="ATIP_FORCED_PAYER_ACCOUNT" value="">
<input type="hidden" name="ATIP_PAYER_FEE_AMOUNT" value="">
<input type="hidden" name="ATIP_PAYMENT_URL" value="<SUCCESSURL>">
<input type="hidden" name="ATIP_PAYMENT_URL_METHOD" value="POST">
<input type="hidden" name="ATIP_NOPAYMENT_URL" value="<FAILUREURL>">
<input type="hidden" name="ATIP_NOPAYMENT_URL_METHOD" value="POST">
<input type="hidden" name="ATIP_PAYMENT_FIXED" value="1">
<input type="hidden" name="ATIP_PAYEE_ACCOUNT" value="<ACCOUNTNUMBER>">
<input type="hidden" name="ATIP_PAYEE_NAME" value="<ACCOUNTNAME>">
<input type="hidden" name="ATIP_BUTTON" value="1">
<input type="hidden" name="ATIP_PAYMENT_AMOUNT" value="<AMOUNT>" >
<input type="hidden" name="ATIP_PAYMENT_UNIT" value="1">
<input type="hidden" name="ATIP_PAYMENT_METAL" value="1">
<input type="image" name="pay" src="https://secure.e-
bullion.com/banners/ebullion_button_1.gif">
</form>

Return values:

$_POST['ATIP_PAYMENT_AMOUNT']
$_POST['ATIP_TRANSACTION_ID']
$_POST['ATIP_ACCOUNT']

MONEY BOOKER

<form action="https://www.moneybookers.com/app/payment.pl" target="_blank">


<input type="hidden" name="pay_to_email" value="<ACCOUNTNUMBER>">
<input type="hidden" name="return_url" value="<SUCCESSURL>">
<input type="hidden" name="cancel_url" value="<FAILUREURL>">
<input type="hidden" name="language" value="EN">
<input type="hidden" name="amount" value="<AMOUNT>">
<input type="hidden" name="currency" value="<CURRENCYCODE>">
<input type=image src="../images/mb.jpg" style="width:75;height:30">
</form>

Return values:

$_POST['AMOUNT']
$_POST['TRANSACTION_ID']

ALERT PAY

<form action="https://www.alertpay.com/PayProcess.aspx" method="post">


<input type="hidden" name="ap_purchasetype" value="Item">
<input type="hidden" name="ap_merchant" value="<ADMINEMAILID>">

Page 267 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

<input type="hidden" name="ap_itemname" value="PTYW">


<input type="hidden" name="ap_currency" value="USD">
<input type="hidden" name="ap_returnurl" value="<SUCCESSURL>">
<input type="hidden" name="ap_quantity" value="1">
<input type="hidden" name="ap_description" value="PTYW">
<input type="hidden" name="ap_amount" value="<AMOUNT>">
<input type="hidden" name="ap_cancelurl" value="<FAILUREURL>">
<input type="image" src="../images/alertpay.gif" >
</form>

Return values:

$_POST['AMOUNT']
$_POST['TRANSACTION_ID']

SAFEPAY SOLUTIONS

<form action="https://www.safepaysolutions.com/index.php" method="post">


<input type="hidden" name="_ipn_act" value="_ipn_payment">
<input type="hidden" name="fid" value="a8966ef75849cd589a5c2e80310986">
<input type="hidden" name="itestmode" value="off">
<input type="hidden" name="notifyURL" value="">
<input type="hidden" name="returnURL" value="<SUCCESSURL>">
<input type="hidden" name="cancelURL" value="<FAILUREURL>">
<input type="hidden" name="notifyEml" value="">
<input type="hidden" name="iowner" value="<ACCOUNTNUMBER>">
<input type="hidden" name="ireceiver" value="<ACCOUNTNUMBER>">
<input type="hidden" name="iamount" value="<AMOUNT>">
<input type="hidden" name="itemName" value="<ITEMNAME>">
<input type="hidden" name="itemNum" value="1">
<input type="hidden" name="idescr" value="">
<input type="hidden" name="idelivery" value="3">
<input type="hidden" name="iquantity" value="1">
<input type="hidden" name="imultiplyPurchase" value="n">
<input type="hidden" name="colortheme" value="LightBlueYellow">
<input type="image" src="../images/safepay.jpg">
</form>

Return values:

$_POST['iamount']
$_POST['TRANSACTION_ID']

LIBERTY RESERVE
<form method="post" action="https://sci.libertyreserve.com">
<input type="hidden" name="lr_acc" value="<ACCOUNTNUMBER>">
<input type="hidden" name="lr_amnt" value="<AMOUNT>" />
<input type="hidden" name="AMOUNT" value="<AMOUNT>" />
<input type="hidden" name="lr_currency" value="LRUSD">
<input type="hidden" name="lr_comments" value="<COMMENTS>">
<input type="hidden" name="lr_merchant_ref" value="OID_000001">
<input type="hidden" name="lr_success_url" value="<SUCCESSURL>">

Page 268 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

<input type="hidden" name="lr_fail_url" value="<FAILUREURL>">


<input type="hidden" name="order_id" value="000001" />
<input type="hidden" name="item_name" value="<DESCRIPTION>" />
<input type="image" src="../images/lr.jpg" value="Buy!">
</form>

Return values:

$_POST['AMOUNT']
$_POST['lr_transfer']

PECUNIX

<form action="https://pri.pecunix.com/money.refined" method="post">


<input type="hidden" name="PAYEE_ACCOUNT" value="<ACCOUNTNUMBER>">
<input type="hidden" name="PAYMENT_AMOUNT " value="<AMOUNT>">
<input type="hidden" name="PAYMENT_URL" value="<SUCCESSURL>">
<input type="hidden" name="NOPAYMENT_URL" value="<FAILUREURL>">
<input type="hidden" name="STATUS_URL" value="">
<input type="hidden" name="STATUS_TYPE" value="FORM">
<input type="hidden" name="PAYMENT_URL_METHOD" value="POST">
<input type="hidden" name="NOPAYMENT_URL_METHOD" value="POST">
<input type="hidden" name="INPUT_HASH" value="A1213419A0C503FC2767891F21463751">
<input type="hidden" name="PAYMENT_UNITS" value="AUD">
<input type="hidden" name="WHO_PAYS_FEES" value="PAYER">
<input type="hidden" name="PAYMENT_ID" value="1234">
<input type="hidden" name="SUGGESTED_MEMO" value="Payment to gold-cart.com">
<input type="image" src="../images/pecunix.jpg" value="Buy!">
</form>

Return values:

$_POST['PAYMENT_AMOUNT']
$_POST['TRANSACTION_ID']

Paymate (Credit Card Payment Gateway)

<form
action="https://www.paymate.com/PayMate/ExpressPayment?mid='.$records[0]["creditcard_acc
ount_name"].'" method="post">
<input type="hidden" name="amt" value="'.$payamount.'">
<input type="hidden" name="amt_editable" value="N">
<input type="hidden" name="currency" value="'.$currency_code.'">
<input type="hidden" name="ref" value="'.$_SERVER['SERVER_NAME'].' Check out">
<input type="hidden" name="return"
value="'.$domain.'?do=returnpayment&status=yes&type=credit">
<input type="hidden" name="popup" value="'.$domain.'?do=returnpayment&status=no">
<input type="image" src="images/paymate.gif" name="submit" alt="'.$language['LANG435'].'">
</form>

Page 269 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

PSIGATE(Credit Card Payment Gateway)

<form action="https://devcheckout.psigate.com/htmlpost/htmlmessenger" method=post>


<input type=hidden name="merchantid" value="'.$records[0]["creditcard_account_name"].'">
<input type=hidden name="thanksurl"
value="'.$domain.'?do=returnpayment&status=yes&type=credit">
<input type=hidden name="nothanksurl" value="'.$domain.'?do=returnpayment&status=no">
<input type=hidden name="paymenttype" value="cc">
<input type=hidden name="orderid" value="">
<input type=hidden name="subtotal" value="'.$payamount.'">
<input type="image" src="images/psigate.gif" name="submit" alt="psi gate">
</form>

GOOGLE CHECKOUT

<form method="POST"
action="https://sandbox.google.com/checkout/cws/v2/Merchant/1234567890/checkoutForm"
accept-charset="utf-8">
<input type="hidden" name="item_name_1" value="Peanut Butter"/>
<input type="hidden" name="item_description_1" value="Chunky peanut butter."/>
<input type="hidden" name="item_quantity_1" value="1"/>
<input type="hidden" name="item_price_1" value="3.99"/>
<input type="hidden" name="item_currency_1" value="USD"/>
<input type="hidden" name="item_name_2" value="Grape Jelly"/>
<input type="hidden" name="item_description_2" value="16 oz. bottle of Concord grape jelly."/>
<input type="hidden" name="item_quantity_2" value="1"/>
<input type="hidden" name="item_price_2" value="4.49"/>
<input type="hidden" name="item_currency_2" value="USD"/>
<input type="hidden" name="ship_method_name_1" value="UPS Air"/>
<input type="hidden" name="ship_method_price_1" value="19.99"/>
<input type="hidden" name="ship_method_currency_1" value="USD"/>
<input type="hidden" name="ship_method_us_area_1" value="CONTINENTAL_48"/>
<input type="hidden" name="ship_method_name_2" value="UPS Ground"/>
<input type="hidden" name="ship_method_price_2" value="10.99"/>
<input type="hidden" name="ship_method_currency_2" value="USD"/>
<input type="hidden" name="ship_method_us_area_2" value="FULL_50_STATES"/>
<input type="hidden" name="tax_rate" value="0.0875"/>
<input type="hidden" name="tax_us_state" value="NY"/>
<input type="hidden" name="_charset_"/>
<input type="image" name="Google Checkout" alt="Fast checkout through Google"
src="http://sandbox.google.com/checkout/buttons/checkout.gif?merchant_id=1234567890&w=
180&h=46&style=white&variant=text&loc=en_US"
height="46" width="180"/>
</form>
In this example:

 The buyer will purchase two items: 1 Chunky Peanut Butter for $3.99 and 1 Grape Jelly for
$4.49.

 Two shipping options are available: UPS Air for $19.99, available if the buyer is within in
the continental 48 states; and UPS Ground for $10.00, available to buyers in all 50 states.

 Buyers in New York will be charged 8.75% tax on the item.

Page 270 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

Enabling the HTML API

Before you can start processing HTML posts in this manner, you must enable the HTML API in your
merchant account as follows:

1. Sign in to Google Checkout.


2. Click the Settings tab.
3. Click Integration.
4. Remove the check in the box beside 'For extra security, my company will only post digitally
signed XML shopping carts. (Google should reject all others)'
5. Click Save.

2Checkout.com
<form action="https://www.2checkout.com/2co/buyer/purchase" method="post">
<input type='hidden' name='sid' value='1417176'>
<input type='hidden' name='quantity' value='1'>
<input type='hidden' name='product_id'
value='<AJDF:output>$ses_acctype1</AJDF:output>'>
<input name="demo" value="N" type="hidden">
<input name="return_url" value="<AJDF:output>$siteurl</AJDF:output>?do=paysuc"
type="hidden">
<br>
<input src="images/2checkout.gif" name="submit" alt="Make payments with
2CheckOut" type="image" border="0">
</form>
SafePay
<form action=―https://www.safepaysolutions.com/index.php‖ method=―post‖>
<input type=―hidden‖ name=―_ipn_act‖ value=―_ipn_payment‖>
<input type=―hidden‖ name=―fid‖ value=―a8966ef75849cd589a5c2e80310986‖>
<input type=―hidden‖ name=―itestmode‖ value=―off‖>
<input type=―hidden‖ name=―notifyURL‖ value=――>
<input type=―hidden‖ name=―returnURL‖ value=―$this->successUrl―>
<input type=―hidden‖ name=―cancelURL‖ value=―$this->failureUrl―>
<input type=―hidden‖ name=―notifyEml‖ value=――>
<input type=―hidden‖ name=―iowner‖ value=―$this->ownerId―>
<input type=―hidden‖ name=―ireceiver‖ value=―$this->receiverId―>
<input type=―hidden‖ name=―iamount‖ value=―$this->amount―>
<input type=―hidden‖ name=―itemName‖ value=―Deposit Amount‖>
<input type=―hidden‖ name=―itemNum‖ value=―1‖>
<input type=―hidden‖ name=―idescr‖ value=――>
<input type=―hidden‖ name=―idelivery‖ value=―3‖>
<input type=―hidden‖ name=―iquantity‖ value=―1‖>
<input type=―hidden‖ name=―imultiplyPurchase‖ value=―n‖>
<input type=―hidden‖ name=―colortheme‖ value=―LightBlueYellow‖>
<input type=―image‖ src=―https://www.safepaysolutions.com/images/index_r1_c1.jpg‖
alt=―Pay through SafePay Solutions‖>
</form>

Page 271 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

PHP Used Defined Project Oriented Library Tracks

Library Lits

1. Get the Gmail, Yahoo, Hotmail and AOL address book contacts

2. Get site ranking information from the Alexa site

3. Convert the array to diagram

4. Convert image to ascii code art

5. Encode/Decode binary data with text characters

6. Automatic fill options for text fields

7. Take the Database Backup

8. Create the Bar Chart

9. Create Barcode

10. Given byte to Byte, Kilo byte, Mega byte, Giga byte, TB and Pb

11. Draw the Pie Chart

12. Correct text with abbreviations used by people in chats

13. Based Encryption and Decryption Program

14. Shows the Astronomy picture of today. Fetched from the NASA website

15. Daily Show the Artoon from www.adressa.no site

16. Daily retrieve joke from jokes2go site

17. Download images through Google

18. Work with Flickr photos

19. Get geographical location of the IP address using web service of http://www.geoplugin.com

20. Convert Gif animation file into multiple images

21. Translate the Site words with Google Translator

22. Convert the HTML page to Document

23. Which like relation calculation between two names

24. Convert original image to cartoon effect image

25. Merge 2 Images into a Single Image

26. Convert original image to image appears mirrored

27. Get Site Page Ranks

28. Give spelling suggestion for English words using yahoo API

29. Conver the Text to MP3 format file

30. Create thermo graph

31. Working with yahoo travel api

Page 272 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

32. Get the searching result from Wikipedia

33. Working with yahoo query API

Get the Gmail, Yahoo, Hotmail, AOL address book contacts


<?php
/**
* AddressBook
*
* This class contains functions to handle the gmail,yahoo,hotmail,aol address book.
*
* @package Lib_AddressBook
* @category Library
* @version 1.0
*/
// ------------------------------------------------------------------------
class Lib_AddressBook
{
/**
* Stores function type's name
*
* @var string $type
*/
private $type;
/**
* Flag for error
*
* @var boolean $error
*/
private $error;
/**
* Stores username
*
* @var string $username
*/
private $username;
/**
* Stores password
*
* @var string $password
*/
private $password;
/**
* Stores mail posted page name
*
* @var string $page
*/
private $page;
/**
* Stores mail subject
*
* @var string $mailSubject
*/
private $mailSubject;
/**
* Stores mail message
*
* @var string $mailMessage
*/
private $mailMessage;
/**
* Stores error numbers and description
*
* @var array $debug

Page 273 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

*/
public $debug = array();
/**
* Stores the output
*
* @var string $result
*/
public $result;

/**
* Constructs a Lib_AddressBook object with given parameters
* also it will invoke address book process
*
* @param string $type
* @param string $username
* @param string $password
* @return Lib_AddressBook
*/
public function Lib_AddressBook($type,$username,$password,$page,$mailSubject,$mailMessage)
{
$this->type = $type;
$this->username = $username;
$this->password = $password;
$this->page = $page;
$this->mailSubject = $mailSubject;
$this->mailMessage = $mailMessage;
if($this->isValidCall())
{
if(strtolower($type)=='gmail')
$this->gmailAddress();
if(strtolower($type)=='yahoo')
$this->yahooAddress();
if(strtolower($type)=='hotmail')
$this->hotmailAddress();
if(strtolower($type)=='aol')
$this->aolAddress();
}
}

/**
* Check whether the function call is valid or not
*
* @return bool
*/

private function isValidCall()


{
if(strtolower($this->type)!='gmail' && strtolower($this->type)!='yahoo' && strtolower($this-
>type)!='hotmail' && strtolower($this->type)!='aol')
{
echo '<b>Component Error!<b> Invalid argument <i>type</i> - gmail or yahoo or hotmail or
aol';
exit();
}
else if(empty($this->username))
{
echo '<b>Component Error!<b> Invalid argument <i>username</i> - username expected';
exit();
}
else if(empty($this->password))
{
echo '<b>Component Error!<b> Invalid argument <i>password</i> - password expected';
exit();
}
else if(empty($this->page))
{

Page 274 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

echo '<b>Component Error!<b> Invalid argument <i>page</i> - page name expected';


exit();
}
else if(empty($this->mailSubject))
{
echo '<b>Component Error!<b> Invalid argument <i>mailSubject</i> - mail subject expected';
exit();
}
else if(empty($this->mailMessage))
{
echo '<b>Component Error!<b> Invalid argument <i>mailMessage</i> - mail message
expected';
exit();
}
return true;
}

/**
* This function is use to find out the address book of gmail and send invitation mail to all members.
*
* @return array $result
*/

private function gmailAddress()


{

$sAction = $this->fnGet("action");
$result="";
if ($sAction == 'sendemails')
{
// Send the Email Addresses
$num = $this->fnGet("i");

$sEmailAddress = $this->fnGet("fromname");
for ($i=0; $i < $num; $i++)
{
$sName = $this->fnGet("name" . $i);
$sEmail = $this->fnGet("email" . $i);
$sCheck = $this->fnGet("check" . $i);
if ($sCheck == "on")
{
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
// Additional headers
$headers .= 'To: ' . $sName . ' <' . $sEmail . '>' . "\r\n";
$headers .= 'From: ' . $this->username . ' <' . $this->username . '>'
. "\r\n";

$sSubject=$this->mailSubject;
$sMessage=$this->mailMessage;
// Mail it
$bMailReturn = mail($sEmail, $sSubject, $sMessage, $headers);
if ($bMailReturn == true)
$result='Message sent to ' . $sEmail . '<br>';
}
}
$this->result=$result;
return true;
}
else
{
$varURL = "http://www.AddressBookImport.com/trial/";
$params = "service=Gmail&emailaddress=".$this->username."&password=".$this->password;
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_URL,$varURL);

Page 275 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
$content = curl_exec ($ch);

if (strpos($content, "~Invalid Login~") !== false)


$result.='<br><br><div align=center>... INVALID LOGIN ...</div>';

else
{
$result.='
<form method="post" action="'.$this->page.'">
<div align=center><br><br>Select the Contacts you want to send invite
to:<br/></div>
<table border=0 cellspacing=0 cellpadding=3 width="40%" align=center>';
$content = str_replace('<!-- -->', '', $content);

$sList = explode("\n", $content);


for ($i=0; $i < count($sList)-1; $i++)
{
$sList2 = explode(",", $sList[$i]);
$result.='<tr><td width="10" align=center><input type="checkbox"
id="check' . $i . '" name="check' . $i . '" checked></td><td><input type="text" size="30" name="name' . $i . '" value="'
. $sList2[0] . '"></td><td><input type="text" size="30" name="email' . $i . '" value="' . $sList2[1] . '"></td></tr>';
}

if (count($sList)>0)
{
$result.='
</table>
<br /><br />
<div align=center><input type="submit" value="Send
Invite"></div>
<input type="hidden" name="action" value="sendemails">
<input type="hidden" name="i" value="' . $i . '">
<input type="hidden" name="fromname" value="' . $this-
>fnGet("emailaddress") . '">
</form>
';
}
else
$result.='</table><br><br><div align=center>... NO MAIL IDS
...</div></form>';
}
$this->result=$result;
return true;
}

/**
* This function is use to find out the address book of yahoo and send invitation mail to all members.
*
* @return array $result
*/

private function yahooAddress()


{

$sAction = $this->fnGet("action");
$result="";
if ($sAction == 'sendemails')
{
$num = $this->fnGet("i");

Page 276 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

$sEmailAddress = $this->fnGet("fromname");
for ($i=0; $i < $num; $i++)
{
$sName = $this->fnGet("name" . $i);
$sEmail = $this->fnGet("email" . $i);
$sCheck = $this->fnGet("check" . $i);
if ($sCheck == "on")
{
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

// Additional headers
$headers .= 'To: ' . $sName . ' <' . $sEmail . '>' . "\r\n";
$headers .= 'From: ' . $this->username . ' <' . $this->username . '>'
. "\r\n";

$sSubject=$this->mailSubject;
$sMessage=$this->mailMessage;

// Mail it
$bMailReturn = mail($sEmail, $sSubject, $sMessage, $headers);
if ($bMailReturn == true)
$result='Message sent to ' . $sEmail . '<br>';
}
}
$this->result=$result;
return true;
}
else
{
$varURL = "http://www.AddressBookImport.com/trial/";

$params = "service=Yahoo&emailaddress=" . $this->username . "&password=" . $this-


>password;

$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_URL,$varURL);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
$content = curl_exec ($ch);

if (strpos($content, "~Invalid Login~") !== false)


$result.='<br><br><div align=center>... INVALID LOGIN ...</div>';

else
{
$result.='
<form method="post" action="'.$this->page.'">
<div align=center><br><br>Select the Contacts you want to send invite
to:<br/></div>
<table border=0 cellspacing=0 cellpadding=3 width="40%" align=center>';
$content = str_replace('<!-- -->', '', $content);

$sList = explode("\n", $content);


for ($i=0; $i < count($sList)-1; $i++)
{
$sList2 = explode(",", $sList[$i]);
$result.='<tr><td width="10" align=center><input type="checkbox"
id="check' . $i . '" name="check' . $i . '" checked></td><td><input type="text" size="30" name="name' . $i . '" value="'
. $sList2[0] . '"></td><td><input type="text" size="30" name="email' . $i . '" value="' . $sList2[4] . '"></td></tr>';
}

Page 277 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

if (count($sList)>0)
{
$result.='
</table>
<br /><br />
<div align=center><input type="submit" value="Send
Invite"></div>
<input type="hidden" name="action" value="sendemails">
<input type="hidden" name="i" value="' . $i . '">
<input type="hidden" name="fromname" value="' . $this-
>fnGet("emailaddress") . '">
</form>
';
}
else
$result.='</table><br><br><div align=center>... NO MAIL IDS
...</div></form>';
}
$this->result=$result;
return true;
}

/**
* This function is use to find out the address book of hotmail and send invitation mail to all members.
*
* @return array $result
*/

private function hotmailAddress()


{

$sAction = $this->fnGet("action");
$result="";
if ($sAction == 'sendemails')
{
$num = $this->fnGet("i");

$sEmailAddress = $this->fnGet("fromname");
for ($i=0; $i < $num; $i++)
{
$sName = $this->fnGet("name" . $i);
$sEmail = $this->fnGet("email" . $i);
$sCheck = $this->fnGet("check" . $i);
if ($sCheck == "on")
{
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

// Additional headers
$headers .= 'To: ' . $sName . ' <' . $sEmail . '>' . "\r\n";
$headers .= 'From: ' . $this->username . ' <' . $this->username . '>'
. "\r\n";

$sSubject=$this->mailSubject;
$sMessage=$this->mailMessage;

// Mail it
$bMailReturn = mail($sEmail, $sSubject, $sMessage, $headers);
if ($bMailReturn == true)
$result='Message sent to ' . $sEmail . '<br>';
}

Page 278 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

}
$this->result=$result;
return true;
}
else
{
$varURL = "http://www.AddressBookImport.com/trial/";

$params = "service=Hotmail&emailaddress=".$this->username."&password=".$this-
>password;

$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_URL,$varURL);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
$content = curl_exec ($ch);

if (strpos($content, "~Invalid Login~") !== false)


$result.='<br><br><div align=center>... INVALID LOGIN ...</div>';

else
{
$result.='
<form method="post" action="'.$this->page.'">
<div align=center><br><br>Select the Contacts you want to send invite
to:<br/></div>
<table border=0 cellspacing=0 cellpadding=3 width="40%" align=center>';
$content = str_replace('<!-- -->', '', $content);

$sList = explode("\n", $content);


for ($i=1; $i < count($sList)-1; $i++)
{
$sList2 = explode(",", $sList[$i]);
$splitString = explode('"',$sList2[1]);
$user_name_hotmail = $splitString[1];

$splitStringmail = explode('"',$sList2[46]);
$user_mail_hotmail = $splitStringmail[1];
$sList2 = explode(",", $sList[$i]);
$result.='<tr><td width="10" align=center><input type="checkbox"
id="check' . $i . '" name="check' . $i . '" checked></td><td><input type="text" size="30" name="name' . $i . '" value="'
. $user_name_hotmail . '"></td><td><input type="text" size="30" name="email' . $i . '" value="' . $user_mail_hotmail .
'"></td></tr>';
}
if (count($sList)>0)
{
$result.='
</table>
<br /><br />
<div align=center><input type="submit" value="Send
Invite"></div>
<input type="hidden" name="action" value="sendemails">
<input type="hidden" name="i" value="' . $i . '">
<input type="hidden" name="fromname" value="' . $this-
>fnGet("emailaddress") . '">
</form>
';
}
else
$result.='</table><br><br><div align=center>... NO MAIL IDS
...</div></form>';
}
$this->result=$result;
return true;
}

Page 279 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

/**
* This function is use to validate the subject.
*
* @return array $array
*/

private function parseContent($pattern, $subject)


{
$array = array();
preg_match_all( $pattern, $subject, $array );
return $array;
}

/**
* This function is use to delete the file.
*
* @return array $fileName
*/

private function rmFile( $fileName )


{
@unlink( $fileName );
}

/**
* This function is use to set the username.
*
* @return array $username
*/

private function setUsername( $username )


{
$this->_username = $username;
}

/**
* This function is use set the password.
*
* @return array $password
*/

private function setPassword( $password )


{
$this->_password = $password;
}

/**
* This function is use to initialize the variable.
*
* @return array _username
*/

private function getUsername()


{
return $this->_username;
}

/**
* This function is use to initialize the variable.
*
* @return array _password
*/

Page 280 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

private function getPassword()


{
return $this->_password;
}

/**
* This function is use to collect all the contact list of aol.
*
* @return array $result
*/

private function getContactList($username, $password)


{

$this->setUsername( $username );
$this->setPassword( $password );

$cookieFile = CPATH.$this->getUsername().'_aol_cookiejar.txt';
//incase this user has a cookies file in our cookies directory then lets remove
// it before starting the whole process or otherwise it won't work!!
if( file_exists( CPATH.$this->getUsername().'_aol_cookiejar.txt' ) )
{
$this->rmFile( CPATH.$this->getUsername().'_aol_cookiejar.txt' );
}
$ch = curl_init();
// try to login using the access that has been granted from the user ...
curl_setopt( $ch, CURLOPT_URL,
'http://my.screenname.aol.com/_cqr/login/login.psp?sitedomain=sns.webmail.aol.com&authLev=2&siteState=ver%3A2%
7Cac%3AWS%7Cat%3ASNS%7Cld%3Awebmail.aol.com%7Cuv%3AAOL%7Clc%3Aen-
us&lang=en&locale=us&seamless=novl' );
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1)
Gecko/20061204 Firefox/2.0.0.1');
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookieFile);
curl_setopt($ch, CURLOPT_COOKIEFILE,$cookieFile);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$return = curl_exec( $ch );

$data = $this->parseContent( '/<form name="AOLLoginForm"(.*?)<\/form>/s', $return );


$hidden = explode( '<input type="hidden"', $data[1][0] );
unset( $hidden[0] ); //remove the action since we don't really need it here
curl_setopt($ch, CURLOPT_URL, 'https://my.screenname.aol.com/_cqr/login/login.psp');
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,false);
$uname = 'loginId='.urlencode( $this->getUsername() );
$upass = 'password='.urlencode( $this->getPassword() );
$postFields = '';
foreach( $hidden as $field )
{
$field = trim( $field );
$tmp = explode( ' ', $field );
$removal = array( 'name=', 'value=', '"', '>', '</div' );
$tmp[0] = str_replace( $removal, '', $tmp[0] );
$tmp[1] = str_replace( $removal, '', $tmp[1] );
$postFields .= trim($tmp[0].'='.$tmp[1]).'&';
unset( $tmp );
}
$postFields .= $uname.'&'.$upass;
curl_setopt($ch, CURLOPT_POST, 2);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
$return = curl_exec( $ch );
$logIn = $this->parseContent( '/LoginSuccess.aspx(.*?)\'/s', $return );
$loginParts = explode( '&', $logIn[1][0] );

Page 281 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

$targetSuccessUrl = '';
foreach( $loginParts as $part )
{
$tmp = explode( '=', trim( $part ) );
if( $tmp[0] == 'siteState' )
{
$tmp[1] = urlencode( $tmp[1] );
}
$targetSuccessUrl .= $tmp[0].'='.$tmp[1].'&';
}
$targetSuccessUrl = substr_replace( $targetSuccessUrl , '', -1 );
$loginSuccessUrl = 'http://webmail.aol.com/_cqr/LoginSuccess.aspx'.$targetSuccessUrl;
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_URL, $loginSuccessUrl);
curl_setopt($ch, CURLOPT_REFERER, $loginSuccessUrl );
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookieFile);
curl_setopt($ch, CURLOPT_COOKIEFILE,$cookieFile);
$successPath = curl_exec( $ch );
$tmpSuccessPath = $this->parseContent( '/ClickHereMessage(.*?)Try Again/s', $successPath );
$gSuccessPath = $this->parseContent( '/webmail.aol.com(.*?)target/s', $tmpSuccessPath[1][0]);
$path = 'http://webmail.aol.com';
$gSuccessfull = trim( $gSuccessPath[1][0] );
$path .= str_replace( '"', '', $gSuccessfull );
curl_setopt( $ch, CURLOPT_URL, $path );
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 0 );

// by here we have successfully logged in


$weAreIn = curl_exec( $ch );
// from this point we are trying to go to the contacts page
$homePage = $this->parseContent( '/padding(.*?)true/s', $weAreIn );
$homePageLink = ''.$homePage[0][0];
$landingPageUrl = $this->parseContent( '/http(.*?)true/s', $homePageLink );

// now go to the landing page


$landingPageSubUrl = $this->parseContent( '/gSuccessPath(.*?)var/s', $landingPageUrl[0][0] );
$landingPageSubUrl = str_replace( array( '=', ' ', '"', ';' ), '', $landingPageSubUrl[1][0] );
$landingPageSubUrl = str_replace( 'Suite.aspx', '', $landingPageSubUrl );
curl_setopt( $ch, CURLOPT_URL, 'http://webmail.aol.com'.trim( $landingPageSubUrl
).'Lite/ContactList.aspx?folder=New%20Mail&showUserFolders=False' );
$contactsPage = curl_exec( $ch );
//we need the value of the "user" element in order to proceed
$firstUserPattern = $this->parseContent( '/ProcessCommand(.*?)toolbarType/s', $contactsPage );
$secondUserPattern = $this->parseContent( '/\.com(.*?)class/s', $firstUserPattern[1][0] );
$userArray = explode( ',', $secondUserPattern[1][0] );
$user = str_replace( array( '\'', ')', ';', '"' ), '', $userArray[1] );

// now we need to get all the pages that contains the contacts
// am not navigating through the whole pages, but rather i am using the print
// functionality that AOL is providing for their users in order to get the whole
// bunch of contacts in one single step.
curl_setopt( $ch, CURLOPT_URL, 'http://webmail.aol.com/'.trim( $landingPageSubUrl ).'Lite/addresslist-
print.aspx?command=all&sort=FirstLastNick&sortDir=Ascending&nameFormat=FirstLastNick&user='.$user );
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
$contactsRecords = curl_exec( $ch );

// ok, now we have the contacts bunch and we need to filter them ...
$firstPhaseFilter = $this->parseContent( '/fullName(.*?)contactSeparator/s',$contactsRecords );
$contactList = array();
foreach( $firstPhaseFilter[0] as $value )
{
$value = ''.$value; //don't ask me why i did that, it just didn't work except like this!!!
// filter contact's full name

Page 282 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

$contactName = $this->parseContent( '/fullName">(.*?)<\/span/s', $value );


// filter contact's email
$contactEmail = $this->parseContent( '/<span>Email 1:<\/span> <span>(.*?)<\/span>/s', $value);
$result['name'][] = strip_tags($contactName[1][0]);
$result['email'][] = $contactEmail[1][0];

}
// Clean up and finalize everything ...
$this->rmFile( $cookieFile );

$this->result=$result;
return true;

/**
* This function is use to find out the address book of aol and send invitation mail to all members.
*
* @return array $result
*/

private function aolAddress()


{

$sAction = $this->fnGet("action");
$result="";
if ($sAction == 'sendemails')
{
$num = $this->fnGet("i");

$sEmailAddress = $this->fnGet("fromname");
for ($i=0; $i < $num; $i++)
{
$sName = $this->fnGet("name" . $i);
$sEmail = $this->fnGet("email" . $i);
$sCheck = $this->fnGet("check" . $i);
if ($sCheck == "on")
{
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

// Additional headers
$headers .= 'To: ' . $sName . ' <' . $sEmail . '>' . "\r\n";
$headers .= 'From: ' . $this->username . ' <' . $this->username . '>'
. "\r\n";

$sSubject=$this->mailSubject;
$sMessage=$this->mailMessage;

// Mail it
$bMailReturn = mail($sEmail, $sSubject, $sMessage, $headers);
if ($bMailReturn == true)
$result.='Message sent to ' . $sEmail . '<br>';
}
}
$this->result=$result;
return true;
}
else
{

$content = $this->getContactList($this->username,$this->password);

if(!is_array($content))
{

Page 283 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

$result.='<p align="center"><font color="#FF0000">No contacts


found</font></p>';
}

else
{
$result.='
<form method="post" action="'.$this->page.'">
<div align=center><br><br>Select the Contacts you want to send invite
to:<br/></div>
<table border=0 cellspacing=0 cellpadding=3 width="40%" align=center>';
$content = str_replace('<!-- -->', '', $content);
$total = sizeof($content['name']);
for ($i=0;$i< $total;$i++)
{

$result.='<tr><td width="10" align=center><input type="checkbox" id="check' . $i . '"


name="check' . $i . '" checked></td><td><input type="text" size="30" name="name' . $i . '" value="'
.$content['name'][$i]. '"></td><td><input type="text" size="30" name="email' . $i . '" value="' .$content['email'][$i].
'"></td></tr>';
}
if ($total>0)
{
$result.='
</table>
<br /><br />
<div align=center><input type="submit" value="Send
Invite"></div>
<input type="hidden" name="action" value="sendemails">
<input type="hidden" name="i" value="' . $i . '">
<input type="hidden" name="fromname" value="' . $this-
>fnGet("emailaddress") . '">
</form>
';
}
else
$result.='</table><br><br><div align=center>... NO MAIL IDS
...</div></form>';
}
$this->result=$result;
return true;
}

/**
* This function is use get server variables.
*
* @return array fnGet
*/

private function fnGet($varQuery, $varType = "AUTO")


{
if ($varType == "AUTO")
{
if (isset($_GET["$varQuery"]))
{
return($_GET["$varQuery"]);
}
elseif (isset($_POST["$varQuery"]))
{
return($_POST["$varQuery"]);
}
}
elseif ($varType == "GET")

Page 284 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

{
if (isset($_GET["$varQuery"]))
{
return($_GET["$varQuery"]);
}
}
elseif ($varType == "POST")
{
if (isset($_POST["$varQuery"]))
{
return($_POST["$varQuery"]);
}
}
return("");
}
}
?>
Get site ranking information from the Alexa site
<?php
/**
* AlexaPageRank
*
* This class contains functions get site ranking information from the Alexa site.
*
* @package Lib_AlexaPageRank
* @category Library
* @version 1.0
*/
// ------------------------------------------------------------------------
class Lib_AlexaPageRank
{
/**
* Stores function type's name
*
* @var string $type
*/
private $type;
/**
* Flag for error
*
* @var boolean $error
*/
private $error;
/**
* Stores error numbers and description
*
* @var array $debug
*/
public $debug = array();
/**
* Stores the output
*
* @var string $result
*/
public $result;
/**
* site url
*
* @var string $url
*/
private $url;
/**
* curl timeout
*
* @var integer CURL_TIMEOUT
*/

Page 285 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

const CURL_TIMEOUT = 20;


/**
* alexa site url
*
* @var string ALEXA_SITE_INFO_URL
*/
const ALEXA_SITE_INFO_URL = 'http://www.alexa.com/xml/dad?url=';

/**
* Constructs a Lib_AlexaPageRank object with given parameters
* also it will invoke page rank process
*
* @param string $type
* @param string $url
* @return Lib_AlexaPageRank
*/

public function Lib_AlexaPageRank($type,$url)


{
$this->type = $type;
$this->url=$url;

if($this->isValidCall())
{
if(strtolower($type)=='alexa_rank')
$this->getAlexaRank();
}
}

/**
* Check whether the function call is valid or not
*
* @return bool
*/

private function isValidCall()


{
if(strtolower($this->type)!='alexa_rank')
{
echo '<b>Component Error!<b> Invalid argument <i>type</i> - alexa_rank expected';
exit();
}
else if(empty($this->url))
{
echo '<b>Component Error!<b> Invalid argument <i>url</i> - url expected';
exit();
}
else if(is_numeric($this->url))
{
echo '<b>Component Error!<b> Invalid argument <i>url</i> - url must be string';
exit();
}
return true;
}

/**
* get page rank for given site
*
* @return string
*/

private function getAlexaRank()


{
$url=$this->url;
if(!eregi("^(https?://)?(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-]+@)?(([0-
9]{1,3}\.){3}[0-9]{1,3}|([0-9a-z_!~*'()-]+\.)*([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\.[a-z]{2,6})(:[0-9]{1,4})?((/?)|(/[0-

Page 286 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

9a-z_!~*'().;?:@&=+$,%#-]+)+/?)$",$url))
{
$this->error = 1;
$this->debug['errinfo'] = array(1001=>'Not a valid URL format');
return false;
}
$xml_str = $this->get(self::ALEXA_SITE_INFO_URL.$url);

if (function_exists('simplexml_load_string'))
{
$xml = simplexml_load_string($xml_str);
$alexa_ranking= $xml->SD->POPULARITY['TEXT'] ? (int) $xml->SD->POPULARITY['TEXT'] : 0;
if ($alexa_ranking)
$this->result= $alexa_ranking;
else
$this->result= 'No result';
return true;
}
preg_match('#<POPULARITY URL=".+?" TEXT="(\d+)"/>#s', $xml_str, $matches);
$alexa_ranking= isset($matches[1]) ? (int) $matches[1] : 0;
if ($alexa_ranking)
$this->result= $alexa_ranking;
else
$this->result= 'No result';
return true;
}

/**
* call curl function
*
* @return string
*/

private function get($url)


{
if (!function_exists('curl_init'))
{
$response = '';
$url_data = parse_url($url);

$socket = fsockopen($url_data['host'], 80, $errno, $errstr, self::CURL_TIMEOUT);


$query = "GET ".$url_data['path'].(isset($url_data['query']) ? '?'.$url_data['query'] : '')." HTTP/1.1\r\n";
$query .= "Host: ".$url_data['host']."\r\n";
$query .= "Connection: Close\r\n\r\n";

fwrite($socket, $query);

while (!feof($socket))
{
$response .= fread($socket, 1024);
}

fclose($socket);
list($headers, $body) = explode("\r\n\r\n", $response, 2);
return $body;
}
$hCurl = curl_init($url);
curl_setopt($hCurl, CURLOPT_TIMEOUT, self::CURL_TIMEOUT);
curl_setopt($hCurl, CURLOPT_RETURNTRANSFER, TRUE);
$response = curl_exec($hCurl);
return $response;
}

}
?>
Convert the array to diagram

Page 287 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

<?php
/**
* ArrayDiagram
*
* This class contains functions convert array to diagram.
*
* @package Lib_ArrayDiagram
* @category Library
* @version 1.0
*/
// ------------------------------------------------------------------------
class Lib_ArrayDiagram
{
/**
* Stores function type's name
*
* @var string $type
*/
private $type;
/**
* Stores the output
*
* @var string $result
*/
public $result;
/**
* Stores error numbers and description
*
* @var array $debug
*/
public $debug = array();
/**
* input data array
*
* @var array $data
*/
private $data = array();
/**
* image background color
*
* @var array $bgcolor
*/
private $bgcolor = array(255, 255, 255);
/**
* image border color
*
* @var array $bordercolor
*/
private $bordercolor = array(100, 100, 100);
/**
* image border width
*
* @var integer $borderwidth
*/
private $borderwidth = 0;
/**
* rectangle border color
*
* @var array $rectBorderColor
*/
private $rectBorderColor = array(170, 170, 170);
/**
* rectangle background color
*
* @var array $rectBgColor
*/

Page 288 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

private $rectBgColor = array(194, 194, 239);


/**
* font color
*
* @var array $fontcolor
*/
private $fontcolor = array(0, 0, 0);
/**
* font size
*
* @var integer $font
*/
private $font = 2;
/**
* font width
*
* @var integer $fontwidth
*/
private $fontwidth = 0;
/**
* font height
*
* @var integer $fontheight
*/
private $fontheight = 0;
/**
* padding
*
* @var integer $padding
*/
private $padding = 10;
/**
* in padding
*
* @var integer $inpadding
*/
private $inpadding = 5;
/**
* space padding
*
* @var integer $spacepadding
*/
private $spacepadding = 5;
/**
* 0 (opaque) to 127 (transparent)
*
* @var integer $alpha
*/
private $alpha = 0;
/**
* left offset
*
* @var integer $leftoffset
*/
private $leftoffset = 0;
/**
* Constructs a Lib_ArrayDiagram object with given parameters
* also it will invoke array diagram process
*
* @param string $type
* @param string $data
* @return Lib_ArrayDiagram
*/

public function Lib_ArrayDiagram($type,$data=array())


{

Page 289 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

$this->type = $type;
$this->data = $data;

if($this->isValidCall())
{
if(strtolower($type)=='diagram')
$this->draw();

}
}

/**
* Check whether the function call is valid or not
*
* @return bool
*/
private function isValidCall()
{
if(strtolower($this->type)!='diagram')
{
echo '<b>Component Error!<b> Invalid argument <i>type</i> - diagram expected';
exit();
}
else if(!is_array($this->data))
{
echo '<b>Component Error!<b> Invalid argument data type <i>data</i> - array expected';
exit();
}
else if(empty($this->data))
{
echo '<b>Component Error!<b> Invalid argument <i>data</i> - fill all the fields';
exit();
}
return true;
}

/**
* draw the image
*
* @return image
*/
private function draw($file = "")
{
if (count($this->data) == 0)
{
$this->error = 1;
$this->debug['errinfo'] = array(1001=>'Array element not found');
return false;
}
$arrk = array_keys($this->data);
$this->fontwidth = imagefontwidth($this->font);
$this->fontheight = imagefontheight($this->font);
$maxw = $this->getMaxWidth($this->data);
$w = $maxw + (2 * $this->padding) + 1;
$h = $this->getMaxDeepness($this->data);
$h = (2 * $this->padding) +
(($this->fontheight + (2 * $this->inpadding)) * $h) +
((2 * $this->spacepadding) * ($h - 1)) + 1;
$this->im = imagecreatetruecolor($w, $h);

// background color
$this->allocateColor("im_bgcolor", $this->bgcolor, false);
imagefilledrectangle($this->im, 0, 0, $w, $h, $this->im_bgcolor);
if ($this->borderwidth > 0)
{
$this->allocateColor("imBorderColor", $this->bordercolor);

Page 290 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

for ($i = 0; $i < $this->borderwidth; $i++)


{
imagerectangle($this->im, $i, $i, $w - 1 - $i, $h - 1 - $i, $this->imBorderColor);
}
}

// allocate colors
$this->allocateColor("imRectBgColor", $this->rectBgColor);
$this->allocateColor("imRectBorderColor", $this->rectBorderColor);
$this->allocateColor("im_fontcolor", $this->fontcolor);

// draw all data


$this->drawData($this->data[$arrk[0]], $this->padding);

// draw 1st square


$rw = ($this->fontwidth * strlen($arrk[0])) + (2 * $this->inpadding);
$x1 = round(($w - $rw) / 2);
$y1 = $this->padding;
$x2 = $x1 + $rw;
$y2 = $y1 + (2 * $this->inpadding) + $this->fontheight;
$this->rectangle($x1, $y1, $x2, $y2, $this->imRectBorderColor, $this->imRectBgColor);
imagestring($this->im, $this->font, $x1 + $this->inpadding, $y1 + $this->inpadding, $arrk[0], $this->im_fontcolor);
$x1 = $x1 + round(($x2 - $x1) / 2);
imageline($this->im, $x1, $y2 + 1, $x1, $y2 + $this->spacepadding - 1, $this->imRectBorderColor);

// output
if (strlen($file) > 0 && is_dir(dirname($file)))
{
imagepng($this->im, $file);
}
else
{
header("Content-Type: image/png");
imagepng($this->im);
}
}
/**
* draw the data
*
*/

private function drawData(&$data, $offset = 0, $level = 1, $width = 0)


{
$top = $this->padding + ($level * (($this->spacepadding * 2) + $this->fontheight + (2 * $this->inpadding)));
$startx = $endx = 0;

foreach ($data as $k => $v)


{

if (is_array($v))
{
$width = $this->getMaxWidth($v);
$rw = ($this->fontwidth * strlen($k)) + (2 * $this->inpadding);
if ($width < $rw)
{
$width = $rw;
}
$x1 = $offset + round(($width - $rw) / 2);
$y1 = $top;
$x2 = $x1 + $rw;
$y2 = $y1 + (2 * $this->inpadding) + $this->fontheight;
//echo "($x1,$y1)-($x2,$y2)<br>\n";
$this->rectangle($x1, $y1, $x2, $y2, $this->imRectBorderColor, $this->imRectBgColor);
imagestring($this->im, $this->font, $x1 + $this->inpadding, $y1 + $this->inpadding, $k, $this->im_fontcolor);

// upper line

Page 291 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

$x1 = $x1 + round(($x2 - $x1) / 2);


imageline($this->im, $x1, $y1 - 1, $x1, $y1 - $this->spacepadding + 1, $this->imRectBorderColor);
// lower line
imageline($this->im, $x1, $y2 + 1, $x1, $y2 + $this->spacepadding - 1, $this->imRectBorderColor);
$this->drawData($v, $offset, $level + 1, $width);
$offset += $width + $this->spacepadding + 1;
}
else
{
$rw = ($this->fontwidth * strlen($v)) + (2 * $this->inpadding);
if (count($data) == 1)
{
$offset += round(($width - $rw) / 2);
}
$x1 = $offset;
$y1 = $top;
$x2 = $x1 + $rw;
$y2 = $y1 + (2 * $this->inpadding) + $this->fontheight;

$this->rectangle($x1, $y1, $x2, $y2, $this->imRectBorderColor, $this->imRectBgColor);


imagestring($this->im, $this->font, $x1 + $this->inpadding, $y1 + $this->inpadding, $v, $this->im_fontcolor);
// upper line
$x1 = $x1 + round(($x2 - $x1) / 2);
imageline($this->im, $x1, $y1 - 1, $x1, $y1 - $this->spacepadding + 1, $this->imRectBorderColor);
$offset += $rw + $this->spacepadding + 1;
}
if ($startx == 0)
{
$startx = $x1;
}
$endx = $x1;
}

$top -= $this->spacepadding;
imageline($this->im, $startx, $top, $endx, $top, $this->imRectBorderColor);
}

/**
* get maximum width
*
*/

private function getMaxWidth(&$arr)


{
$c = 0;
foreach ($arr as $k => $v)
{
if ($c > 0)
{
$c += $this->spacepadding + 1;
}
if (is_array($v))
{
$n = $this->getMaxWidth($v);
if ($n > (2 * $this->inpadding) + (imagefontwidth($this->font) * strlen($k)))
{
$c += $n;
}
else
{
$c += (2 * $this->inpadding) + (imagefontwidth($this->font) * strlen($k));
}
}
else
{
$c += (2 * $this->inpadding) + (imagefontwidth($this->font) * strlen($v));

Page 292 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

}
}
return $c;
}

/**
* get maximum deepness
*
*/

private function getMaxDeepness(&$arr)


{
$p = 0;
foreach ($arr as $k => $v)
{
if (is_array($v))
{
$r = $this->getMaxDeepness($v);
if ($r > $p)
{
$p = $r;
}
}
}
return ($p + 1);
}

/**
* draw the rectangle
*
*/

private function rectangle($x1, $y1, $x2, $y2, $color, $bgcolor)


{
imagerectangle($this->im, $x1, $y1, $x2, $y2, $color);
imagefilledrectangle($this->im, $x1 + 1, $y1 + 1, $x2 - 1, $y2 - 1, $bgcolor);
}

/**
* allocate color
*
*/

private function allocateColor($var, $color, $alpha = true)


{
$alpha = ($alpha ? $this->alpha : 0);
$this->$var = imagecolorallocatealpha($this->im, $color[0], $color[1], $color[2], $alpha);
}

}
?>
Convert image to ascii code art
<?php
/**
* AsciiArt
*
* This class contains functions convert image to ascii code art.
*
* @package Lib_AsciiArt
* @category Library
* @version 1.0
*/
// ------------------------------------------------------------------------
class Lib_AsciiArt
{
/**

Page 293 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

* Stores function type's name


*
* @var string $type
*/
private $type;
/**
* Stores the output
*
* @var string $result
*/
public $result;
/**
* Input image path
*
* @var string $imagePath
*/
private $imagePath;
/**
* Stores error numbers and description
*
* @var array $debug
*/
public $debug = array();
/**
* replace chars
*
* @var array $_replaceCharacters
*/
private $_replaceCharacters = array (
1 => "W",
2 => "@",
3 => "#",
4 => "*",
5 => "+",
6 => ":",
7 => ".",
8 => ",",
9 => "&nbsp;"
);
/**
* image types
*
* @var array $imageTypes
*/
private $imageTypes = array (
1 => "gif",
2 => "jpeg",
3 => "png",
4 => "jpg"
);
/**
* image resource
*
* @var integer $image
*/
private $image = 0;
/**
* image height
*
* @var integer $imageHeight
*/
private $imageHeight = 0;
/**
* image width
*
* @var integer $imageWidth

Page 294 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

*/
private $imageWidth = 0;
/**
* Container for the rendered HTML/ASCII image
*
* @var string $imageHTML
*/
private $imageHTML = '';
/**
* CSS for the HTML Image Output
*
* @var string $imageCSS
*/
private $imageCSS = '
color : #000000;
background-color : #FFFFFF;
font-size : 8px;
font-family : "Courier New", Courier, mono;
line-height : 5px;
letter-spacing : -1px;
';
/**
* the last font tag
*
* @var array $lastRGB
*/
private $lastRGB = array();
/**
* the font tag state
*
* @var bool $fontTagOpen
*/
private $fontTagOpen = false;
/**
* mode 1- black & white,2- Colorized,3- Colorized using fixed character
*
* @var integer $mode
*/
private $mode = false;
/**
* Constructs a Lib_AsciiArt object with given parameters
* also it will invoke ascii art process
*
* @param string $type
* @param string $imagePath
* @return Lib_AsciiArt
*/

public function Lib_AsciiArt($type,$imagePath,$mode=1)


{
$this->type = $type;
$this->imagePath = $imagePath;
$this->mode = $mode;

if($this->isValidCall())
{
if(strtolower($type)=='asciiart')
$this->asciiart();
}
}

/**
* Check whether the function call is valid or not
*
* @return bool
*/

Page 295 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

private function isValidCall()


{
if(strtolower($this->type)!='asciiart')
{
echo '<b>Component Error!<b> Invalid argument <i>type</i> - asciiart expected';
exit();
}
else if(empty($this->imagePath))
{
echo '<b>Component Error!<b> Invalid argument <i>imagePath</i> - image path expected';
exit();
}
return true;
}

/**
* set the rgb color
*
*/

function rgb2HEX($rgb)
{
return sprintf("%02X%02X%02X",$rgb["red"],$rgb["green"],$rgb["blue"]);
}

/**
* render the pixel
*
*/

function renderPixel($mode, $x, $y, $fixedChar)


{
$rgb = imagecolorsforindex($this->image, imagecolorat($this->image, $x, $y));

switch ($mode)
{
case 1:
$brightness = $rgb["red"] + $rgb["green"] + $rgb["blue"];

$replaceCharacterNo = round($brightness / 100) + 1;

$this->imageHTML .= $this->_replaceCharacters[$replaceCharacterNo];
break;
case 2:
$brightness = $rgb["red"] + $rgb["green"] + $rgb["blue"];

$replaceCharacterNo = round($brightness / 100) + 1;


if ($this->lastRGB == $rgb)
{
$this->imageHTML .= $this->_replaceCharacters[$replaceCharacterNo];
}
else
{

if ($this->fontTagOpen)
{
$this->imageHTML .= "</font>";
}

$this->imageHTML .= "<font color=\"#".$this->rgb2HEX($rgb)."\">".$this-


>_replaceCharacters[$replaceCharacterNo];
$this->fontTagOpen = true;
}
break;
case 3:
if ($this->lastRGB == $rgb)

Page 296 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

{
$this->imageHTML .= $fixedChar;
}
else
{

if ($this->fontTagOpen)
{
$this->imageHTML .= "</font>";
}

$this->imageHTML .= "<font color=\"#".$this->rgb2HEX($rgb)."\">".$fixedChar;


$this->fontTagOpen = true;
}
break;
}
$this->lastRGB = $rgb;
}

/**
* set the image css
*
*/

function setImageCSS ($css)


{
$this->imageCSS = $css;
}

/**
* render html image
*
*/

function renderHTMLImage($mode = 1, $resolution = 2, $fixedChar = 'W', $flipH = false, $flipV = false)


{
$this->imageHTML = '';

if ($resolution < 1)
{
$resolution = 1;
}

if (!$flipH && !$flipV)


{
for ($y = 0; $y < $this->imageHeight; $y += $resolution)
{
for ($x = 0; $x < $this->imageWidth; $x += $resolution)
{
$this->renderPixel($mode, $x, $y, $fixedChar);
}
$this->imageHTML .= "<br>\n";
}
}
else if ($flipH && !$flipV)
{
for ($y = 0; $y < $this->imageHeight; $y += $resolution)
{
for ($x = $this->imageWidth; $x > 0; $x -= $resolution)
{
$this->renderPixel($mode, $x, $y, $fixedChar);
}
$this->imageHTML .= "<br>\n";
}
}
else if (!$flipH && $flipV)

Page 297 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

{
for ($y = $this->imageHeight; $y > 0; $y -= $resolution)
{
for ($x = 0; $x < $this->imageWidth; $x += $resolution)
{
$this->renderPixel($mode, $x, $y, $fixedChar);
}
$this->imageHTML .= "<br>\n";
}
}
else if ($flipH && $flipV)
{
for ($y = $this->imageHeight; $y > 0; $y -= $resolution)
{
for ($x = $this->imageWidth; $x > 0; $x -= $resolution)
{
$this->renderPixel($mode, $x, $y, $fixedChar);
}
$this->imageHTML .= "<br>\n";
}
}
if ($this->fontTagOpen) {
$this->imageHTML .= "</font>\n";
}
}

/**
* rendered ASCII HTML image and CSS
*
*/

function getHTMLImage()
{
return '<style type="text/css">'
.'.asciiimage{'
.$this->imageCSS
.'}</style>'
.'<span class="asciiimage">'
.$this->imageHTML
.'</span>';
}

/**
* Checks if an error has occured
*
*/

function isError()
{
return count($this->debug) > 0;
}

/**
* Returns the unformatted error messages as an array
*
*/

function getdebug()
{
return $this->debug;
}

/**
* Returns the error messages as HTML
*
*/

Page 298 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

function getHTMLdebug()
{
if (!$this->isError())
{
return '';
}
foreach($this->debug as $error)
{
$ret.= @htmlentities($error).'<br>';
}
return $ret;
}

/**
* find out the debug
*
*/

function setFile($filename)
{
if (!$imagesize = @getimagesize($filename))
{
$this->debug['errinfo'] = array(1001=>'Cannot open "'.$filename.'" for reading.');
return false;
}

list($width,$height,$type) = $imagesize;
switch ($type)
{
case 1:
case 2:
case 3:
$imagefunction = "imagecreatefrom".$this->imageTypes[$type];

if (!function_exists($imagefunction) || !$this->image = $imagefunction($filename)) {


$this->debug['errinfo'] = array(1002=>'Unable to create images from '.$this->imageTypes[$type]);
return false;
}
$this->imageHeight = $height;
$this->imageWidth = $width;

break;
default:
$this->debug['errinfo'] = array(1003=>'Cannot determine image type of "'.$filename.'".');
return false;
}

return true;
}

/**
* Returns the height of the original bitmap image in pixels
*
*/

function getImageHeight()
{
return $this->imageHeight;
}

/**
* Returns the width of the original bitmap image in pixels
*
*/

Page 299 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

function getImageWidth()
{
return $this->imageWidth;
}

/**
* Returns the height of the original bitmap image in pixels
*
* @return array $result
*/

function asciiart()
{
$image=$this->imagePath;
if(!$this->setFile($image))
{
echo $this->getHTMLdebug();
}
else
{
$flip_h = false;
$flip_v = false;
$color="#000000";
$font_size ='10';
$line_height=8;
$letter_spacing=0;
$mode=$this->mode;
$resolution=3;
$fixed_char="W";
// Set the CSS as desired
$this->setImageCSS('
color : '.$color.';
background-color: transparent;
font-size : '.$font_size.'px;
font-family : "Courier New", Courier, mono;
line-height : '.$line_height."px;
letter-spacing : ".$letter_spacing.'px; ');

// Convert the image


$this->renderHTMLImage($mode, $resolution, $fixed_char, $flip_h, $flip_v);

// Print converted image as HTML


$output.=$this->getHTMLImage();

$this->result=$output;
return true;
}

}
?>
Encode/Decode binary data with text characters
<?php
/**
* AsciiEncode
*
* This class contains functions Encode/Decode binary data with text characters
*
* @package Lib_AsciiEncode
* @category Library
* @version 1.0
*/
// ------------------------------------------------------------------------
class Lib_AsciiEncode
{

Page 300 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

/**
* Stores function type's name
*
* @var string $type
*/
private $type;
/**
* Flag for error
*
* @var boolean $error
*/
private $error;
/**
* Stores error numbers and description
*
* @var array $debug
*/
public $debug = array();
/**
* Stores the output
*
* @var string $result
*/
public $result;
/* text for convert
*
* @var string $value
*/
private $value;
/* method type
*
* @var string $method
*/
private $method;
/* variation type Basic/Adobe/BtoA
*
* @var integer $variation
*/
private $variation;
/**
* Algorithm variations.
*/
const BASIC = 0; // Default implementation
const ADOBE = 1; // Adobe version
const BTOA = 2; // BTOA version
/**
* Constructs a Lib_AsciiEncode object with given parameters
* also it will invoke ascii encode process
*
* @param string $type
* @param string $value
* @param string $method
* @param integer $variation
* @return Lib_AsciiEncode
*/

public function Lib_AsciiEncode($type,$value,$method='encode',$variation=0)


{
$this->type = $type;
$this->value = $value;
$this->method = $method;
$this->variation = $variation;

if($this->isValidCall())
{
if(strtolower($type)=='asciiencode')

Page 301 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

$this->getResult();
}

/**
* Check whether the function call is valid or not
*
* @return bool
*/

private function isValidCall()


{
if(strtolower($this->type)!='asciiencode')
{
echo '<b>Component Error!<b> Invalid argument <i>type</i> - asciiencode expected';
exit();
}
elseif(empty($this->value))
{
echo '<b>Component Error!<b> Invalid argument data type <i>value</i> - value expected';
exit();
}
elseif(empty($this->method))
{
echo '<b>Component Error!<b> Invalid argument data type <i>method</i> - method
expected';
exit();
}
elseif((strtolower($this->method)!='encode') && (strtolower($this->method)!='decode'))
{
echo '<b>Component Error!<b> Invalid argument data type <i>method</i> - method enocde
or decode expected';
exit();
}
elseif(!is_numeric($this->variation))
{
echo '<b>Component Error!<b> Invalid argument data type <i>variation</i> - variation must
be numeric';
exit();
}
elseif($this->variation>2||$this->variation<0)
{
echo '<b>Component Error!<b> Invalid argument data type <i>variation</i> - variation must
be 0 to 2.';
exit();
}
return true;
}
/**
* Encode to ASCII format.
*
* @return string.
*/

private function encode($value, $variation = self::BASIC, $split_pos = false)


{
switch ($variation)
{
case self::ADOBE:
$y_exception = false;
$z_exception = true;
break;
case self::BTOA:
$y_exception = true;
$z_exception = true;

Page 302 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

break;
case self::BASIC:
$y_exception = false;
$z_exception = false;
break;
}
// Returned value
$return = '';
// Get string tuples of 4 bytes
$tuples = str_split($value, 4);
// Foreach tuple
foreach ($tuples as $tuple)
{
// Convert tuple (string value) to binary (integer value)
$bin_tuple = 0;
$len = strlen($tuple);
for ($i = 0; $i < $len; $i++)
{
$bin_tuple |= (ord($tuple[$i]) << ((3 - $i) * 8));
}
// Get unsigned value as string
$bin_tuple = sprintf('%u', $bin_tuple);
// Zero-tuple is represented as "z"
if ($z_exception && $bin_tuple == 0)
{
$return .= 'z';
// Space-tuple is represented as "y"
} elseif ($y_exception && $bin_tuple == 0x20202020)
{
$return .= 'y';
// Tuple
}
else
{
// Create a tuple 85 (string value)
$i = 5;
$tuple85 = '';
while ($i--)
{
$c = bcmod($bin_tuple, '85');
$tuple85 = chr(bcadd($c, '33')).$tuple85;
$bin_tuple = bcdiv($bin_tuple, '85', 0);
}
$tuple85 = substr($tuple85, 0, $len + 1);
// Append to return value
$return .= $tuple85;
}
}
switch ($variation)
{
case self::BASIC:
self::split($return, $split_pos);
break;
case self::ADOBE:
$return = '<~'.$return.'~>';
self::split($return, $split_pos);
break;
case self::BTOA:
self::btoaCreatechecks($value, $size_dec, $size_hex, $check_xor, $check_sum,
$check_rot);
self::split($return, $split_pos);
$return = sprintf(
"xbtoa Begin\n%s\nxbtoa End N %s %s E %s S %s R
%s\n",
$return, $size_dec, $size_hex, $check_xor, $check_sum,
$check_rot

Page 303 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

);
break;
}
return $return;
}
/**
* Decode from ASCII.
*
* @return string
*/

private function decode($value, $variation = self::BASIC)


{
// Get BTOA checks
if ($variation == self::BTOA)
{
self::btoaGetChecks($value, $size_dec, $size_hex, $check_xor, $check_sum, $check_rot);
}
// Clean value
self::clean($value, $variation);

// Returned value
$return = '';
// Const values
$max_tuple = pow(2, 32);
$base85 = array();
$base85[0] = 1; // 85^0
$base85[1] = $base85[0] * 85; // 85^1
$base85[2] = $base85[1] * 85; // 85^2
$base85[3] = $base85[2] * 85; // 85^3
$base85[4] = $base85[3] * 85; // 85^4
// Get ASCIItuples
$value = str_split($value, 5);
// Foreach tuple 85 of 5 bytes
foreach ($value as $tuple85)
{
// If zero-tuple was found
if ($tuple85 === 'zzzzz')
{
$return .= str_repeat(chr(0), 4);
continue;
// If space-tupe was found
}
elseif ($tuple85 === 'yyyyy')
{
$return .= str_repeat(' ', 4);
continue;
}
// If the tuple has invalid chars
if (!preg_match('/^[\x21-\x75]{1,5}$/', $tuple85))
{
$this->error = 1;
$this->debug['errinfo'] = array(1005=>'Tuple has invalid characters ('.$tuple85.')');
return false;
}
// Convert tuple 85 (text) to binary tuple (number)
$bin_tuple = '0';
$len = strlen($tuple85);
// Append "u" to missing positions to avoid rounding-down effect
$tuple85 .= str_repeat('u', 5 - $len);
for ($i = 0; $i < 5; $i++)
{
$bin_char = strval(ord($tuple85[$i]) - 33);
$bin_tuple += bcmul($bin_char, $base85[4 - $i]);
}
// If binary value is greater than 2^32

Page 304 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

if ($bin_tuple > $max_tuple)


{
$this->error = 1;
$this->debug['errinfo'] = array(1004=>'Tuple is greater than '.$max_tuple);
return false;
}
$bin_tuple = bindec(sprintf('%032b', $bin_tuple));
// Create a tuple (string value)
$i = 4;
$tuple = '';
$len -= 1;
while ($len--)
{
$c = ($bin_tuple >> (--$i * 8)) & 0xFF;
$tuple .= chr($c);
}
// Append to return value
$return .= $tuple;
}
// Get BTOA checks
if ($variation == self::BTOA)
{
$v = self::btoaValidateChecks($return, $size_dec, $size_hex, $check_xor, $check_sum, $check_rot);
if (!$v)
{
$this->error = 1;
$this->debug['errinfo'] = array(1003=>'Generated text did not pass by validation of
BTOA checks');
return false;
}
}
return $return;
}
/**
* Split a string on a specific position.
*
* @return void
*/

private function split(&$value, $pos)


{
if (is_numeric($pos) && $pos > 0)
{
$value = chunk_split($value, $pos, "\n");
$value = rtrim($value);
}
}
/**
* Convert some characters of an encoded text.
*
* @return bool
*/

private function clean(&$value, $variation)


{
$value = trim($value);
switch ($variation)
{
case self::BASIC:
// Remove spaces
$tr = array(' ' => '',
"\r" => '',
"\n" => '',
"\t" => '',
"\0" => '',
"\f" => ''

Page 305 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

);
$value = strtr($value, $tr);
break;
case self::ADOBE:
if (substr($value, 0, 2) != '<~' || substr($value, -2, 2) != '~>')
{
$this->error = 1;
$this->debug['errinfo'] = array(1002=>'Value does not have Adobe delimiter');
return false;
}
// Remove <~ and ~>
$value = substr($value, 2, strlen($value) - 4);
// Remove spaces and convert "z" exception to a tuple
$tr = array(' ' => '',
"\r" => '',
"\n" => '',
"\t" => '',
"\0" => '',
"\f" => '',
'z' => 'zzzzz'
);
$value = strtr($value, $tr);
break;
case self::BTOA:
// Remove first line
$first = strpos($value, "\n");
$value = substr($value, $first + 1);
// Remove last line
$last = strrpos($value, "\n");
$value = substr($value, 0, $last);
// Remove spaces and convert "z" and "y" exception to a tuple
$tr = array(' ' => '',
"\r" => '',
"\n" => '',
"\t" => '',
"\0" => '',
"\f" => '',
'z' => 'zzzzz',
'y' => 'yyyyy'
);
$value = strtr($value, $tr);
break;
}
}
/**
* Gets check values from an encoded ASCII BTOA value.
*
* @return void
*/

private function btoaGetChecks($value, &$size_dec, &$size_hex, &$check_xor, &$check_sum, &$check_rot)


{
$value = trim($value);
$exp = '/xbtoa[\040]+End[\040]+'.
'N[\040]+([\d]+)[\040]+([0-9a-f]+)[\040]+'.
'E[\040]+([0-9a-f]+)[\040]+'.
'S[\040]+([0-9a-f]+)[\040]+'.
'R[\040]+([0-9a-f]+)'.
'$/i';
if (!preg_match($exp, $value, $match))
{
$this->error = 1;
$this->debug['errinfo'] = array(1001=>'Invalid ASCII BTOA encoded data');
return false;
}
$size_dec = $match[1];

Page 306 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

$size_hex = $match[2];
$check_xor = $match[3];
$check_sum = $match[4];
$check_rot = $match[5];
}
/**
* Generate BTOA values to validate a received text.
*
* @return void
*/

private function btoaCreatechecks($value, &$size_dec, &$size_hex, &$check_xor, &$check_sum, &$check_rot)


{
$size = strlen($value);
// Check xor, sum, rot
$check_xor = 0;
$check_sum = 0;
$check_rot = 0;
for ($i = 0; $i < $size; $i++)
{
$c = ord($value[$i]);
$check_xor ^= $c;
$check_sum += $c + 1;
$check_rot <<= 1;
if ($check_rot & 0x80000000)
{
$check_rot += 1;
}
$check_rot += $c;
}
$size_dec = sprintf('%0.0f', $size);
$size_hex = sprintf('%x', $size);
$check_xor = sprintf('%x', $check_xor);
$check_sum = sprintf('%x', $check_sum);
$check_rot = sprintf('%x', $check_rot);
}
/**
* Validate a decoded ASCII BTOA value.
*
* @return bool
*/

private function btoaValidateChecks($value, $size_dec, $size_hex, $check_xor, $check_sum, $check_rot)


{
self::btoaCreatechecks($value, $size_dec2, $size_hex2, $check_xor2, $check_sum2, $check_rot2);
return $size_dec === $size_dec2 &&
$size_hex === $size_hex2 &&
$check_xor === $check_xor2 &&
$check_sum === $check_sum2 &&
$check_rot === $check_rot2;
}

/**
* Call encode/decode.
*
* @return string
*/

private function getResult()


{
if (strtolower($this->method) == 'encode')
{
$this->result= $this->encode($this->value, $this->variation, 80);
}
elseif (strtolower($this->method)== 'decode')
{

Page 307 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

$this->result= $this->decode($this->value, $this->variation);


}
return true;
}

}
?>
Automatic fill options for text fields
<?php
/**
* AutoFill
*
* This class contains functions work with automatic fill options for text fields.
*
* @package Lib_AutoFill
* @category Library
* @version 1.0
*/
// ------------------------------------------------------------------------
class Lib_AutoFill
{
/**
* Stores function type's name
*
* @var string $type
*/
private $type;
/**
* Flag for error
*
* @var boolean $error
*/
private $error;
/**
* Stores error numbers and description
*
* @var array $debug
*/
public $debug = array();
/**
* Stores the output
*
* @var bool $result
*/
public $result;
/**
* Stores inputs
*
* @var array $data
*/
private $data = array();
/**
* text box id
*
* @var string $txtFiledId
*/
private $txtFiledId;
/**
* display number of data
*
* @var integer $limit
*/
private $limit;
/**
* data fill status
*

Page 308 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

* @var bool $submitOnFill


*/
private $submitOnFill=false;
/**
* java script loaded status
*
* @var bool $javascriptLoaded
*/
private $javascriptLoaded=false;

/**
* Constructs a Lib_AutoFill object with given parameters
* also it will invoke auto fill process
*
* @param string $type
* @param string $txtFiledId
* @param array $data
* @param integer $limit
* @return Lib_AutoFill
*/

public function Lib_AutoFill($type,$txtFiledId,$data,$limit=100)


{
$this->type = $type;
$this->txtFiledId = $txtFiledId;
$this->data = $data;
$this->limit = $limit;

if($this->isValidCall())
{
if(strtolower($type)=='autofill')
$this->fill();
}
}

/**
* Check whether the function call is valid or not
*
* @return bool
*/
private function isValidCall()
{
if(strtolower($this->type)!='autofill')
{
echo '<b>Component Error!<b> Invalid argument <i>type</i> - autofill expected';
exit();
}
else if(empty($this->txtFiledId))
{
echo '<b>Component Error!<b> Invalid argument <i>txtFiledId</i> - text filed id expected';
exit();
}
else if(is_numeric($this->txtFiledId))
{
echo '<b>Component Error!<b> Invalid argument <i>txtFiledId</i> - text filed must be
string';
exit();
}
else if(!is_array($this->data))
{
echo '<b>Component Error!<b> Invalid argument data type <i>data</i> - array expected';
exit();
}
else if(empty($this->data))
{
echo '<b>Component Error!<b> Invalid argument <i>data</i> - fill all the fields';

Page 309 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

exit();
}
else if(empty($this->limit))
{
echo '<b>Component Error!<b> Invalid argument <i>limit</i> - limit expected';
exit();
}
else if(!is_numeric($this->limit))
{
echo '<b>Component Error!<b> Invalid argument <i>limit</i> - limit must be numeric';
exit();
}
return true;
}

/**
* This function call the sub functions and create auto fill text box
*
*/

private function fill()


{
for($j=0;$j<count($this->data);$j++)
$this->addOption($this->data[$j][0]);
$this->setLimit($this->limit);
$this->create();
$style='<input type="text" name='.$this->txtFiledId.' id='.$this->txtFiledId.' />
<style type="text/css">
.autofill-box
{
z-index: 100;
padding: 1px;
background: #e5e5e5;
border: 1px dotted #000;
text-align: left;
font: 11px Verdana, Arial, sans-serif;
}
.autofill-box li {padding: 2px 7px;}
.autofill-box .selection
{
background: #AAF;
color: #FFF;
}</style>';
echo $style;
}

/**
* This function create auto fill text box
*
* @return string
*/

private function create($bool_return = false)


{
$var_name = "AutoFill_" . $this->txtFiledId;
$html = $this->loadJavascript(true);
$html .= '
<script type="text/javascript">
' . $var_name . ' = new AutoFill("' . $this->txtFiledId . '");
' . $var_name . '.setLimit(' . (int)$this->limit . ');
' . $var_name . '.submitOnFill(' . ($this->submitOnFill ? 'true' : 'false') . ');';
foreach ($this->options as $option)
$html .= "\n".' ' . $var_name . '.addOption("' . $option . '");';
$html .= '
</script>';
return $this->printHTML($html, $bool_return);

Page 310 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

}
/**
* This function set input data array
*
*/

private function addOption($option)


{
$this->options[] = $option;
}

/**
* This function set data display limit
*
*/

private function setLimit($limit)


{
$this->limit = (int)$limit;
}

/**
* This function set the fill status
*
*/

private function submitOnFill($bool_submit = true)


{
$this->submitOnFill = (bool)$bool_submit;
}

/**
* This function load the java script
*
* @return string
*/

private function loadJavascript($bool_return = false)


{
if ($this->javascriptLoaded)
{
return;
}
$this->javascriptLoaded = true;
$html = '
<script type="text/javascript">

function AutoFill(fieldId)
{
if (!document.customProperties)
{
document.customProperties = [];
}
if (!document.customProperties[fieldId])
{
document.customProperties[fieldId] = {};
}
document.customProperties[fieldId].autoFill = {
field: null,
list: null,
options: [],
limit: 10,
submitOnFill: false,
currentSelection: -1
};
var autoFill = document.customProperties[fieldId].autoFill;

Page 311 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

this.id = fieldId;
this.addOption = function(value)
{
autoFill.options.push(value);
autoFill.options.sort();
};
this.setLimit = function(limit)
{
autoFill.limit = limit;
};
this.submitOnFill = function(boolSubmit)
{
autoFill.submitOnFill = typeof boolSubmit == "undefined" ? true : boolSubmit;
};
if (window.addEventListener)
{
window.addEventListener("load", function() {AutoFill.init(fieldId)}, true);
}
else if (window.attachEvent)
{
window.attachEvent("onload", function() {AutoFill.init(fieldId)});
}
}
AutoFill.init = function(fieldId)
{
var field = document.getElementById(fieldId), autoFill;

if (!field)
{
throw new Error("element not found");
}
field.autoFill = autoFill = document.customProperties[fieldId].autoFill;
var cont = document.createElement("div"), box = document.createElement("div");
var list = document.createElement("ul");
cont.style.display = "inline";
cont.style.position = "relative";
field = field.parentNode.replaceChild(cont, field);
cont.appendChild(field);
cont.appendChild(box);
box.appendChild(list);
field.onkeydown = function(e)
{
if (!e)
{
e = window.event;
}
var keyCode = (e.keyCode ? e.keyCode : (e.which ? e.which : 0));
var autoFill = document.customProperties[this.id].autoFill;
var list = autoFill.list, current = autoFill.currentSelection;
if ((keyCode == 38) || (keyCode == 40))
{
var i = current + (keyCode == 38 ? -1 : 1);
AutoFill.moveSelectionTo(list, i);
}
else if (keyCode == 13)
{
if ((current > -1) && (current < list.childNodes.length))
{
var item = list.childNodes.item(current);
field.nextSibling.hide();
autoFill.currentSelection = -1;
if (item.className != "")
{
var le = field.value.lastIndexOf(",");
var old_field = field.value.substr(0,le);
if(le != -1)

Page 312 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

{
field.value = old_field+","+item.innerHTML;
}
else
{
field.value = item.innerHTML;
}
list.clear();
return false;
}
}
}
};
field.onkeyup = function(e)
{
if (!e)
{
e = window.event;
}
var keyCode = (e.keyCode ? e.keyCode : (e.which ? e.which : 0));
var autoFill = document.customProperties[this.id].autoFill;
var list = autoFill.list, box = list.parentNode;
if ((keyCode != 38) && (keyCode != 40) && (keyCode != 13))
{
list.clear();
if (this.value == "")
{
box.style.display = "none";
}
else
{

var p = this.value.replace(/([\\\|\.\+\*\?\[\^\(\$\)])/gi, "\\$1");


var p =p.split(",").pop();
var pattern = new RegExp(("^"+ p +".+$"), "i"), i = -1, j = 0;
while (++i < autoFill.options.length) {
if (autoFill.options[i].match(pattern))
{
if ((j < autoFill.limit) || (autoFill.limit < 0))
{
list.addItem(autoFill.options[i], j);
}
j++;
}
}
if ((j > autoFill.limit) && (autoFill.limit > -1))
{
var more = document.createElement("li");
more.innerHTML = "...";
list.appendChild(more);
}
if (list.childNodes.length > 0)
{
box.show();
}
else
{
box.hide();
}
}
}
};
field.onfocus = function()
{
var autoFill = document.customProperties[this.id].autoFill;
var list = autoFill.list, box = list.parentNode;

Page 313 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

if (list.childNodes.length > 0)
{
box.show();
}
};
field.onblur = function()
{
var box = this.nextSibling;
setTimeout(function() {box.hide()}, 300);
};
box.className = "autofill-box";
box.style.display = "none";
box.style.position = "absolute";
box.style.top = (field.clientHeight + 4) + "px";
box.style.left = "0";
box.show = function() {box.style.display = "";};
box.hide = function() {box.style.display = "none";};
list.style.margin = "0";
list.style.padding = "0";
list.style.listStyle = "none";
list.clear = function()
{
for (var i = list.childNodes.length - 1; i >= 0; i--)
{
list.removeChild(list.childNodes.item(i));
}
};
list.addItem = function(value, index)
{
var li = document.createElement("li");
li.className = (index == field.autoFill.currentSelection) ? "selection" : "selectable";
li.innerHTML = value;
li.index = index;
li.style.cursor = "pointer";
list.appendChild(li);
li.onclick = function()
{
field.focus();
var le = field.value.lastIndexOf(",");
var old_field = field.value.substr(0,le);

if(le != -1)
{
field.value = old_field+","+value;
}
else
{
field.value = value;
}
if (field.autoFill.submitOnFill)
{
field.form.submit();
}
};
li.onmouseover = function()
{
AutoFill.moveSelectionTo(list, li.index);
};
li.onmouseout = function()
{
field.autoFill.currentSelection = -1;
li.className = "selectable";
};
};
field.autoFill.field = field;
field.autoFill.list = list;

Page 314 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

}
AutoFill.moveSelectionTo = function(list, index)
{
var autoFill = list.parentNode.previousSibling.autoFill;
var current = autoFill.currentSelection;
if ((current > -1) && (current < list.childNodes.length))
{
var currentItem = list.childNodes.item(current);
if (currentItem.className != "")
{
currentItem.className = "selectable";
}
}
if (index < 0)
{
autoFill.currentSelection = -1;
} else if (index >= list.childNodes.length)
{
autoFill.currentSelection = list.childNodes.length;
if (list.lastChild && (list.lastChild.className == ""))
{
autoFill.currentSelection--;
}
}
else
{
autoFill.currentSelection = index;
var item = list.childNodes.item(index);
if (item.className != "")
{
item.className = "selection";
}
}
}
</script>';
return $this->printHTML($html, $bool_return);
}

/**
* This function print the output
*
* @return string
*/

private function printHTML($html, $bool_return)


{
if ($bool_return)
{
return $html;
}
$this->result=$html;
return true;
}

}
?>
Take the Database Backup
<?php
/**
* BackupDB
*
* This class contains functions backup to database.
*
* @package Lib_BackupDB
* @category Library
* @version 1.0

Page 315 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

*/
// ------------------------------------------------------------------------
class Lib_BackupDB
{
/**
* Stores function type's name
*
* @var string $type
*/
private $type;
/**
* Flag for error
*
* @var boolean $error
*/
private $error;
/**
* Stores error numbers and description
*
* @var array $debug
*/
public $debug = array();
/**
* Stores the output
*
* @var bool $result
*/
public $result;
/**
* user name
*
* @var string $userName
*/
private $userName;
/**
* password
*
* @var string $password
*/
private $password;
/**
* server name
*
* @var string $serverName
*/
private $serverName;
/**
* database name
*
* @var string $dbName
*/
private $dbName;
/**
* backup path
*
* @var string $backupPath
*/
private $backupPath;
/**
* table name
*
* @var string $tables
*/
private $tables;

/**

Page 316 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

* Constructs a Lib_BackupDB object with given parameters


* also it will invoke backup process
*
* @param string $type
* @param string $userName
* @param string $password
* @param string $serverName
* @param string $dbName
* @param string $backupPath
* @param string $tables
* @return Lib_BackupDB
*/

public function Lib_BackupDB($type,$userName,$password,$serverName,$dbName,$backupPath,$tables = '*')


{
$this->type = $type;
$this->userName=$userName;
$this->password=$password;
$this->serverName=$serverName;
$this->dbName=$dbName;
$this->backupPath=$backupPath;
$this->tables=$tables;

if($this->isValidCall())
{
if(strtolower($type)=='backup')
$this->backup();

}
}

/**
* Check whether the function call is valid or not
*
* @return bool
*/

private function isValidCall()


{
if(strtolower($this->type)!='backup')
{
echo '<b>Component Error!<b> Invalid argument <i>type</i> - backup expected';
exit();
}
else if(empty($this->userName))
{
echo '<b>Component Error!<b> Invalid argument <i>userName</i> - user name expected';
exit();
}
else if(empty($this->serverName))
{
echo '<b>Component Error!<b> Invalid argument <i>serverName</i> - server name
expected';
exit();
}
else if(empty($this->dbName))
{
echo '<b>Component Error!<b> Invalid argument <i>dbName</i> - database name
expected';
exit();
}
else if(empty($this->backupPath))
{
echo '<b>Component Error!<b> Invalid argument <i>backupPath</i> - backup path
expected';
exit();

Page 317 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

}
else if(!file_exists($this->backupPath))
{
echo '<b>Component Error!<b> Path not found <i>'.$this->backupPath.'</i> - backup path
not found';
exit();
}
else if(!is_writable($this->backupPath))
{
echo '<b>Component Error!<b> Access Denied <i>'.$this->backupPath.'</i> - backup path
not writable';
exit();
}
else if(empty($this->tables))
{
echo '<b>Component Error!<b> Invalid argument <i>tables</i> - table name expected';
exit();
}
return true;
}

/**
* check database connection and backup the database.
*
* @return string
*/

private function backup()


{

$link = mysql_connect($this->serverName,$this->userName,$this->password);
if( $link)
{
$dbCon=mysql_select_db($this->dbName,$link);
if($dbCon)
{
//get all of the tables
if($this->tables == '*')
{
$tables = array();
$res = mysql_query('SHOW TABLES');
while($row = mysql_fetch_row($res))
{
$tables[] = $row[0];
}
}
else
{
$tables = is_array($tables) ? $tables : explode(',',$this->tables);
}

if(count($tables) >0)
{
foreach($tables as $table)
{
$res = mysql_query('SELECT * FROM '.$table);
if(!empty($res))
{
$num_fields = mysql_num_fields($res);

//$return.= 'DROP TABLE '.$table.';';


$row2 = mysql_fetch_row(mysql_query('SHOW CREATE TABLE
'.$table));
$return.= "\n\n".$row2[1].";\n\n";

for ($i = 0; $i < $num_fields; $i++)

Page 318 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

{
while($row = mysql_fetch_row($res))
{
$return.= 'INSERT INTO '.$table.' VALUES(';
for($j=0; $j<$num_fields; $j++)
{
$row[$j] = addslashes($row[$j]);
$row[$j] =
ereg_replace("\n","\\n",$row[$j]);
if (isset($row[$j])) { $return.=
'"'.$row[$j].'"' ; } else { $return.= '""'; }
if ($j<($num_fields-1)) { $return.= ','; }
}
$return.= ");\n";
}
}
$return.="\n\n\n";
}
else
{
$this->error = 1;
$this->debug['errinfo'] = array(1004=>'table not found');
return false;
}
}

//save file
$handle = fopen($this->backupPath."/".$this->dbName.'.sql','w+');
fwrite($handle,$return);
fclose($handle);
$this->result="true";
return true;
}
else
{
$this->error = 1;
$this->debug['errinfo'] = array(1003=>'table not found');
return false;
}
}
else
{
$this->error = 1;
$this->debug['errinfo'] = array(1002=>'database not found');
return false;
}
}
else
{
$this->error = 1;
$this->debug['errinfo'] = array(1001=>'connection not found');
return false;
}
}

}
?>
Create the Bar Chart
<?php
/**
* BarChart
*
* This class contains functions to handle the bar chart.
*
* @package Lib_BarChart
* @category Library

Page 319 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

* @version 1.0
*/
// ------------------------------------------------------------------------

class Lib_BarChart
{
/**
* Stores function type's name
*
* @var string $type
*/
private $type;
/**
* Flag for error
*
* @var boolean $error
*/
private $error;
/**
* Stores inputs
*
* @var array $ary
*/
private $ary = array();
/**
* Stores bar chart title name
*
* @var array $title
*/
private $title;
/**
* Stores error numbers and description
*
* @var array $debug
*/
public $debug = array();
/**
* Stores the output
*
* @var bool $result
*/
public $result;

/**
* Constructs a Lib_BarChart object with given parameters
* also it will invoke bar chart process
*
* @param string $type
* @param array $ary
* @return Lib_BarChart
*/

public function Lib_BarChart($type,$ary=array(),$title='')


{
$this->type = $type;
$this->ary = $ary;
$this->title = $title;

if($this->isValidCall())
{
if(strtolower($type)=='barchart')
$this->barChart();
}
}

/**

Page 320 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

* Check whether the function call is valid or not


*
* @return bool
*/

private function isValidCall()


{
if(strtolower($this->type)!='barchart')
{
echo '<b>Component Error!<b> Invalid argument <i>type</i> - barchart expected';
exit();
}
else if(!is_array($this->ary))
{
echo '<b>Component Error!<b> Invalid argument data type <i>data</i> - array expected';
exit();
}
else if(empty($this->ary))
{
echo '<b>Component Error!<b> Invalid argument <i>array</i> - fill all the fields';
exit();
}
else if(!function_exists("gd_info"))
{
echo '<b>Component Error!<b> Invalid Stream <i>GD</i> - Cannot initialize new GD image
stream';
exit();
}
return true;
}

/**
* This function create bar chart image for the given inputs.
*
* @return image barChart
*/

private function barChart()


{
$data=$this->ary;
$width = 480;
$height = 250;

$image = imagecreate($width, $height);


$white = imagecolorallocate($image, 0xFF, 0xFF, 0xFF);
$navy = imagecolorallocate($image, 0x00, 0x00, 0x80);
$black = imagecolorallocate($image, 0x00, 0x00, 0x00);
$gray = imagecolorallocate($image, 0xC0, 0xC0, 0xC0);

$maxval = max($data);
$nval = sizeof($data);
$vmargin = 20;
$hmargin = 38;
$base = floor(($width - $hmargin) / $nval); // distance between columns
$ysize = $height - 2 * $vmargin; // y-size of plot
$xsize = $nval * $base; // x-size of plot

$titlefont = 3;
$title = $this->title;
$txtsz = imagefontwidth($titlefont) * strlen($title); // pixel-width of title
$xpos = (int)($hmargin + ($xsize - $txtsz)/2); // center the title
$xpos = max(1, $xpos); // force positive coordinates
$ypos = 3; // distance from top
imagestring($image, $titlefont, $xpos, $ypos, $title , $black);
// y labels and grid lines
$labelfont = 2;

Page 321 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

$ngrid = 1; // number of grid lines


$dydat = $maxval / $ngrid; // data units between grid lines
$dypix = $ysize / ($ngrid + 1); // pixels between grid lines
if($dydat >0 && $dypix>0)
{
for ($i = 0; $i <= ($ngrid + 1); $i++)
{
// height of grid line in units of data
$ydat = (int)($i * $dydat);
// height of grid line in pixels
$ypos = $vmargin + $ysize - (int)($i*$dypix);
$txtsz = imagefontwidth($labelfont) * strlen($ydat); // pixel-width of label
$txtht = imagefontheight($labelfont); // pixel-height of label
$xpos = (int)(($hmargin - $txtsz) / 2);
$xpos = max(1, $xpos);
imagestring($image, $labelfont, $xpos,
$ypos - (int)($txtht/2), $ydat, $black);
if (!($i == 0) && !($i > $ngrid))
{
imageline($image, $hmargin - 3,
$ypos, $hmargin + $xsize, $ypos, $gray);

}
}
// columns and x labels
$padding = 3; // half of spacing between columns
$yscale = $ysize / (($ngrid+1) * $dydat); // pixels per data unit
for ($i = 0; list($xval, $yval) = each($data); $i++)
{
// vertical columns
$ymax = $vmargin + $ysize;
$ymin = $ymax - (int)($yval*$yscale);
$xmax = $hmargin + ($i+1)*$base - $padding;
$xmin = $hmargin + $i*$base + $padding;
imagefilledrectangle($image, $xmin, $ymin, $xmax, $ymax, $navy);

// x labels
$txtsz = imagefontwidth($labelfont) * strlen($xval);
$xpos = $xmin + (int)(($base - $txtsz) / 2);
$xpos = max($xmin, $xpos);
$ypos = $ymax + 3; // distance from x axis
imagestring($image, $labelfont, $xpos, $ypos, $xval, $black);
}

imagerectangle($image, $hmargin, $vmargin,$hmargin + $xsize, $vmargin + $ysize, $black);

header("Content-type: image/jpg");
return imagegif($image);
imagedestroy($image);
}
else
{
$this->error = 1;
$this->debug['errinfo'] = array(1001=>'Give proper input');
return false;
}
}

}
?>
Create Barcode
<?
/**
* Barcode
*

Page 322 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

* This class contains functions create Barcode.


*
* @package Lib_Barcode
* @category Library
* @version 1.0
*/
// ------------------------------------------------------------------------
class Lib_Barcode
{
/**
* Stores function type's name
*
* @var string $type
*/
private $type;
/**
* Flag for error
*
* @var boolean $error
*/
private $error;
/**
* Stores error numbers and description
*
* @var array $debug
*/
public $debug = array();
/**
* Stores the output
*
* @var string $result
*/
public $result;
/**
* barcode input number
*
* @var integer $bcode
*/
private $bcode;
/**
* barcode font path
*
* @var string $bfont
*/
private $bfont;
/**
* barcode default exe file
*
* @var string $genbarcodeLocation
*/
public $genbarcodeLocation="/usr/local/bin/genbarcode";
/**
* Constructs a Lib_Barcode object with given parameters
* also it is use to generate barcode.
*
* @param string $type
* @param integer $bcode
* @param string $bfont
* @return Lib_Barcode
*/

public function Lib_Barcode($type,$bcode,$bfont)


{
$this->type = $type;
$this->bcode = $bcode;
$this->bfont = $bfont;

Page 323 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

if($this->isValidCall())
{
if(strtolower($type)=='barcode')
$this->barcodeDisplay();
}

/**
* Check whether the function call is valid or not
*
* @return bool
*/

private function isValidCall()


{
if(strtolower($this->type)!='barcode')
{
echo '<b>Component Error!<b> Invalid argument <i>type</i> - barcode expected';
exit();
}
elseif(empty($this->bfont))
{
echo '<b>Component Error!<b> Invalid argument data type <i>font</i> - font name
expected';
exit();
}
elseif(!file_exists($this->bfont))
{
echo '<b>Component Error!<b> Invalid argument data type <i>'.$this->bfont.'</i> - font not
found';
exit();
}
elseif(empty($this->bcode))
{
echo '<b>Component Error!<b> Invalid argument data type <i>bcode</i> - barcode
expected';
exit();
}
elseif(!is_numeric($this->bcode))
{
echo '<b>Component Error!<b> Invalid argument data type <i>bcode</i> - barcode must be
numeric';
exit();
}
elseif(strlen($this->bcode)<12 || strlen($this->bcode)>13)
{
echo '<b>Component Error!<b> Invalid argument data type <i>bcode</i> - barcode must be
allow 12/13 digits only';
exit();
}
elseif (!function_exists("imagecreate"))
{
echo '<b>Component Error!<b> Invalid Stream <i>GD</i> - Cannot initialize new GD image
stream';
exit();
}
return true;
}

/**
* configuration end's heare.
*
* @return integer
*/

Page 324 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

private function barcodeGenEanSum($ean)


{
$even=true;
$esum=0;
$osum=0;
for ($i=strlen($ean)-1;$i>=0;$i--)
{
if ($even)
$esum+=$ean[$i];
else
$osum+=$ean[$i];
$even=!$even;
}
return (10-((3*$esum+$osum)%10))%10;
}

/**
* encodes with EAN-13 using built in functions.
*
* @return array
*/

private function barcodeEncodeEan($ean, $encoding = "EAN-13")


{
$digits=array(3211,2221,2122,1411,1132,1231,1114,1312,1213,3112);

$mirror=array("000000","001011","001101","001110","010011","011001","011100","010101","010110","011010
");
$guards=array("9a1a","1a1a1","a1a");

$ean=trim($ean);
if (eregi("[^0-9]",$ean))
{
return array("text"=>"Invalid EAN-Code");
}
$encoding=strtoupper($encoding);
if ($encoding=="ISBN")
{
if (!ereg("^978", $ean))
$ean="978".$ean;
}
if (ereg("^978", $ean))
$encoding="ISBN";

$ean=substr($ean,0,12);
$eansum=$this->barcodeGenEanSum($ean);
$ean.=$eansum;
$line=$guards[0];
for ($i=1;$i<13;$i++)
{
$str=$digits[$ean[$i]];
if ($i<7 && $mirror[$ean[0]][$i-1]==1)
$line.=strrev($str);
else
$line.=$str;
if ($i==6)
$line.=$guards[1];
}
$line.=$guards[2];

/* create text */
$pos=0;
$text="";
for ($a=0;$a<13;$a++)
{
if ($a>0)

Page 325 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

$text.=" ";
$text.="$pos:12:{$ean[$a]}";
if ($a==0)
$pos+=12;
else if ($a==6)
$pos+=12;
else
$pos+=7;
}

return array("encoding" => $encoding,"bars" => $line,"text" => $text);


}

/**
* Generate the bar code image content
*
* @return image
*/

private function barcodeOutimage($text, $bars, $scale = 1, $mode = "png",$total_y = 0, $space = '')


{
// global $bar_color, $bg_color, $text_color;
$bar_color=Array(0,0,0);
$bg_color=Array(255,255,255);
$text_color=Array(0,0,0);
global $font_loc;
/* set defaults */
if ($scale<1)
$scale=2;
$total_y=(int)($total_y);
if ($total_y<1)
$total_y=(int)$scale * 60;
if (!$space)
$space=array('top'=>2*$scale,'bottom'=>2*$scale,'left'=>2*$scale,'right'=>2*$scale);

/* count total width */


$xpos=0;
$width=true;
for ($i=0;$i<strlen($bars);$i++)
{
$val=strtolower($bars[$i]);
if ($width)
{
$xpos+=$val*$scale;
$width=false;
continue;
}
if (ereg("[a-z]", $val))
{
/* tall bar */
$val=ord($val)-ord('a')+1;
}
$xpos+=$val*$scale;
$width=true;
}

/* allocate the image */


$total_x=( $xpos )+$space['right']+$space['right'];
$xpos=$space['left'];

$im=imagecreate($total_x, $total_y);
/* create two images */
$col_bg=ImageColorAllocate($im,$bg_color[0],$bg_color[1],$bg_color[2]);
$col_bar=ImageColorAllocate($im,$bar_color[0],$bar_color[1],$bar_color[2]);
$col_text=ImageColorAllocate($im,$text_color[0],$text_color[1],$text_color[2]);
$height=round($total_y-($scale*10));

Page 326 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

$height2=round($total_y-$space['bottom']);

/* paint the bars */


$width=true;
for ($i=0;$i<strlen($bars);$i++)
{
$val=strtolower($bars[$i]);
if ($width)
{
$xpos+=$val*$scale;
$width=false;
continue;
}
if (ereg("[a-z]", $val))
{
/* tall bar */
$val=ord($val)-ord('a')+1;
$h=$height2;
}
else
$h=$height;
imagefilledrectangle($im, $xpos, $space['top'], $xpos+($val*$scale)-1, $h, $col_bar);
$xpos+=$val*$scale;
$width=true;
}
/* write out the text */
global $_SERVER;
$chars=explode(" ", $text);
reset($chars);
while (list($n, $v)=each($chars))
{
if (trim($v))
{
$inf=explode(":", $v);
$fontsize=$scale*($inf[1]/1.8);
$fontheight=$total_y-($fontsize/2.7)+2;
@imagettftext($im, $fontsize, 0, $space['left']+($scale*$inf[0])+2,
$fontheight, $col_text, $this->bfont, $inf[2]);
}
}

/* output the image */


$mode=strtolower($mode);
if ($mode=='jpg' || $mode=='jpeg')
{
header("Content-Type: image/jpeg; name=\"barcode.jpg\"");
imagejpeg($im);
}
else if ($mode=='gif')
{
header("Content-Type: image/gif; name=\"barcode.gif\"");
imagegif($im);
}
else
{
header("Content-Type: image/png; name=\"barcode.png\"");
imagepng($im);
}
}

/**
* Generate the barcode text
*
* @return string
*/

Page 327 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

private function barcodeOuttext($code,$bars)


{
$width=true;
$xpos=$heigh2=0;
$bar_line="";
for ($i=0;$i<strlen($bars);$i++)
{
$val=strtolower($bars[$i]);
if ($width)
{
$xpos+=$val;
$width=false;
for ($a=0;$a<$val;$a++) $bar_line.="-";
continue;
}
if (ereg("[a-z]", $val))
{
$val=ord($val)-ord('a')+1;
$h=$heigh2;
for ($a=0;$a<$val;$a++) $bar_line.="I";
}
else
for ($a=0;$a<$val;$a++)
$bar_line.="#";
$xpos+=$val;
$width=true;
}
return $bar_line;
}

/* Generate barcode with HTML.


*
*/

private function barcodeOuthtml($code, $bars, $scale = 1, $total_y = 0, $space = '')


{
/* set defaults */
$total_y=(int)($total_y);
if ($scale<1)
$scale=2;
if ($total_y<1)
$total_y=(int)$scale * 60;
if (!$space)
$space=array('top'=>2*$scale,'bottom'=>2*$scale,'left'=>2*$scale,'right'=>2*$scale);

/* generate html-code */
$height=round($total_y-($scale*10));
$height2=round($total_y)-$space['bottom'];
$out=
'<Table border=0 cellspacing=0 cellpadding=0 bgcolor="white">'."\n".
'<TR><TD><img src=white.png height="'.$space['top'].'" width=1></TD></TR>'."\n".
'<TR><TD>'."\n".
'<IMG src=white.png height="'.$height2.'" width="'.$space['left'].'">';

$width=true;
for ($i=0;$i<strlen($bars);$i++)
{
$val=strtolower($bars[$i]);
if ($width)
{
$w=$val*$scale;
if ($w>0) $out.="<IMG src=white.png height=\"$total_y\" width=\"$w\" align=top>";
$width=false;
continue;
}
if (ereg("[a-z]", $val))

Page 328 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

{
//hoher strich
$val=ord($val)-ord('a')+1;
$h=$height2;
}
else
$h=$height;
$w=$val*$scale;
if ($w>0)
$out.='<IMG src="black.png" height="'.$h.'" width="'.$w.'" align=top>';
$width=true;
}
$out.=
'<IMG src=white.png height="'.$height2.'" width=".'.$space['right'].'">'.
'</TD></TR>'."\n".
'<TR><TD><img src="white.png" height="'.$space['bottom'].'" width="1"></TD></TR>'."\n".
'</TABLE>'."\n";
return $out;
}

/**
* encodes $code with $encoding using genbarcode
*
* @return array
*/

private function barcodeEncodeGenbarcode($code,$encoding)


{
//global $genbarcodeLocation;
/* delete EAN-13 checksum */
if (eregi("^ean$", $encoding) && strlen($code)==13)
$code=substr($code,0,12);
if (!$encoding)
$encoding="ANY";
$encoding=ereg_replace("[|\\]", "_", $encoding);
$code=ereg_replace("[|\\]", "_", $code);
$cmd=$genbarcodeLocation." \""
.str_replace("\"", "\\\"",$code)."\" \""
.str_replace("\"", "\\\"",strtoupper($encoding))."\"";
//print "'$cmd'<BR>\n";
$fp=popen($cmd, "r");
if ($fp)
{
$bars=fgets($fp, 1024);
$text=fgets($fp, 1024);
$encoding=fgets($fp, 1024);
pclose($fp);
}
else
return false;
$ret=array("encoding" => trim($encoding),"bars" => trim($bars),"text" => trim($text));
if (!$ret['encoding'])
return false;
if (!$ret['bars'])
return false;
if (!$ret['text'])
return false;
return $ret;
}

/**
* built-in encoder
*
* @return array
*/

Page 329 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

private function barcodeEncode($code,$encoding)


{
//global $genbarcodeLocation;
if (
((eregi("^ean$", $encoding)
&& ( strlen($code)==12 || strlen($code)==13)))

|| (($encoding) && (eregi("^isbn$", $encoding))


&& (( strlen($code)==9 || strlen($code)==10) ||
(((ereg("^978", $code) && strlen($code)==12) ||
(strlen($code)==13)))))

|| (( !isset($encoding) || !$encoding || (eregi("^ANY$", $encoding) ))


&& (ereg("^[0-9]{12,13}$", $code)))

)
{
/* use built-in EAN-Encoder */
$bars=$this->barcodeEncodeEan($code, $encoding);
}
else if (file_exists($genbarcodeLocation))
{
/* use genbarcode */
$bars=$this->barcodeEncodeGenbarcode($code, $encoding);
}
else
{
$this->error = 1;
$this->debug['errinfo'] = array(1001=>'Invalid number of digits.You should give 12/13 digits');
return false;
}
return $bars;
}
/**
* encodes and prints a barcode
*
* @return array
*/

private function barcodePrint($code, $encoding="ANY", $scale = 2 ,$mode = "png" )


{
$bars=$this->barcodeEncode($code,$encoding);
if (!$bars)
return;
if (!$mode)
$mode="png";
if (eregi($mode,"^(text|txt|plain)$"))
print $this->barcodeOuttext($bars['text'],$bars['bars']);
elseif (eregi($mode,"^(html|htm)$"))
$s=0;//print barcodeOuthtml($bars['text'],$bars['bars'], $scale,0, 0);
else
$this->barcodeOutimage($bars['text'],$bars['bars'],$scale, $mode);
return $bars;
}
/**
* Call barcode print function
*
* @return barcode image
*/

private function barcodeDisplay()


{
$code=$this->bcode;
$this->barcodePrint($code);
}
}

Page 330 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

?>
Given byte to Byte, Kilo byte, Mega byte, Giga byte, TB and Pb
<?php
/**
* Byte
*
* This class contains functions find out given byte to byte,kilo byte,mega byte,giga byte etc.
*
* @package Lib_Byte
* @category Library
* @version 1.0
*/
// ------------------------------------------------------------------------
class Lib_Byte
{
/**
* Stores function type's name
*
* @var string $type
*/
private $type;
/**
* Flag for error
*
* @var boolean $error
*/
private $error;
/**
* Stores error numbers and description
*
* @var array $debug
*/
public $debug = array();
/**
* Stores the output
*
* @var bool $result
*/
public $result;
/**
* input number
*
* @var integer $number
*/
private $number;

/**
* Constructs a Lib_Byte object with given parameters
* also it will invoke byte process
*
* @param string $type
* @param integer $number
* @return Lib_Byte
*/

public function Lib_Byte($type,$number)


{
$this->type = $type;
$this->number=$number;

if($this->isValidCall())
{
if(strtolower($type)=='byte')
$this->getSize();

Page 331 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

}
}

/**
* Check whether the function call is valid or not
*
* @return bool
*/

private function isValidCall()


{
if(strtolower($this->type)!='byte')
{
echo '<b>Component Error!<b> Invalid argument <i>type</i> - byte expected';
exit();
}
else if(empty($this->number))
{
echo '<b>Component Error!<b> Invalid argument <i>number</i> - number expected';
exit();
}
else if(!is_numeric($this->number))
{
echo '<b>Component Error!<b> Invalid argument <i>number</i> - number must be numeric';
exit();
}
return true;
}

/**
* get the size for given byte value
*
* @return string
*/

private function getSize ()


{
$sizeb=$this->number;
$sizekb = $sizeb / 1024;
$sizemb = $sizekb / 1024;
$sizegb = $sizemb / 1024;
$sizetb = $sizegb / 1024;
$sizepb = $sizetb / 1024;
if ($sizeb > 1) {$size = round($sizeb,2) . "b";}
if ($sizekb > 1) {$size = round($sizekb,2) . "kb";}
if ($sizemb > 1) {$size = round($sizemb,2) . "mb";}
if ($sizegb > 1) {$size = round($sizegb,2) . "gb";}
if ($sizetb > 1) {$size = round($sizetb,2) . "tb";}
if ($sizepb > 1) {$size = round($sizepb,2) . "pb";}
$this->result=$size;
return true;
}

}
?>
Draw the Pie Chart
<?php
/**
* Chart
*
* This class contains functions to handle the pie chart.
*
* @package Lib_Chart
* @category Library
* @version 1.0
*/

Page 332 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

// ------------------------------------------------------------------------

class Lib_Chart
{
/**
* Stores function type's name
*
* @var string $type
*/
private $type;
/**
* Flag for error
*
* @var boolean $error
*/
private $error;
/**
* Stores inputs
*
* @var array $ary
*/
private $ary = array();
/**
* Stores error numbers and description
*
* @var array $debug
*/
public $debug = array();
/**
* Stores the output
*
* @var bool $result
*/
public $result;

/**
* Constructs a Lib_Chart object with given parameters
* also it will invoke pie chart process
*
* @param string $type
* @param array $ary
* @return Lib_Chart
*/

public function Lib_Chart($type,$ary=array())


{
$this->type = $type;
$this->ary = $ary;
$this->imageName = $imageName;

if($this->isValidCall())
{
if(strtolower($type)=='piechart')
$this->pieChart();
}
}

/**
* Check whether the function call is valid or not
*
* @return bool
*/

private function isValidCall()


{
if(strtolower($this->type)!='piechart')

Page 333 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

{
echo '<b>Component Error!<b> Invalid argument <i>type</i> - piechart expected';
exit();
}
else if(!is_array($this->ary))
{
echo '<b>Component Error!<b> Invalid argument data type <i>data</i> - array expected';
exit();
}
else if(empty($this->ary))
{
echo '<b>Component Error!<b> Invalid argument <i>array</i> - fill all the fields';
exit();
}
else if(!function_exists("gd_info"))
{
echo '<b>Component Error!<b> Invalid Stream <i>GD</i> - Cannot initialize new GD image
stream';
exit();
}
return true;
}

/**
* This function create pie chart image for the given inputs.
*
* @return image pieChart
*/

private function pieChart()


{
if(count($this->ary)==2)
{
$data=$this->ary[0];
$label=$this->ary[1];
if(!empty($data) && !empty($label))
{
$datamatch=0;
$labelmatch=0;

$data1 = explode('*',$data);
$label1 = explode('*',$label);

$datacount=count($data1);
$labelcount=count($label1);
if($datacount!=1 || $labelcount!=1)
{
if($datacount==$labelcount)
{
for($count=0;$count< count($data1);$count++)
{
if(!is_numeric($data1[$count]))
{
$datamatch=1;

}
}
for($count=0;$count< count($label1);$count++)
{
if(is_numeric($label1[$count]))
{
$labelmatch=1;

}
}
if($datamatch!=1 && $labelmatch!=1)

Page 334 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

$show_label = true; // true = show label, false = don't show


label.
$show_percent = true; // true = show percentage, false =
don't show percentage.
$show_text = true; // true = show text, false = don't show
text.
$show_parts = false; // true = show parts, false = don't
show parts.
$label_form = 'round'; // 'square' or 'round' label.
$width = 199;
$background_color ='FFFFFF'; // background-color of the
chart...
$text_color = '000000'; // text-color.
$colors = array('003366', 'CCD6E0', '7F99B2','F7EFC6',
'C6BE8C', 'CC6600','990000','520000','BFBFC1','808080'); // colors of the slices.
$shadow_height = 16; // Height on shadown.
$shadow_dark = true; // true = darker shadow, false =
lighter shadow...
// DON'T CHANGE ANYTHING BELOW THIS LINE...
$height = $width/2;
$data = explode('*',$data);
if ($label != '') $label = explode('*',$label);
for ($i = 0; $i < count($label); $i++)
{
if ($data[$i]/array_sum($data) < 0.1) $number[$i]
= ' '.number_format(($data[$i]/array_sum($data))*100,1,',','.').'%';
else $number[$i] =
number_format(($data[$i]/array_sum($data))*100,1,',','.').'%';
if (strlen($label[$i]) > $text_length) $text_length =
strlen($label[$i]);
}
if (is_array($label))
{
$antal_label = count($label);
$xtra = (5+15*$antal_label)-
($height+ceil($shadow_height));
if ($xtra > 0) $xtra_height = (5+15*$antal_label)-
($height+ceil($shadow_height));

$xtra_width = 5;
if ($show_label) $xtra_width += 20;
if ($show_percent) $xtra_width += 45;
if ($show_text) $xtra_width += $text_length*8;
if ($show_parts) $xtra_width += 35;
}
$img = ImageCreateTrueColor($width+$xtra_width,
$height+ceil($shadow_height)+$xtra_height);

ImageFill($img, 0, 0, $this->colorHex($img,
$background_color));

foreach ($colors as $colorkode)


{
$fill_color[] = $this->colorHex($img, $colorkode);
$shadow_color[] = $this->colorHexshadow($img,
$colorkode, $shadow_dark);
}
$label_place = 5;
if (is_array($label))
{
for ($i = 0; $i < count($label); $i++)
{
if ($label_form == 'round' && $show_label)
{

Page 335 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

imagefilledellipse($img,$width+11,$label_place+5,10,10, $this->colorHex($img, $colors[$i % count($colors)]));

imageellipse($img,$width+11,$label_place+5,10,10, $this->colorHex($img, $text_color));


}
else if ($label_form == 'square' &&
$show_label)
{

imagefilledrectangle($img,$width+6,$label_place,$width+16,$label_place+10, $this->colorHex($img, $colors[$i


% count($colors)]));

imagerectangle($img,$width+6,$label_place,$width+16,$label_place+10, $this->colorHex($img, $text_color));


}
if ($show_percent) $label_output =
$number[$i].' ';
if ($show_text) $label_output =
$label_output.$label[$i].' ';
if ($show_parts) $label_output =
$label_output.$data[$i];

imagestring($img,'2',$width+20,$label_place,$label_output, $this->colorHex($img, $text_color));


$label_output = '';
$label_place = $label_place + 15;
}
}
$centerX = round($width/2);
$centerY = round($height/2);
$diameterX = $width-4;
$diameterY = $height-4;
$data_sum = array_sum($data);
$start = 270;
for ($i = 0; $i < count($data); $i++)
{
$value += $data[$i];
$end = ceil(($value/$data_sum)*360) + 270;
$slice[] = array($start, $end,
$shadow_color[$value_counter % count($shadow_color)], $fill_color[$value_counter % count($fill_color)]);
$start = $end;
$value_counter++;
}
for ($i=$centerY+$shadow_height; $i>$centerY; $i--)
{
for ($j = 0; $j < count($slice); $j++)
{
imagefilledarc($img, $centerX, $i,
$diameterX, $diameterY, $slice[$j][0], $slice[$j][1], $slice[$j][2], IMG_ARC_PIE);
}
}
for ($j = 0; $j < count($slice); $j++)
{
imagefilledarc($img, $centerX, $centerY,
$diameterX, $diameterY, $slice[$j][0], $slice[$j][1], $slice[$j][3], IMG_ARC_PIE);
}
$this->outputImage($img);

else
{
$this->error = 1;
$this->debug['errinfo'] = array(1005=>'First array is numeric
& second one is string');
return false;
}
}

Page 336 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

else
{
$this->error = 1;
$this->debug['errinfo'] = array(1004=>'The parameter count of data
and label should be same');
return false;
}
}
else
{
$this->error = 1;
$this->debug['errinfo'] = array(1003=>'The spliter should be astricks only');
return false;
}
}
else
{
$this->error = 1;
$this->debug['errinfo'] = array(1002=>'Array should not be empty');
return false;
}
}
else
{
$this->error = 1;
$this->debug['errinfo'] = array(1001=>'Array element not found');
return false;
}
}

/**
* This function allocate a color for an image.
*
* @return image colorHex
*/

private function colorHex($img, $HexColorString)


{
$R = hexdec(substr($HexColorString, 0, 2));
$G = hexdec(substr($HexColorString, 2, 2));
$B = hexdec(substr($HexColorString, 4, 2));
return imagecolorallocate($img, $R, $G, $B);
}

/**
* This function allocate a color for an image and dark shadow.
*
* @return image colorHexshadow
*/
private function colorHexshadow($img, $HexColorString, $mork)
{
$R = hexdec(substr($HexColorString, 0, 2));
$G = hexdec(substr($HexColorString, 2, 2));
$B = hexdec(substr($HexColorString, 4, 2));
if ($mork)
{
($R > 99) ? $R -= 100 : $R = 0;
($G > 99) ? $G -= 100 : $G = 0;
($B > 99) ? $B -= 100 : $B = 0;
}
else
{
($R < 220) ? $R += 35 : $R = 255;
($G < 220) ? $G += 35 : $G = 255;
($B < 220) ? $B += 35 : $B = 255;
}

Page 337 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

return imagecolorallocate($img, $R, $G, $B);

/**
* This function create the jpeg image and store to images folder.
*
* @return bool result
*/
private function outputImage($img)
{
header("Content-type: image/jpeg");
return imagejpeg($img,NULL,100);
}

}
?>
Correct text with abbreviations used by people in chats
<?php
/**
* ChatGrammarCorrector
*
* This class contains functions used to correct text with abbreviations used by people in chats.
*
* @package Lib_ChatGrammarCorrector
* @category Library
* @version 1.0
*/
// ------------------------------------------------------------------------
class Lib_ChatGrammarCorrector
{
/**
* Stores function type's name
*
* @var string $type
*/
private $type;
/**
* Stores the output
*
* @var string $result
*/
public $result;
/**
* Stores inputs
*
* @var string $data
*/
private $data ;
/**
* Stores correct words
*
* @var string $changes
*/
private $changes = array(
"omg" => "OMG",
"wtf" => "wtfreak",
"ur" => "you're",
"youre" => "you're",
"itz" => "it's",
"its" => "it's",
"im" => "I'm",
"ive" => "I've",
"cant" => "can't",
"isnt" => "isn't",

Page 338 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

"arent" => "aren't",


"wasnt" => "wasn't",
"werent" => "weren't",
"havent" => "haven't",
"hasnt" => "hasn't",
"hadnt" => "hadn't",
"wont" => "won't",
"wouldnt" => "wouldn't",
"dont" => "don't",
"doesnt" => "doesn't",
"didnt" => "didn't",
"couldnt" => "couldn't",
"shouldnt" => "shouldn't",
"mightnt" => "mightn't",
"mustnt" => "mustn't",
"thats" => "that is",
"b4" => "before",
"btw" => "by the way",
"co(s|z)" => "'cause",
"r" => "are",
"u" => "you",
"2nite" => "tonight",
"innit" => "isn't",
"awsum" => "awesome",
"rite" => "right",
"i" => "I",
"dun" => "don't",
"thnk" => "think",
"gud" => "good",
"dat" => "that",
"pl(z|s)" => "please",
"som" => "some",
"avi?" => "avatar",
"sig" => "signature",
"ty" => "thank you",
"oic" => "oh I see",
"srry" => "Sorry",
"ya" => "you're",
"k?noe" => "know",
"lyke?" => "like",
"pic(s?)" => "picture\1",
"rite" => "right",
"diz" => "this",
"d8" => "date",
"duz" => "does",
"eva" => "ever",
"eve?ry1" => "everyone",
"ne1" => "everyone",
"some?1" => "someone",
"sum1" => "someone",
"sup" => "what's up",
"hafta" => "have to",
"hav" => "have",
"idk" => "I don't know",
"wryte" => "write",
"b" => "be",
"tlk" => "talk",
"ty" => "thank you",
"giv" => "give",
"dunno" => "don't know",
"w/o" => "without",
"luv" => "love",
"wernt" => "weren't",
"l8a" => "later",
"oso" => "also",
"n" => "and",

Page 339 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

"den" => "then",


"wuz" => "was",
"ne" => "any",
"neway(s?)" => "anyway\1",
"newayz" => "anyways",
"thx" => "thanks",
"nvmnd" => "nevermind",
"nvm" => "nevermind",
"lyke" => "like",
"srsly" => "seriously",
"wrk" => "work",
"liek" => "like",
"dis" => "this",
"lemme" => "let me",
"amirite\?*" => "am I right?",
"y" => "why",
"wut" => "what",
"gonna" => "going to",
"any1" => "anyone",
"thurr?" => "there",
"wud" => "would",
"im?ma" => "I'm going to",
"laterz" => "later",
"mr(s)." => "Mr\1.",
"(s)hes" => "\1he's",
"cu(z|s)" => "'cause",
"gr8" => "great",
);

/**
* Constructs a Lib_ChatGrammarCorrector object with given parameters
* also it will invoke grammar correction process
*
* @param string $type
* @param string $data
* @return Lib_ChatGrammarCorrector
*/

public function Lib_ChatGrammarCorrector($type,$data)


{
$this->type = $type;
$this->data = $data;

if($this->isValidCall())
{
if(strtolower($type)=='grammer')
$this->correct();
}
}

/**
* Check whether the function call is valid or not
*
* @return bool
*/
private function isValidCall()
{
if(strtolower($this->type)!='grammer')
{
echo '<b>Component Error!<b> Invalid argument <i>type</i> - grammer expected';
exit();
}
else if(empty($this->data))
{
echo '<b>Component Error!<b> Invalid argument <i>data</i> - data expected';
exit();

Page 340 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

}
return true;
}

/**
* This function replaces repeated punctuation.
*
* @return string $msg
*/

private function replaceRepeatedPunctuation($msg)


{
$msg = preg_replace("#!!+#", "!", $msg);
$msg = preg_replace("#\?\?+#", "?", $msg);
$msg = preg_replace("#![\?!]+#", "!?", $msg);
$msg = preg_replace("#\?[\?!]+#", "!?", $msg);
$msg = preg_replace("#\.\.+#", "...", $msg);

return $msg;
}

/**
* This function correct the text.
*
* @return string $result
*/

private function correct()


{
$msg=$this->data;
foreach ($this->changes as $k => $v)
{
$msg = preg_replace("#\b$k\b#i", $v, $msg);
}

$msg = $this->replaceRepeatedPunctuation($msg);

$words = explode(" ", $msg);


$new = array();

$start = true;
foreach ($words as $w)
{
if (strtolower($w) != $w)
{
}
else if (strtoupper($w) == $w)
{
}
else
{
if ($w == "i")
{
$w = "I";
}
else if (preg_match("#o\.o|o\-o#i", $w))
{
}
else if (preg_match("#^i'#", $w))
{
$w = strtoupper(substr($w, 0, 1)) . strtolower(substr($w, 1));
}
else if ($start)
{
$w = strtoupper(substr($w, 0, 1)) . strtolower(substr($w, 1));
}

Page 341 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

else
{
$w = strtolower($w);
}
}

$start = preg_match("#(\.|!|\?)$#", trim($w));

$new[] = $w;
}

$msg = implode(" ", $new);


$this->result=$msg;
return true;
}

}
?>
Based Encryption and Decryption Program
<?php
class encryptdecrypt {
var $keys;

function crypt_key($ckey){
$this->keys = array();

$c_key = base64_encode(sha1(md5($ckey)));
$c_key = substr($c_key, 0, round(ord($ckey{0})/5));

$c2_key = base64_encode(md5(sha1($ckey)));
$last = strlen($ckey) - 1;
$c2_key = substr($c2_key, 1, round(ord($ckey{$last})/7));

$c3_key = base64_encode(sha1(md5($c_key).md5($c2_key)));
$mid = round($last/2);
$c3_key = substr($c3_key, 1, round(ord($ckey{$mid})/9));

$c_key = $c_key.$c2_key.$c3_key;
$c_key = base64_encode($c_key);

for($i = 0; $i < strlen($c_key); $i++){


$this->keys[] = $c_key[$i];
}
}

function encrypt($string){
$string = base64_encode($string);
$keys = $this->keys;
for($i = 0; $i < strlen($string); $i++){
$id = $i % count($keys);
$ord = ord($string{$i});
$ord = $ord OR ord($keys[$id]);
$id++;
$ord = $ord AND ord($keys[$id]);
$id++;
$ord = $ord XOR ord($keys[$id]);
$id++;
$ord = $ord + ord($keys[$id]);
$string{$i} = chr($ord);
}
return base64_encode($string);
}

function decrypt($string){
$string = base64_decode($string);
$keys = $this->keys;

Page 342 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

for($i = 0; $i < strlen($string); $i++){


$id = $i % count($keys);
$ord = ord($string{$i});
$ord = $ord XOR ord($keys[$id]);
$id++;
$ord = $ord AND ord($keys[$id]);
$id++;
$ord = $ord OR ord($keys[$id]);
$id++;
$ord = $ord - ord($keys[$id]);
$string{$i} = chr($ord);
}
return base64_decode($string);
}
}
$crypt = new encryptdecrypt; //sets up an instance of the class
$crypt->crypt_key('test_key'); //assigns an encryption key to the instance
echo $encrypted = $crypt->encrypt('ramasubbu'); //encrypts the data using the key
echo "<br />";
echo $decrypted = $crypt->decrypt($encrypted); //decrypts the data using the key
?>
Shows the Astronomy picture of today. Fetched from the NASA website.
<?php
/**
* DailyAstroImage
*
* This class contains functions shows the Astronomy picture of today. Fetched from the nasa website.
*
* @package Lib_DailyAstroImage
* @category Library

* @version 1.0
*/
// ------------------------------------------------------------------------
class Lib_DailyAstroImage
{
/**
* Stores function type's name
*
* @var string $type
*/
private $type;
/**
* Flag for error
*
* @var boolean $error
*/
private $error;
/**
* Stores error numbers and description
*
* @var array $debug
*/
public $debug = array();
/**
* Stores the output
*
* @var bool $result
*/
public $result;
/**
* image width
*
* @var integer $imgWidth
*/

Page 343 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

private $imgWidth;

/**
* Constructs a Lib_DailyAstroImage object with given parameters
* also it will invoke daily astronomy image process
*
* @param string $type
* @param integer $imgWidth
* @return Lib_DailyAstroImage
*/

public function Lib_DailyAstroImage($type,$imgWidth = 400)


{
$this->type = $type;
$this->imgWidth = $imgWidth;

if($this->isValidCall())
{
if(strtolower($type)=='astro')
$this->showImg();
}
}

/**
* Check whether the function call is valid or not
*
* @return bool
*/
private function isValidCall()
{
if(strtolower($this->type)!='astro')
{
echo '<b>Component Error!<b> Invalid argument <i>type</i> - astro expected';
exit();
}
else if(empty($this->imgWidth))
{
echo '<b>Component Error!<b> Invalid argument <i>imgWidth</i> - image width expected';
exit();
}
else if(!is_numeric($this->imgWidth))
{
echo '<b>Component Error!<b> Invalid argument <i>imgWidth</i> - image width must be
numeric';
exit();
}
return true;
}

/**
* This function show the astronomy image
*
* @return image
*/

private function showImg()


{
$out=$this->astroPicture();
$this->result= "<img src=\"".$out."\" width=".$this->imgWidth.">";
return true;
}

/**
* This function create astronomy image
*
* @return image

Page 344 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

*/

private function astroPicture($pic="")


{
if (empty($pic))
$pic = "http://antwrp.gsfc.nasa.gov/apod/astropix.html";
$fd = fopen ($pic, "r");
while (!feof ($fd))
{
$tmp = fgets($fd, 4096);
if (eregi("<a href=\"image", $tmp))
{
$astropicture = $tmp;
break;
}
}
fclose ($fd);
$substr = stristr($astropicture,'<img');
if ($substr)
$astropicture = str_replace($substr,'',$astropicture);
$astropicture = str_replace('">',"",$astropicture);
$astropicture = str_replace('<a href="','http://antwrp.gsfc.nasa.gov/apod/',$astropicture);
$astropicture = str_replace('<A href=','http://antwrp.gsfc.nasa.gov/apod/',$astropicture);
$astropicture = str_replace("\n","",$astropicture);
$astropicture = str_replace("\r","",$astropicture);
$astropicture = str_replace('"',"",$astropicture);
$substr2 = stristr($astropicture,'>');
if ($substr2)
$astropicture = str_replace($substr2,'',$astropicture);
unset ($substr);
unset ($substr2);
return $astropicture;
}

}
?>
Daily Show the Artoon from www.adressa.no site
<?php
/**
* DailyCartoon
*
* This class contains functions show daily cartoon from www.adressa.no site.
*
* @package Lib_DailyCartoon
* @category Library

* @version 1.0
*/
// ------------------------------------------------------------------------
class Lib_DailyCartoon
{
/**
* Stores function type's name
*
* @var string $type
*/
private $type;
/**
* Flag for error
*
* @var boolean $error
*/
private $error;
/**
* Stores error numbers and description

Page 345 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

*
* @var array $debug
*/
public $debug = array();
/**
* Stores the output
*
* @var string $result
*/
public $result;

/**
* Constructs a Lib_DailyCartoon object with given parameters
* also it will invoke daily cartoon process
*
* @param String $type
* @return Lib_DailyCartoon
*/

public function Lib_DailyCartoon($type)


{
$this->type = $type;

if($this->isValidCall())
{
if(strtolower($type)=='cartoon')
$this->callCartoon();
}

/**
* Check whether the function call is valid or not
*
* @return bool
*/

private function isValidCall()


{
if(strtolower($this->type)!='cartoon')
{
echo '<b>Component Error!<b> Invalid argument <i>type</i> - cartoon expected';
exit();
}
return true;
}
/**
* select the date
*
* @return string
*/

private function selectDate($date,$CARTOONS)


{
$today = date("Y-m-d") ;
$todaySec = date("U") ;

if (!$date)
{
$date = date("Y-m-d") ;
$prevday = date("Y-m-d",strtotime("yesterday")) ;
$nextday = date("Y-m-d",strtotime("tomorrow")) ;
}
foreach ($CARTOONS as $index => $cartoon)
$CARTOONS[$index]['date'] = date($cartoon['dateformat'],strtotime($date)) ;

Page 346 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

$prevday = date("Y-m-d",mktime (0,0,0,substr($date, 5, 2),substr($date, 8, 2)-1,substr($date, 0, 4))) ;


$nextday = date("Y-m-d",mktime (0,0,0,substr($date, 5, 2),substr($date, 8, 2)+1,substr($date, 0, 4))) ;
$nextdaySec = date("U",mktime (0,0,0,substr($date, 5, 2),substr($date, 8, 2)+1,substr($date, 0, 4))) ;
$this->cartoons($date,$CARTOONS);
}

/**
* select the cartoon
*
* @return string
*/

private function cartoons($date,$CARTOONS)


{
$template = '<table style="width:95%; border:0;"><tr><td style="text-
align:center">{{{CARTOON}}}</td></tr></table><br />' ;
foreach ($CARTOONS as $index => $cartoon)
{
$done = 0 ;
$cartoon_text = $template ;
if ($cartoon['cache'])
{
$dh = opendir("cache") ;
$cache_match = "{$cartoon['name']}__".$date."__" ;
while ($file = readdir($dh))
{
if (strstr($file,$cache_match) !== false)
{
$cartoon_file = "cache/".$file ;
$cartoon_text =
str_replace("{{{CARTOON}}}",$cartoon['cartoon'],$cartoon_text) ;
$cartoon_text =
str_replace("{{{FETCH}}}",$cartoon_file,$cartoon_text) ;
$done = 1 ;
break ;
}
}
closedir($dh) ;
}
if (!$done)
{
$url = str_replace("{{{DATE}}}",$cartoon['date'],$cartoon['url']) ;

$fopen_check = ini_get('allow_url_fopen') ;
//$fopen_check = 'Off' ;
//If allow_url_fopen
if ($fopen_check == 'On' || $fopen_check == 1 || $fopen_check == 'true')
{
$fh = @fopen($url,"r") ;
//If not allow_url_fopen - use curl
}
else
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$fh = curl_exec($ch);
curl_close($ch);
}

if ($fh)
{
//If allow_url_fopen
if($fopen_check)
{

Page 347 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

while (!feof($fh))
{
$tmp .= fread($fh, 2048) ;
}
fclose ($fh) ;
$bytes = strlen($tmp) ;
// draw image here
preg_match($cartoon['regexp'],$tmp,$matches) ;
//If not allow_url_fopen
}
else
{
$bytes = strlen($fh) ;
// draw image here
preg_match($cartoon['regexp'],$fh,$matches) ;
}
if ($matches[0])
{
$cartoon_file = $cartoon['fetch'] ;
$matchindex = 0 ;

for($i=1; $i < count($matches); $i++)


{
$cartoon_file =
str_replace("{{{".$i."}}}",$matches[$i],$cartoon_file) ;
}
if ($cartoon['cache'])
{
$bits = explode("/",$cartoon_file) ;
$cartoon_cachefile = $bits[count($bits)-1] ; // get just the
last filename portion
$cartoon_cachefile = str_replace(".","_",$cartoon['name']) .
"__" . $date . "__" . $cartoon_cachefile ;
$cartoon_cachefile = str_replace(" ","_",$cartoon_cachefile) ;
$cartoon_cachefile = str_replace("\\","",$cartoon_cachefile) ;
$cartoon_cachefile = str_replace(":","",$cartoon_cachefile) ;
$cartoon_cachefile = str_replace("/","",$cartoon_cachefile) ;
// this will create a filename like "Daily_Dilbert__2006-08-
24__dilbert20060824.gif"
if (file_exists("cache") &&
file_exists("cache/".$cartoon_cachefile))
{
$cartoon_file = "cache/".$cartoon_cachefile ;
}
elseif (file_exists("cache"))
{
// save a copy of the cartoon
if ($fopen_check == 'On' || $fopen_check == 1 ||
$fopen_check == 'true')
{
//If allow_url_fopen
$fh_cartoon = fopen($cartoon_file,"rb") ;
//If not allow_url_fopen - use curl
}
else
{
$ch2 = curl_init();
curl_setopt($ch2, CURLOPT_URL,
$cartoon_file);
curl_setopt($ch2, CURLOPT_HEADER, 0);
curl_setopt($ch2,
CURLOPT_RETURNTRANSFER, 1);
$fh_cartoon = curl_exec($ch2);
curl_close($ch2);
}
if ($fh_cartoon)

Page 348 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

{
$cartoon_binary = '' ;
$byte_count = 0 ;
//If allow_url_fopen
if($fopen_check)
{
while (!feof($fh_cartoon))
{
$cartoon_binary .=
@fread($fh_cartoon,1) ;
$byte_count++ ;
}
fclose($fh_cartoon) ;
//If not allow_url_fopen
}
else
{
$cartoon_binary .= $fh_cartoon;
}
$fh_cartoon =
@fopen("cache/".$cartoon_cachefile,"wb") ;
if ($fh_cartoon)
{
//If allow_url_fopen
if ($fopen_check)
{

fwrite($fh_cartoon,$cartoon_binary,$byte_count) ;
//If not allow_url_fopen
}
else
{

fwrite($fh_cartoon,$cartoon_binary) ;
}
fclose($fh_cartoon) ;
}
$cartoon_file = "cache/".$cartoon_cachefile
;
}
}
}
$cartoon_text =
str_replace("{{{CARTOON}}}",$cartoon['cartoon'],$cartoon_text) ;
$cartoon_text =
str_replace("{{{FETCH}}}",$cartoon_file,$cartoon_text) ;
// reapply the {{{#}}} filters, if any
for($i=1; $i < count($matches); $i++)
{
$cartoon_text =
str_replace("{{{".$i."}}}",$matches[$i],$cartoon_text) ;
}

}
else
{
// preg_match didn't find any matches
$cartoon_text =
str_replace("{{{CARTOON}}}",(isset($cartoon['404']) ? '<img src="404comics/'.$cartoon['404'].'" border="0" /><br
/>No strip for this date.' : " No strip for this date."),$cartoon_text) ;
}
}
else
{
// couldn't open page, either fopen isn't allowed to open url's or the page is
404, etc

Page 349 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

$cartoon_text = str_replace("{{{CARTOON}}}",(isset($cartoon['404']) ?
'<img src="404comics/'.$cartoon['404'].'" border="0" alt="No Image(404)" title="strip does not exist (404)" /><br
/>Image (404 not found)' : "Could not open <a href=\"$url\">$url</a>, 404 Not found."),$cartoon_text) ;
}
}
$cartoon_text = str_replace("{{{SITE}}}",$cartoon['site'],$cartoon_text) ;

$this->result= "\n$cartoon_text</p>\n" ;
return true;
}
}
/**
* define the cartoon array
*
* @return string
*/

private function callCartoon()


{
$index = 0 ;

$CARTOONS = Array() ;
$CARTOONS[$index]['name'] = "Nemi";
$CARTOONS[$index]['site'] =
"http://www.adressa.no/index.jsp?service=tegneserier&stripe=Nemi&date=today" ;
$CARTOONS[$index]['url'] =
'http://www.adressa.no/index.jsp?service=tegneserier&stripe=Nemi&date={{{DATE}}}' ;
$CARTOONS[$index]['dateformat'] = "dmy" ;
$CARTOONS[$index]['regexp'] = '/http:\/\/www.adressa.no\/template\/ver1-
0\/gfx\/tegneserier\/Nemi\/nemi_([0-9]*).gif/i' ;
$CARTOONS[$index]['fetch'] = 'http://www.adressa.no/template/ver1-
0/gfx/tegneserier/Nemi/nemi_{{{1}}}.gif' ;
$CARTOONS[$index]['cartoon'] = '<img src="{{{FETCH}}}" alt="Nemi" title="Nemi av Lise Myhre" />' ;
$CARTOONS[$index]['cache'] = 1 ;
$CARTOONS[$index]['404'] = '404AdamAtHome.gif' ;
// attempt to make the cache folder and chmod 777 if it doesn't already exist
// we'll use the @ prefix to supress any errors
@mkdir("cache") ;
@chmod(0777,"cache") ;
$date = $HTTP_GET_VARS['date'] ;
$this->selectDate($date,$CARTOONS);
}

}
?>
Daily retrieve joke from jokes2go site
<?php
/**
* DailyJoke
*
* This class contains functions retrieve daily joke from jokes2go site.
*
* @package Lib_DailyJoke
* @category Library

* @version 1.0
*/
// ------------------------------------------------------------------------
class Lib_DailyJoke
{
/**
* Stores function type's name
*
* @var string $type
*/

Page 350 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

private $type;
/**
* Flag for error
*
* @var boolean $error
*/
private $error;
/**
* Stores error numbers and description
*
* @var array $debug
*/
public $debug = array();
/**
* Stores the output
*
* @var bool $result
*/
public $result;

/**
* Constructs a Lib_DailyJoke object with given parameters
* also it will invoke joke process
*
* @param string $type
* @return Lib_DailyJoke
*/

public function Lib_DailyJoke($type)


{
$this->type = $type;

if($this->isValidCall())
{
if(strtolower($type)=='joke')
$this->getJoke();
}
}

/**
* Check whether the function call is valid or not
*
* @return bool
*/

private function isValidCall()


{
$count=strlen($this->number);
if(strtolower($this->type)!='joke')
{
echo '<b>Component Error!<b> Invalid argument <i>type</i> - joke expected';
exit();
}
return true;
}

/**
* get joke from jokes2go site
*
* @return string
*/

private function getJoke()

Page 351 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

{
$link="http://www.jokes2go.com/jtoday.html";
$content=file_get_contents($link);
if(strpos($content,"<pre>")!==false)
{
$position1=strpos($content,"<pre>")+5;
$position2=strpos($content,'<',$position1);
$joke=substr($content,$position1,$position2-$position1);
}
else
{
$joke="Not found";
}
$this->result=$joke;
return true;
}

}
?>
Download images through Google
<?php
/**
* DownloadImage
*
* This class contains functions for download images through google.
*
* @package Lib_DownloadImage
* @category Library

* @version 1.0
*/
// ------------------------------------------------------------------------
class Lib_DownloadImage
{
/**
* Stores function type's name
*
* @var string $type
*/
private $type;
/**
* Stores the output
*
* @var string $result
*/
public $result;
/**
* Stores error numbers and description
*
* @var array $debug
*/
public $debug = array();
/**
* image name
*
* @var integer $imagesOf
*/
private $imagesOf;
/**
* number of images download
*
* @var integer $numberOfImages
*/
private $numberOfImages ;
/**

Page 352 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

* size limit
*
* @var integer $sizeLimit
*/
private $sizeLimit;
/**
* destination path
*
* @var string $destinationPath
*/
private $destinationPath;
/**
* google url array
*
* @var array $googleUrlArray
*/
private $googleUrlArray=array();
/**
* Constructs a Lib_DownloadImage object with given parameters
* also it will invoke image downloaded process
*
* @param string $type
* @param integer $imagesOf
* @param integer $numberOfImages
* @param integer $sizeLimit
* @param string $destinationPath
* @return Lib_DownloadImage
*/

public function Lib_DownloadImage($type,$imagesOf, $numberOfImages, $sizeLimit,$destinationPath)


{
$this->type = $type;
$this->imagesOf = $imagesOf;
$this->numberOfImages = $numberOfImages;
$this->sizeLimit = $sizeLimit;
$this->destinationPath = $destinationPath;

if($this->isValidCall())
{
if(strtolower($type)=='download')
$this->download();

}
}

/**
* Check whether the function call is valid or not
*
* @return bool
*/
private function isValidCall()
{
if(strtolower($this->type)!='download')
{
echo '<b>Component Error!<b> Invalid argument <i>type</i> - download expected';
exit();
}
else if(empty($this->imagesOf))
{
echo '<b>Component Error!<b> Invalid argument <i>imagesOf</i> - images name expectd';
exit();
}
else if(empty($this->numberOfImages))
{
echo '<b>Component Error!<b> Invalid argument <i>numberOfImages</i> - number of
images expectd';

Page 353 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

exit();
}
else if(!is_numeric($this->numberOfImages))
{
echo '<b>Component Error!<b> Invalid argument <i>numberOfImages</i> - number of
images must be numeric';
exit();
}
else if(empty($this->sizeLimit))
{
echo '<b>Component Error!<b> Invalid argument <i>sizeLimit</i> - size limit expectd';
exit();
}
else if(!is_numeric($this->sizeLimit))
{
echo '<b>Component Error!<b> Invalid argument <i>sizeLimit</i> - size limit must be
numeric';
exit();
}
else if(!file_exists($this->destinationPath))
{
echo '<b>Component Error!<b> Path not found <i>'.$this->destinationPath.'</i> - destination
path not found';
exit();
}
else if(!is_writable($this->destinationPath))
{
echo '<b>Component Error!<b> Access Denied <i>'.$this->destinationPath.'</i> - destination
path not writable';
exit();
}
return true;
}

/**
* call all sub functions
*
* @return bool
*/

private function download()


{
$this->googleUrlArray=$this->createGoogleUrl();
$this->downloadImages();
$this->result="true";
return true;
}

/**
* create a list of google image urls
*
* @return image
*/

private function createGoogleUrl()


{
$imagesOf = $this->imagesOf;
$numberOfImages = $this->numberOfImages+20;
$numberOfPages = ($numberOfImages/20)+1;
$j=0;
for($i=0; $i<$numberOfPages; $i++ )
{
$returnArray[] =
"http://images.google.co.in/images?q=".rawurlencode($imagesOf)."&hl=en&lr=&start=".$j."&sa=N&gbv=1";

$j += 20;

Page 354 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

}
return $returnArray;
}

/**
* download images from google
*
*/

private function downloadImages()


{
$imgUrlArray=$this->getImageUrls($urlArray);
$dir=$this->imagesOf;
$img=$this->destinationPath;
@mkdir($img."/".$dir,0777);
for($i=0; $i<count($imgUrlArray); $i++)
{
$imageName = basename($imgUrlArray[$i]);
$info = @getimagesize($imgUrlArray[$i]);
if(trim($this->sizeLimit) != "" && $this->sizeLimit > 0)
{
if (count($info) > 0 && $info[0] >= $this->sizeLimit)
{
if(trim($imageName) != '' )
{

@copy($imgUrlArray[$i], $img."/".$dir."/".$imageName);
}
}
}
else
{
if(trim($imageName) != '' )
{

@copy($imgUrlArray[$i], $img."/".$dir."/".$imageName);
}
}
}
}

/**
* return paths of all images to be downloaded
*
* @return array
*/

private function getImageUrls()


{
$urlArray=$this->googleUrlArray;
$returnArray=array();
$returnArray1=array();
$return=array();
for ($j=0;$j<count($urlArray);$j++)
{
$url=trim($urlArray[$j]);
$str=$this->getHtmlCode($url);
$pattern='/<img src=(.*)\<\/a>/Us';
preg_match_all($pattern, $str, $returnArray, PREG_GREP_INVERT);
$returnArray1=$returnArray[1];
$count=count($returnArray1);
for ($i=1;$i<$count;$i++)
{
$str1=trim(strip_tags($returnArray[1][$i]));
$pos1=strrpos($str1,"http://");
$pos2=strpos($str1," width");

Page 355 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

$link=trim(substr($str1,$pos1,$pos2-$pos1));
$return[]=$link;
}
}
return $return;
}

/**
* get source code of a url
*
* @return string
*/

private function getHtmlCode($url)


{
$returnStr="";
$fp=fopen($url, "r");
while (!feof($fp))
{
$returnStr.=fgetc($fp);
}
fclose($fp);
return $returnStr;
}

}
?>
Work with Flickr photos
<?php
/**
* Flickr
*
* This class contains functions to work with Flickr photos.
*
* @package Lib_Flickr
* @category Library

* @version 1.0
*/
// ------------------------------------------------------------------------
class Lib_Flickr
{
/**
* Stores function type's name
*
* @var string $type
*/
private $type;
/**
* Stores the output
*
* @var string $result
*/
public $result;
/**
* Input tags
*
* @var string $category
*/
private $category;
/**
* Constructs a Lib_Flickr object with given parameters
* also it will invoke Flickr Photo process
*
* @param string $type

Page 356 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

* @param string $category


* @return Lib_Flickr
*/
public function Lib_Flickr($type,$category)
{
$this->type = $type;
$this->category = $category;
if($this->isValidCall())
{
if(strtolower($type)=='flickr')
$this->feedRead();

}
}
/**
* Check whether the function call is valid or not
*
* @return bool
*/
private function isValidCall()
{
if(strtolower($this->type)!='flickr')
{
echo '<b>Component Error!<b> Invalid argument <i>type</i> - flickr';
exit();
}
else if(empty($this->category))
{
echo '<b>Component Error!<b> Invalid argument <i>category</i> - category expected';
exit();
}
return true;
}
/**
* This function get the flickr photo's list depend upon the given category ex:sports
*
* @return string $result
*/
private function feedRead()
{
$category=str_replace(" ","%20",$this->category);
if($category!='')

$link='http://api.flickr.com/services/feeds/photos_public.gne?tags='.$category.'&format=rss_200%22';

else
return "Invalid Category/Tag";
$xmlstr=simplexml_load_file($link,'SimpleXMLElement', LIBXML_NOCDATA);
$res=$this->feedConversion($xmlstr);
$this->result=$res;
return true;
}
/**
* This function split the each category feed
*
* @return string $res
*/
function feedConversion($feed)
{
foreach($feed->entry as $item)
{
$re['id']=(string)$item->id;
$re['published']=(string)$item->published;
$re['updated']=(string)$item->updated;
$re['title']=(string)$item->title;
$re['content']=(string)$item->content;

Page 357 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

$re['author']=(string)$item->author->name;
$re['author_uri']=(string)$item->author->uri;
$res[]=$re;
}
if(isset($res))
return $res;
else
return "No Results";
}
}
?>
Get geographical location of the IP address using web service of http://www.geoplugin.com
<?php
/**
* GeoIP
*
* This class contains functions get geographical location of the IP address using web service of
http://www.geoplugin.com.
*
* @package Lib_GeoIP
* @category Library

* @version 1.0
*/
// ------------------------------------------------------------------------
class Lib_GeoIP
{
/**
* Stores function type's name
*
* @var string $type
*/
private $type;
/**
* Flag for error
*
* @var boolean $error
*/
private $error;
/**
* Stores error numbers and description
*
* @var array $debug
*/
public $debug = array();
/**
* Stores the output
*
* @var bool $result
*/
public $result;
/**
* the geoPlugin server
*
* @var string $host
*/
private $host = 'http://www.geoplugin.net/php.gp?ip={IP}';
/**
* ip address
*
* @var string $ip
*/
private $ip;
/**
* Constructs a Lib_GeoIP object with given parameters

Page 358 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

* also it will invoke geoip process


*
* @param string $type
* @param string $ip
* @return Lib_GeoIP
*/
public function Lib_GeoIP($type,$ip)
{
$this->type = $type;
$this->ip = $ip;
if($this->isValidCall())
{
if(strtolower($type)=='geoip')
$this->locate();
}
}
/**
* Check whether the function call is valid or not
*
* @return bool
*/
private function isValidCall()
{
if(strtolower($this->type)!='geoip')
{
echo '<b>Component Error!<b> Invalid argument <i>type</i> - geoip expected';
exit();
}
else if(empty($this->ip))
{
echo '<b>Component Error!<b> Invalid argument <i>ip</i> - ip address expected';
exit();
}
return true;
}
/**
* This function check is valid ip
*
* @return bool
*/
private function isIpAddress($value)
{
if(preg_match("/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/",$value))
{
$parts=explode(".",$value);
foreach($parts as $ip_parts)
{
if(intval($ip_parts)>255 || intval($ip_parts)<0)
return false;
}
return true;
}
else
return false;
}
/**
* This function locate the region and give output
*
* @return string
*/
private function locate()
{
if($this->isIpAddress($this->ip))
{
global $_SERVER;
$host = str_replace( '{IP}', $this->ip, $this->host );

Page 359 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

$host = str_replace( '{CURRENCY}', $this->currency, $host );


$data = array();
$response = $this->fetch($host);
$data = unserialize($response);
$city = $data['geoplugin_city'];
$region = $data['geoplugin_region'];
$areaCode = $data['geoplugin_areaCode'];
$dmaCode = $data['geoplugin_dmaCode'];
$countryCode = $data['geoplugin_countryCode'];
$countryName = $data['geoplugin_countryName'];
$continentCode = $data['geoplugin_continentCode'];
$latitude = $data['geoplugin_latitude'];
$longitude = $data['geoplugin_longitude'];
$currencyCode = $data['geoplugin_currencyCode'];
$currencySymbol = $data['geoplugin_currencySymbol'];
$currencyConverter = $data['geoplugin_currencyConverter'];
$out= "Geolocation results for {$this->ip}: <br />\n".
"City: {$city} <br />\n".
"Region: {$region} <br />\n".
"Area Code: {$areaCode} <br />\n".
"DMA Code: {$dmaCode} <br />\n".
"Country Name: {$countryName} <br />\n".
"Country Code: {$countryCode} <br />\n".
"Longitude: {$longitude} <br />\n".
"Latitude: {$latitude} <br />\n".
"Currency Code: {$currencyCode} <br />\n".
"Currency Symbol: {$currencySymbol} <br />\n".
"Exchange Rate: {$currencyConverter} <br />\n";
$this->result=$out;
return true;
}
else
{
$this->error = 1;
$this->debug['errinfo'] = array(1001=>'valid ip expected');
return false;
}
}
/**
* This function call curl function
*
* @return string
*/
private function fetch($host)
{
if ( function_exists('curl_init') )
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $host);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT, 'geoPlugin PHP Class v1.0');
$response = curl_exec($ch);
curl_close ($ch);
}
else if ( ini_get('allow_url_fopen') )
{
$response = file_get_contents($host, 'r');
}
else
{
$this->error = 1;
$this->debug['errinfo'] = array(1002=>'geoPlugin class Error: Cannot retrieve data. Either
compile PHP with cURL support or enable allow_url_fopen in php.ini');
return false;
}
return $response;

Page 360 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

}
}
?>
Convert Gif animation file into multiple images
<?php
/**
* GIFDecoder
*
* This class contains functions convert Gif animation file into multiple images.
*
* @package Lib_GIFDecoder
* @category Library

* @version 1.0
*/
// ------------------------------------------------------------------------
Class Lib_GIFDecoder
{
/**
* Stores function type's name
*
* @var string $type
*/
private $type;
/**
* Flag for error
*
* @var boolean $error
*/
private $error;
/**
* Stores error numbers and description
*
* @var array $debug
*/
public $debug = array();
/**
* Stores the output
*
* @var string $result
*/
public $result;
/**
* Gif image file name
*
* @var string $filename
*/
private $filename;
/**
* image designation directory name
*
* @var string $directory
*/
private $directory;
/**
* gif buffer array
*
* @var array $gifBuffer
*/
private $gifBuffer = Array ( );
/**
* gif file array
*
* @var array $gifArrays
*/

Page 361 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

private $gifArrays = Array ( );


/**
* gif delay array
*
* @var array $gifDelays
*/
private $gifDelays = Array ( );
/**
* gif stream
*
* @var string $gifStream
*/
private $gifStream = "";
/**
* gif string
*
* @var string $gifString
*/
private $gifString = "";
/**
* buffer seek
*
* @var integer $gifBseek
*/
private $gifBseek = 0;
/**
* gif screen array
*
* @var array $gifScreen
*/
private $gifScreen = Array ( );
/**
* gif global array
*
* @var array $gifGlobal
*/
private $gifGlobal = Array ( );
/**
* gif sorted
*
* @var integer $gifSorted
*/
private $gifSorted;
/**
* gif color
*
* @var integer $gifColorS
*/
private $gifColorS;
/**
* gif color
*
* @var integer $gifColorC
*/
private $gifColorC;
/**
* gif color
*
* @var integer $gifColorF
*/
private $gifColorF;
/**
* Constructs a Lib_GIFDecoder object with given parameters
* also it will invoke gif decoder process
*
* @param string $type

Page 362 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

* @param string $filename


* @param string $directory
* @return Lib_GIFDecoder
*/
public function Lib_GIFDecoder ($type,$filename,$directory)
{
$this->type = $type;
$this->filename = $filename;
$this->directory = $directory;
if($this->isValidCall())
{
if(strtolower($type)=='gifdecode')
$this->callGifDecoder();
}
}
/**
* Check whether the function call is valid or not
*
* @return bool
*/
private function isValidCall()
{
if(strtolower($this->type)!='gifdecode')
{
echo '<b>Component Error!<b> Invalid argument <i>type</i> - gifdecode expected';
exit();
}
elseif(empty($this->filename))
{
echo '<b>Component Error!<b> Invalid argument data type <i>filename</i> - file name
expected';
exit();
}
elseif(!file_exists($this->filename))
{
echo '<b>Component Error!<b> Invalid argument data type <i>'.$this->filename.'</i> - file
not found';
exit();
}
elseif(empty($this->directory))
{
echo '<b>Component Error!<b> Invalid argument data type <i>directory</i> - directory name
expected';
exit();
}
elseif(!file_exists($this->directory))
{
echo '<b>Component Error!<b> Invalid argument data type <i>'.$this->directory.'</i> -
directory not found';
exit();
}
return true;
}
/**
* read extensions
*
* @return null
*/
private function gifReadExtensions()
{
Lib_GIFDecoder::gifGetByte ( 1 );
for ( ; ; )
{
Lib_GIFDecoder::gifGetByte ( 1 );
if ( ( $u = $this->gifBuffer [ 0 ] ) == 0x00 )
{

Page 363 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

break;
}
Lib_GIFDecoder::gifGetByte ( $u );
// to determine the originaly delays between frames.
if ( $u == 4 )
{
$this->gifDelays [ ] = ( $this->gifBuffer [ 1 ] | $this->gifBuffer [ 2 ] << 8 );
}
}
}
/**
* read descriptor
*
* @return array
*/
private function gifReadDescriptor()
{
$gifScreen = Array ( );
Lib_GIFDecoder::gifGetByte ( 9 );
$gifScreen = $this->gifBuffer;
$gifColorF = $this->gifBuffer [ 8 ] & 0x80 ? 1 : 0;
if ( $gifColorF )
{
$GIF_code = $this->gifBuffer [ 8 ] & 0x07;
$GIF_sort = $this->gifBuffer [ 8 ] & 0x20 ? 1 : 0;
}
else
{
$GIF_code = $this->gifColorC;
$GIF_sort = $this->gifSorted;
}
$GIF_size = 2 << $GIF_code;
$this->gifScreen [ 4 ] &= 0x70;
$this->gifScreen [ 4 ] |= 0x80;
$this->gifScreen [ 4 ] |= $GIF_code;
if ( $GIF_sort )
{
$this->gifScreen [ 4 ] |= 0x08;
}
$this->gifString = "GIF87a";
Lib_GIFDecoder::gifPutByte ( $this->gifScreen );
if ( $gifColorF == 1 )
{
Lib_GIFDecoder::gifGetByte ( 3 * $GIF_size );
Lib_GIFDecoder::gifPutByte ( $this->gifBuffer );
}
else
{
Lib_GIFDecoder::gifPutByte ( $this->gifGlobal );
}
$this->gifString .= chr ( 0x2C );
$gifScreen [ 8 ] &= 0x40;
Lib_GIFDecoder::gifPutByte ( $gifScreen );
Lib_GIFDecoder::gifGetByte ( 1 );
Lib_GIFDecoder::gifPutByte ( $this->gifBuffer );
for ( ; ; )
{
Lib_GIFDecoder::gifGetByte ( 1 );
Lib_GIFDecoder::gifPutByte ( $this->gifBuffer );
if ( ( $u = $this->gifBuffer [ 0 ] ) == 0x00 )
{
break;
}
Lib_GIFDecoder::gifGetByte ( $u );
Lib_GIFDecoder::gifPutByte ( $this->gifBuffer );
}

Page 364 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

$this->gifString .= chr ( 0x3B );


//Add frames into $gifStream array
$this->gifArrays [ ] = $this->gifString;
}
/**
* get bytes
*
* @return integer
*/
private function gifGetByte($len)
{
$this->gifBuffer = Array ( );
for ( $i = 0; $i < $len; $i++ )
{
if ( $this->gifBseek > strlen ( $this->gifStream ) )
{
return 0;
}
$this->gifBuffer [ ] = ord ( $this->gifStream { $this->gifBseek++ } );
}
return 1;
}
/**
* add the bytes
*
*/
private function gifPutByte($bytes)
{
for ( $i = 0; $i < count ( $bytes ); $i++ )
{
$this->gifString .= chr ( $bytes [ $i ] );
}
}
/**
* get frames
*
* @return array
*/
private function gifGetFrames()
{
return ( $this->gifArrays );
}
/**
* get delays
*
* @return array
*/
private function gifGetDelays()
{
return ( $this->gifDelays );
}
/**
* Decode the Gif image
*
*/
private function gifDecode($GIF_pointer)
{
$this->gifStream = $GIF_pointer;
Lib_GIFDecoder::gifGetByte ( 6 ); // GIF89a
Lib_GIFDecoder::gifGetByte ( 7 ); // Logical Screen Descriptor
$this->gifScreen = $this->gifBuffer;
$this->gifColorF = $this->gifBuffer [ 4 ] & 0x80 ? 1 : 0;
$this->gifSorted = $this->gifBuffer [ 4 ] & 0x08 ? 1 : 0;
$this->gifColorC = $this->gifBuffer [ 4 ] & 0x07;
$this->gifColorS = 2 << $this->gifColorC;
if ( $this->gifColorF == 1 )

Page 365 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

{
Lib_GIFDecoder::gifGetByte ( 3 * $this->gifColorS );
$this->gifGlobal = $this->gifBuffer;
}
for ( $cycle = 1; $cycle; )
{
if ( Lib_GIFDecoder::gifGetByte ( 1 ) )
{
switch ( $this->gifBuffer [ 0 ] )
{
case 0x21:
Lib_GIFDecoder::gifReadExtensions ( );
break;
case 0x2C:
Lib_GIFDecoder::gifReadDescriptor ( );
break;
case 0x3B:
$cycle = 0;
break;
}
}
else
{
$cycle = 0;
}
}
}
/**
* call gifdecoder
*
* @return images
*/
private function callGifDecoder()
{
$fileName=explode("/",$this->filename);
$Index=count($fileName) - 1;
$fileName=$fileName[$Index];
$fileExt=explode(".",$this->filename);
$Index=count($fileExt) - 1;
$fileExt=$fileExt[$Index];
$title= str_replace('.'.$fileExt,"",$fileName);
$fp = fread ( fopen ( $this->filename, "rb" ), filesize ( $this->filename ) );
if ( $fp )
{
$this->gifDecode($fp);
$arr = $this->gifGetFrames ( );
$dly = $this->gifGetDelays ( );
for ( $i = 0; $i < count ( $arr ); $i++ )
{
fwrite ( fopen ( ( $i < 10 ? $this->directory."/0".$i."_".$title.".gif" : $this-
>directory."/".$i."_".$title.".gif" ), "wb" ), $arr [ $i ] );
}
for ( $i = 0; $i < count ( $dly ); $i++ )
{
sprintf ( "Delay of %d frame is %d ms<br>", $i, ( $dly [ $i ] * 10 /* milliseconds */ ) );
}
$this->result="true";
return true;
}
}
}
?>
Translate the Site words with Google Translator
<?php
/**
* GoogleTranslate

Page 366 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

*
* This class contains functions working with translate language for site.
*
* @package Lib_GoogleTranslate
* @category Library

* @version 1.0
*/
// ------------------------------------------------------------------------
class Lib_GoogleTranslate
{
/**
* Stores function type's name
*
* @var string $type
*/
private $type;
/**
* Flag for error
*
* @var boolean $error
*/
private $error;
/**
* Stores error numbers and description
*
* @var array $debug
*/
public $debug = array();
/**
* Stores the output
*
* @var bool $result
*/
public $result;
/**
* input url
*
* @var string $url
*/
private $url;
/**
* language converting from
*
* @var string $langFrom
*/
private $langFrom = false;
/**
* language conveting to
*
* @var string $langTo
*/
private $langTo = false;
/**
* Constructs a Lib_GoogleTranslate object with given parameters
* also it will invoke translation process
*
* @param string $type
* @param string $url
* @param string $langFrom
* @param string $langTo
* @return Lib_GoogleTranslate
*/
public function Lib_GoogleTranslate($type,$url,$langFrom,$langTo)
{

Page 367 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

$this->type = $type;
$this->url=$url;
$this->langFrom=$langFrom;
$this->langTo=$langTo;
if($this->isValidCall())
{
if(strtolower($type)=='translation')
$this->translateURL();
}
}
/**
* Check whether the function call is valid or not
*
* @return bool
*/
private function isValidCall()
{
if(strtolower($this->type)!='translation')
{
echo '<b>Component Error!<b> Invalid argument <i>type</i> - translation expected';
exit();
}
else if(empty($this->url))
{
echo '<b>Component Error!<b> Invalid argument <i>url</i> - url expected';
exit();
}
else if(is_numeric($this->url))
{
echo '<b>Component Error!<b> Invalid argument <i>url</i> - url must be string';
exit();
}
else if(empty($this->langFrom))
{
echo '<b>Component Error!<b> Invalid argument <i>langFrom</i> - from language
expected';
exit();
}
else if(is_numeric($this->langFrom))
{
echo '<b>Component Error!<b> Invalid argument <i>langFrom</i> - from language must be
string';
exit();
}
else if(empty($this->langTo))
{
echo '<b>Component Error!<b> Invalid argument <i>langTo</i> - to language expected';
exit();
}
else if(is_numeric($this->langTo))
{
echo '<b>Component Error!<b> Invalid argument <i>langTo</i> - to language must be
string';
exit();
}
return true;
}
/**
* set language to key word
*
* @return string
*/
private function returnLangTo()
{
return $this->langTo;
}

Page 368 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

/**
* set language from key word
*
* @return string
*/
private function returnLangFrom()
{
return $this->langFrom;
}
/**
* collection of language
*
* @return array
*/
private function returnLanguages()
{
$languages=array();
$languages['ar'] = 'Arabic';
$languages['bg'] = 'Bulgarian';
$languages['zh-CN'] = 'Chinese';
$languages['hr'] = 'Croatian';
$languages['cs'] = 'Czech';
$languages['da'] = 'Danish';
$languages['nl'] = 'Dutch';
$languages['en'] = 'English';
$languages['fi'] = 'Finnish';
$languages['fr'] = 'French';
$languages['de'] = 'German';
$languages['el'] = 'Greek';
$languages['hi'] = 'Hindi';
$languages['it'] = 'Italian';
$languages['ja'] = 'Japanese';
$languages['ko'] = 'Korean';
$languages['pl'] = 'Polish';
$languages['pt'] = 'Portuguese';
$languages['ro'] = 'Romanian';
$languages['ru'] = 'Russian';
$languages['es'] = 'Spanish';
$languages['sv'] = 'Swedish';
return $languages;
}
/**
* validates that the 2 languages are in the allowed languages
*
* @return array
*/
private function validateLangPair()
{
$languages = $this->returnLanguages();
$langFrom = $this->returnLangFrom();
$langTo = $this->returnLangTo();
if ( !isset($languages[$langFrom]))
{
$this->error = 1;
$this->debug['errinfo'] = array(1002=>'langFrom ['.$langFrom.'] is not in the allowed
languages');
return false;
}
if ( !isset($languages[$langTo]) )
{
$this->error = 1;
$this->debug['errinfo'] = array(1003=>'langTo ['.$langTo.'] is not in the allowed languages');
return false;
}
}
/**

Page 369 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

* translate a given URL


*
* @return string
*/
private function translateURL()
{
$url=$this->url;
if(!eregi("^(https?://)?(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-]+@)?(([0-
9]{1,3}\.){3}[0-9]{1,3}|([0-9a-z_!~*'()-]+\.)*([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\.[a-z]{2,6})(:[0-9]{1,4})?((/?)|(/[0-
9a-z_!~*'().;?:@&=+$,%#-]+)+/?)$",$url))
{
$this->error = 1;
$this->debug['errinfo'] = array(1001=>'Not a valid URL format');
return false;
}
$this->validateLangPair();
$langpair = $this->langFrom."|".$this->langTo;
$url='http://66.102.9.104/translate_c?hl=ro&safe=off&ie=UTF-8&oe=UTF-
8&prev=%2Flanguage_tools&langpair='.$langpair.'&u='.urlencode($url);
$RawHTML = $this->getDataCurl($url);
$this->result=$RawHTML;
return true;
}
/**
* Using curl to fetch the data
*
* @return string
*/
private function getDataCurl($url,$postData=false)
{
if( !extension_loaded('curl') )
{
$this->error = 1;
$this->debug['errinfo'] = array(1004=>'You need to load/activate the cURL extension
(http://www.php.net/cURL)');
return false;
}
$curlHandle = curl_init(); // init curl
curl_setopt($curlHandle, CURLOPT_COOKIEJAR,"cookie");
curl_setopt($curlHandle, CURLOPT_COOKIEFILE,"cookie");
curl_setopt($curlHandle, CURLOPT_URL, $url); // set the url to fetch
curl_setopt($curlHandle, CURLOPT_HEADER, 0); // set headers (0 = no headers in result)
curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, 1); // type of transfer (1 = to string)
curl_setopt($curlHandle, CURLOPT_TIMEOUT, 10); // time to wait in
curl_setopt($curlHandle, CURLOPT_POST, 0);
if ( $postData!==false )
{
curl_setopt($curlHandle, CURLOPT_POSTFIELDS, http_build_query($postData));
}
$content = curl_exec($curlHandle); // make the call
curl_close($curlHandle); // close the connection
return $content;
}
}
?>
Convert the HTML page to Document
<?php
/**
* HtmlToDoc
*
* This class contains functions convert html to word document.
*
* @package Lib_HtmlToDoc
* @category Library

Page 370 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

* @version 1.0
*/
// ------------------------------------------------------------------------
Class Lib_HtmlToDoc
{
/**
* Stores function type's name
*
* @var string $type
*/
private $type;
/**
* Flag for error
*
* @var boolean $error
*/
private $error;
/**
* Stores error numbers and description
*
* @var array $debug
*/
public $debug = array();
/**
* Stores the output
*
* @var string $result
*/
public $result;
/**
* source file path
*
* @var string $sourceFile
*/
private $sourceFile;
/**
* output file name
*
* @var string $filename
*/
private $filename;
/**
* save designation directory name
*
* @var string $directory
*/
private $directory;
/**
* document file name
*
* @var string $docFile
*/
private $docFile="";
/**
* document title
*
* @var string $title
*/
private $title="Untitled Document";
/**
* html head content
*
* @var string $htmlHead
*/
private $htmlHead="";
/**

Page 371 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

* html body content


*
* @var string $htmlBody
*/
private $htmlBody="";
/**
* Constructs a Lib_HtmlToDoc object with given parameters
* also it will invoke html to doc process
*
* @param string $type
* @param string $sourceFile
* @param string $filename
* @param string $directory
* @return Lib_HtmlToDoc
*/
public function Lib_HtmlToDoc ($type,$sourceFile,$filename,$directory)
{
$this->type = $type;
$this->sourceFile = $sourceFile;
$this->filename = $filename;
$this->directory = $directory;
if($this->isValidCall())
{
if(strtolower($type)=='html_doc')
$this->callDoc();
if(strtolower($type)=='url_doc')
$this->createDocFromURL();
}
}
/**
* Check whether the function call is valid or not
*
* @return bool
*/
private function isValidCall()
{
if(strtolower($this->type)!='html_doc' && strtolower($this->type)!='url_doc')
{
echo '<b>Component Error!<b> Invalid argument <i>type</i> - html_doc or url_doc
expected';
exit();
}
elseif(empty($this->sourceFile))
{
echo '<b>Component Error!<b> Invalid argument data type <i>sourceFile</i> - file name
expected';
exit();
}
elseif(empty($this->filename))
{
echo '<b>Component Error!<b> Invalid argument data type <i>filename</i> - file name
expected';
exit();
}
elseif(empty($this->directory))
{
echo '<b>Component Error!<b> Invalid argument data type <i>directory</i> - directory name
expected';
exit();
}
elseif(!file_exists($this->directory))
{
echo '<b>Component Error!<b> Invalid argument data type <i>'.$this->directory.'</i> -
directory not found';
exit();
}

Page 372 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

elseif(!is_writable($this->directory))
{
echo '<b>Component Error!<b> Access Denied <i>'.$this->directory.'</i> - destination path
not writable';
exit();
}
return true;
}
/**
* Set the document file name
*
*/
private function setDocFileName($docfile)
{
$this->docFile=$docfile;
if(!preg_match("/\.doc$/i",$this->docFile))
$this->docFile.=".doc";
return;
}
/**
* Set the title
*
*/
private function setTitle($title)
{
$this->title=$title;
}
/**
* get header of MS Doc
*
* @return String
*/
private function getHeader()
{
$return = <<<EOH
<html xmlns:v="urn:schemas-microsoft-com:vml"
xmlns:o="urn:schemas-microsoft-com:office:office"
xmlns:w="urn:schemas-microsoft-com:office:word"
xmlns="http://www.w3.org/TR/REC-html40">
<head>
<meta http-equiv=Content-Type content="text/html; charset=utf-8">
<meta name=ProgId content=Word.Document>
<meta name=Generator content="Microsoft Word 9">
<meta name=Originator content="Microsoft Word 9">
<!--[if !mso]>
<style>
v\:* {behavior:url(#default#VML);}
o\:* {behavior:url(#default#VML);}
w\:* {behavior:url(#default#VML);}
.shape {behavior:url(#default#VML);}
</style>
<![endif]-->
<title>$this->title</title>
<!--[if gte mso 9]><xml>
<w:WordDocument>
<w:View>Print</w:View>
<w:DoNotHyphenateCaps/>
<w:PunctuationKerning/>
<w:DrawingGridHorizontalSpacing>9.35 pt</w:DrawingGridHorizontalSpacing>
<w:DrawingGridVerticalSpacing>9.35 pt</w:DrawingGridVerticalSpacing>
</w:WordDocument>
</xml><![endif]-->
<style>
<!--
/* Font Definitions */
@font-face

Page 373 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

{font-family:Verdana;
panose-1:2 11 6 4 3 5 4 4 2 4;
mso-font-charset:0;
mso-generic-font-family:swiss;
mso-font-pitch:variable;
mso-font-signature:536871559 0 0 0 415 0;}
/* Style Definitions */
p.MsoNormal, li.MsoNormal, div.MsoNormal
{mso-style-parent:"";
margin:0in;
margin-bottom:.0001pt;
mso-pagination:widow-orphan;
font-size:7.5pt;
mso-bidi-font-size:8.0pt;
font-family:"Verdana";
mso-fareast-font-family:"Verdana";}
p.small
{mso-style-parent:"";
margin:0in;
margin-bottom:.0001pt;
mso-pagination:widow-orphan;
font-size:1.0pt;
mso-bidi-font-size:1.0pt;
font-family:"Verdana";
mso-fareast-font-family:"Verdana";}
@page Section1
{size:8.5in 11.0in;
margin:1.0in 1.25in 1.0in 1.25in;
mso-header-margin:.5in;
mso-footer-margin:.5in;
mso-paper-source:0;}
div.Section1
{page:Section1;}
-->
</style>
<!--[if gte mso 9]><xml>
<o:shapedefaults v:ext="edit" spidmax="1032">
<o:colormenu v:ext="edit" strokecolor="none"/>
</o:shapedefaults></xml><![endif]--><!--[if gte mso 9]><xml>
<o:shapelayout v:ext="edit">
<o:idmap v:ext="edit" data="1"/>
</o:shapelayout></xml><![endif]-->
$this->htmlHead
</head>
<body>
EOH;
return $return;
}
/**
* Return Document footer
*
* @return String
*/
private function getFotter()
{
return "</body></html>";
}
/**
* check valid url
*
* @return bool
*/
private function isValidUrl($url)
{
if (!eregi("^((http://|https://|file://){0,1}" // type
.'([a-z0-9-]{1,32}[.]){1,10}([a-z0-9]){2,3}' // domain

Page 374 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

.'(:[0-9]{1,5}){0,1}' // port
.'([/\]{1,3}[a-z0-9_-~.]{0,64}){0,16}' // directory
.'([?][a-z0-9=%;+]+){0,1}$|$)', // options
trim($url)))
return false;
else
return true;
}
/**
* Create The MS Word Document from given site url
*
* @return boolean
*/
private function createDocFromURL()
{
$url=$this->sourceFile;
$file=$this->filename;
$folder=$this->directory;
if($this->isValidUrl($url))
{
if(!preg_match("/^http:/",$url))
$url="http://".$url;
$html=@file_get_contents($url);
return $this->createDoc($html,$file,$folder);
}
else
{
$this->error = 1;
$this->debug['errinfo'] = array(1001=>'valid url expected');
return false;
}
}
/**
* call sub function
*
*/
private function callDoc()
{
$html=$this->sourceFile;
$file=$this->filename;
$folder=$this->directory;
if(file_exists($html))
$this->createDoc($html,$file,$folder);
else
{
$this->error = 1;
$this->debug['errinfo'] = array(1002=>'file is not exist');
return false;
}
}
/**
* Create The MS Word Document from given HTML
*
* @return boolean
*/
private function createDoc($html,$file,$folder)
{
if(is_file($html))
$html=@file_get_contents($html);
$this->parseHtml($html);
$this->setDocFileName($file);
$doc=$this->getHeader();
$doc.=$this->htmlBody;
$doc.=$this->getFotter();
return $this->writeFile($folder.'/'.$this->docFile,$doc);
}

Page 375 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

/**
* Parse the html and remove <head></head> part if present into html
*
* @return void
*/
private function parseHtml($html)
{
$html=preg_replace("/<!DOCTYPE((.|\n)*?)>/ims","",$html);
$html=preg_replace("/<script((.|\n)*?)>((.|\n)*?)<\/script>/ims","",$html);
preg_match("/<head>((.|\n)*?)<\/head>/ims",$html,$matches);
$head=$matches[1];
preg_match("/<title>((.|\n)*?)<\/title>/ims",$head,$matches);
$this->title = $matches[1];
$html=preg_replace("/<head>((.|\n)*?)<\/head>/ims","",$html);
$head=preg_replace("/<title>((.|\n)*?)<\/title>/ims","",$head);
$head=preg_replace("/<\/?head>/ims","",$head);
$html=preg_replace("/<\/?body((.|\n)*?)>/ims","",$html);
$this->htmlHead=$head;
$this->htmlBody=$html;
return;
}
/**
* Write the content int file
*
* @return bool
*/
private function writeFile($file,$content,$mode="w")
{
$fp=@fopen($file,$mode);
if(!is_resource($fp))
{
$this->result="false";
return true;
}
fwrite($fp,$content);
fclose($fp);
$this->result="true";
return true;
}
}
?>
Which like relation calculation between two names
<?php
/**
* LoveCalculator
*
* This class contains functions which like relation calculation between two names.
*
* @package Lib_LoveCalculator
* @category Library

* @version 1.0
*/
// ------------------------------------------------------------------------
class Lib_LoveCalculator
{
/**
* Stores function type's name
*
* @var string $type
*/
private $type;
/**
* Flag for error
*

Page 376 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

* @var boolean $error


*/
private $error;
/**
* Stores error numbers and description
*
* @var array $debug
*/
public $debug = array();
/**
* Stores the output
*
* @var bool $result
*/
public $result;
/**
* user first name
*
* @var string $firstName
*/
private $firstName;
/**
* user second name
*
* @var string $secondName
*/
private $secondName;
/**
* Constructs a Lib_LoveCalculator object with given parameters
* also it will invoke relation between two names process
*
* @param string $type
* @param string $firstName
* @param string $secondName
* @return Lib_LoveCalculator
*/
public function Lib_LoveCalculator($type,$firstName,$secondName)
{
$this->type = $type;
$this->firstName=$firstName;
$this->secondName=$secondName;
if($this->isValidCall())
{
if(strtolower($type)=='love')
$this->loveCalc();

}
}
/**
* Check whether the function call is valid or not
*
* @return bool
*/
private function isValidCall()
{
if(strtolower($this->type)!='love')
{
echo '<b>Component Error!<b> Invalid argument <i>type</i> - love expected';
exit();
}
else if(empty($this->firstName))
{
echo '<b>Component Error!<b> Invalid argument <i>firstName</i> - user first name
expected';
exit();
}

Page 377 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

else if(is_numeric($this->firstName))
{
echo '<b>Component Error!<b> Invalid argument <i>firstName</i> - first name must be
string';
exit();
}
else if(empty($this->secondName))
{
echo '<b>Component Error!<b> Invalid argument <i>secondName</i> - user second name
expected';
exit();
}
else if(is_numeric($this->secondName))
{
echo '<b>Component Error!<b> Invalid argument <i>secondName</i> - second name must
be string';
exit();
}
return true;
}
/**
* find out relation between two names.
*
* @return string $result
*/
function loveCalc ()
{
$this->lovename = strtolower(preg_replace("/ /","",strip_tags(trim($this->firstName.$this-
>secondName))));
$alp = count_chars($this->lovename);
for($i=97;$i<=122;$i++)
{
if($alp[$i]!=false)
{
$anz = strlen($alp[$i]);
if($anz<2)
{
$calc[] = $alp[$i];
}
else
{
for($a=0;$a<$anz;$a++)
{
$calc[] = substr($alp[$i],$a,1);
}
}
}
}
while (($anzletter = count($calc))>2)
{
$lettermitte = ceil($anzletter/2);
for($i=0;$i<$lettermitte;$i++)
{
$sum = array_shift($calc)+array_shift($calc);
$anz = strlen($sum);
if($anz<2)
{
$calcmore[] = $sum;
}
else
{
for($a=0;$a<$anz;$a++)
{
$calcmore[] = substr($sum,$a,1);
}
}

Page 378 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

}
$anzc = count($calcmore);
for($b=0;$b<$anzc;$b++)
{
$calc[] = $calcmore[$b];
}
array_splice($calcmore,0);
}
$this->lovestat = $calc[0].$calc[1];
$this->result=$this->lovestat.'%';
return true;
}
}
?>
Convert original image to cartoon effect image
<?php
/**
* MakeCartoon
*
* This class contains functions that convert original image to cartoon effect image.
*
* @package Lib_MakeCartoon
* @category Library

* @version 1.0
*/
// ------------------------------------------------------------------------
class Lib_MakeCartoon
{
/**
* Stores function type's name
*
* @var string $type
*/
private $type;
/**
* Flag for error
*
* @var boolean $error
*/
private $error;
/**
* Stores error numbers and description
*
* @var array $debug
*/
public $debug = array();
/**
* Stores the output
*
* @var bool $result
*/
public $result;
/**
* source image path
*
* @var string $srcImage
*/
private $srcImage;
/**
* destination image name
*
* @var string $destImageName
*/
private $destImageName;

Page 379 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

/**
* destination image extension
*
* @var string $destImageType
*/
private $destImageType;
/**
* image save destination path
*
* @var string $destPath
*/
private $destPath;
/**
* Constructs a Lib_MakeCartoon object with given parameters
* also it will invoke cartoon image process
*
* @param string $type
* @param string $srcImage
* @param string $destPath
* @param string $destImageName
* @param string $destImageType
* @return Lib_MakeCartoon
*/
public function Lib_MakeCartoon($type,$srcImage,$destPath,$destImageName,$destImageType)
{
$this->type = $type;
$this->srcImage = $srcImage;
$this->destPath = $destPath;
$this->destImageName = $destImageName;
$this->destImageType = $destImageType;
if($this->isValidCall())
{
if(strtolower($type)=='cartoon')
$this->makeCall();
}
}
/**
* Check whether the function call is valid or not
*
* @return bool
*/
private function isValidCall()
{
if(strtolower($this->type)!='cartoon')
{
echo '<b>Component Error!<b> Invalid argument <i>type</i> - cartoon expected';
exit();
}
elseif(empty($this->srcImage))
{
echo '<b>Component Error!<b> Invalid argument data type <i>srcImage</i> - source file
path expected';
exit();
}
elseif(!file_exists($this->srcImage))
{
echo '<b>Component Error!<b> Invalid argument data type <i>'.$this->srcImage.'</i> -
source file path not found';
exit();
}
elseif(!file_exists($this->destPath))
{
echo '<b>Component Error!<b> Invalid argument data type <i>'.$this->destPath.'</i> -
destination file path not found';
exit();
}

Page 380 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

else if(!is_writable($this->destPath))
{
echo '<b>Component Error!<b> Access Denied <i>'.$this->destPath.'</i> - destination path
not writable';
exit();
}
elseif(empty($this->destImageName))
{
echo '<b>Component Error!<b> Invalid argument data type <i>destImageName</i> -
destination image name expected';
exit();
}
elseif(empty($this->destImageType))
{
echo '<b>Component Error!<b> Invalid argument data type <i>destImageType</i> -
destination image type expected';
exit();
}
elseif(strtolower($this->destImageType)!='jpg' && strtolower($this->destImageType)!='jpeg' &&
strtolower($this->destImageType)!='gif' && strtolower($this->destImageType)!='png')
{
echo '<b>Component Error!<b> Invalid argument data type <i>destImageType</i> -
destination image type must be jpg/jpeg/gif/png';
exit();
}
else if(!function_exists("gd_info"))
{
echo '<b>Component Error!<b> Invalid Stream <i>GD</i> - Cannot initialize new GD image
stream';
exit();
}
return true;
}
/**
* image convert to cartoon effect image
*
*/
private function cartoonfy ( $image, $triplevel, $diffspace )
{
$this->triplevel = (int)( 2000.0 + 5000.0 * $triplevel );
$this->diffspace = (int)( $diffspace * 32.0 );
if ( $this->i0 = imageCreateFromString ( fread ( fopen ( $image, "rb" ), filesize ( $image ) ) ) )
{
$this->i1 = imageCreateTrueColor ( imageSx ( $this->i0 ), imageSy ( $this->i0 ) );
for ( $x = (int)$this->diffspace; $x < imageSx ( $this->i0 ) - ( 1 + (int)$this->diffspace );
$x++ )
{
for ( $y = (int)$this->diffspace; $y < imageSy ( $this->i0 ) - ( 1 + (int)$this-
>diffspace ); $y++ )
{
$t = $this->getMaxContrast ( $x, $y );
if ( $t > $this->triplevel )
{
imageSetPixel ( $this->i1, $x, $y, 0 );
}
else
{
imageSetPixel ( $this->i1, $x, $y, $this->flattenColor ( imageColorAt (
$this->i0, $x, $y ) ) );
}
}
}
imageDestroy ( $this->i0 );
}
else
{

Page 381 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

$this->error = 1;
$this->debug['errinfo'] = array(1001=>$image.'is not supported image format');
return false;
}
}
/**
* get rgb red
*
* @return color
*/
private function r ( $i )
{
return ( ( $i >> 16 ) & 0x000000FF );
}
/**
* get rgb green
*
* @return color
*/
private function g ( $i )
{
return ( ( $i >> 8 ) & 0x000000FF );
}
/**
* get rgb blue
*
* @return color
*/
private function b ( $i )
{
return ( $i & 0x000000FF );
}
/**
* get rgb color
*
* @return color
*/
private function rgb ( $r, $g, $b )
{
return ( $r << 16 ) + ( $g << 8 ) + ( $b );
}
/**
* get merror
*
* @return integer
*/
private function gmerror ( $cc1, $cc2 )
{
return ( ( ( ( $this->r ( $cc1 ) - $this->r ( $cc2 ) ) * ( $this->r ( $cc1 ) - $this->r ( $cc2 ) ) ) + ( ( $this-
>g ( $cc1 ) - $this->g ( $cc2 ) ) * ( $this->g ( $cc1 ) - $this->g ( $cc2 ) ) ) + ( ( $this->b ( $cc1 ) - $this->b ( $cc2 ) )
* ( $this->b ( $cc1 ) - $this->b ( $cc2 ) ) ) ) );
}
/**
* get flatten color
*
* @return color
*/
private function flattenColor ( $c )
{
return $this->rgb ( ( ( $this->r ( $c ) ) >> 5 ) << 5, ( ( $this->g ( $c ) ) >> 5 ) << 5, ( ( $this->b (
$c ) ) >> 5 ) << 5 );
}
/**
* get maximum contrast image
*
* @return float

Page 382 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

*/
private function getMaxContrast ( $x, $y )
{
$c1;
$c2;
$error = 0;
$max = 0;
$c1 = imageColorAt ( $this->i0, $x - (int)$this->diffspace, $y );
$c2 = imageColorAt ( $this->i0, $x + (int)$this->diffspace, $y );
$error = $this->gmerror ( $c1, $c2 );
if ( $error > $max )
$max = $error;
$c1 = imageColorAt ( $this->i0, $x, $y - (int)$this->diffspace );
$c2 = imageColorAt ( $this->i0, $x, $y + (int)$this->diffspace );
$error = $this->gmerror ( $c1, $c2 );
if ( $error > $max )
$max = $error;
$c1 = imageColorAt ( $this->i0, $x - (int)$this->diffspace, $y - (int)$this->diffspace );
$c2 = imageColorAt ( $this->i0, $x + (int)$this->diffspace, $y + (int)$this->diffspace );
$error = $this->gmerror ( $c1, $c2 );
if ( $error > $max )
$max = $error;
$c1 = imageColorAt ( $this->i0, $x + (int)$this->diffspace, $y - (int)$this->diffspace );
$c2 = imageColorAt ( $this->i0, $x - (int)$this->diffspace, $y + (int)$this->diffspace );
$error = $this->gmerror ( $c1, $c2 );
if ( $error > $max )
$max = $error;
return ( $max );
}
/**
* save the image to destination path
*
*/
private function showCartoonfy ($ext)
{
switch ( strtolower ( $ext ) )
{
case "jpg":
imageJpeg ( $this->i1,$this->destPath.'/'.$this->destImageName.'.jpg' );
break;
case "jpeg":
imageJpeg ( $this->i1,$this->destPath.'/'.$this->destImageName.'.jpg' );
break;
case "gif":
imageGif ( $this->i1,$this->destPath.'/'.$this->destImageName.'.gif' );
break;
case "png":
imagePng ( $this->i1,$this->destPath.'/'.$this->destImageName.'.png' );
break;
}
imageDestroy ( $this->i1 );
}
/**
* call all sub functions
*
* @return string $result
*/
private function makeCall()
{
$params = Array('Triplevel' => 1.0,'Diffspace' => ( 1.0 / 32.0 ));
$this->cartoonfy($this->srcImage, $params [ 'Triplevel' ], $params [ 'Diffspace' ] );
$this->showCartoonfy($this->destImageType);
$this->result="true";
return true;
}
}

Page 383 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

?>
Merge 2 Images into a Single Image
<?php
/**
* MergeImages
*
* This class contains functions merge two images into single image.
*
* @package Lib_MergeImages
* @category Library

* @version 1.0
*/
// ------------------------------------------------------------------------
class Lib_MergeImages
{
/**
* Stores function type's name
*
* @var string $type
*/
private $type;
/**
* Flag for error
*
* @var boolean $error
*/
private $error;
/**
* Stores error numbers and description
*
* @var array $debug
*/
public $debug = array();
/**
* Stores the output
*
* @var string $result
*/
public $result;
/**
* Destination Image
*
* @var Resource imagecreatetruecolor
*/
private $image;
/**
* resize percentage of image 2
*
* @var float
*/
private $perc;
/**
* co-ordinated X
*
* @var float
*/
private $x;
/**
* co-ordinated Y
*
* @var float
*/
private $y;
/**

Page 384 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

* filename for image1


*
* @var string $file1
*/
private $file1;
/**
* filename for image2
*
* @var string $file2
*/
private $file2;
/**
* directory for store merge file
*
* @var string $dirName
*/
private $dirName;
/**
* output merge image file name
*
* @var string $filename
*/
private $filename;
/**
* output merge file extension
*
* @var string $imgtype
*/
private $imgtype;
/**
* merging position
*
* @var string $position
*/
private $position;
/**
* dimension of images
*
* @var string $alt1,$alt2,$tam1,$tam2
*/
private $alt1;
private $tam1;
private $alt2;
private $tam2;
/**
* image type
*
* @var string $img1,$img1
*/
private $img1;
private $img2;
/**
* image name
*
* @var string $name1,$name2
*/
private $name1;
private $name2;
/**
* Constructs a Lib_MergeImages object with given parameters
* also it will invoke image merge process
*
* @param String $type
* @param String $file1
* @param String $file2
* @param String $pos

Page 385 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

* @param String $dirname


* @param String $filename
* @param String $imgtype
* @return Lib_MergeImages
*/
public function Lib_MergeImages($type,$file1,$file2,$dirname,$filename,$imgtype,$position='up')
{
$this->type=$type;
$this->file1=$file1;
$this->file2=$file2;
$this->position=$position;
$this->dirName=$dirname;
$this->filename=$filename;
$this->imgtype=$imgtype;
if($this->isValidCall())
{
if(strtolower($type)=='mergeimage')
$this->callMerge();
}
}
/**
* Check whether the function call is valid or not
*
* @return bool
*/
private function isValidCall()
{
if(strtolower($this->type)!='mergeimage')
{
echo '<b>Component Error!<b> Invalid argument <i>type</i> - mergeimage expected';
exit();
}
elseif(empty($this->file1))
{
echo '<b>Component Error!<b> Invalid argument data type <i>file1</i> - image1 expected';
exit();
}
elseif(!file_exists($this->file1))
{
echo '<b>Component Error!<b> Invalid argument data type <i>'.$this->file1.'</i> - image1
not found';
exit();
}
elseif(empty($this->file2))
{
echo '<b>Component Error!<b> Invalid argument data type <i>file2</i> - image2 expected';
exit();
}
elseif(!file_exists($this->file2))
{
echo '<b>Component Error!<b> Invalid argument data type <i>'.$this->file2.'</i> - image2
not found';
exit();
}
if(strtolower($this->position)!='up' && strtolower($this->position)!='down')
{
echo '<b>Component Error!<b> Invalid argument <i>position</i> - up/down expected';
exit();
}
elseif(empty($this->dirName))
{
echo '<b>Component Error!<b> Invalid argument data type <i>dirName</i> - directory name
expected';
exit();
}
elseif(!file_exists($this->dirName))

Page 386 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

{
echo '<b>Component Error!<b> Invalid argument data type <i>'.$this->dirName.'</i> -
directory not found';
exit();
}
elseif(!is_writable($this->dirName))
{
echo '<b>Component Error!<b> Access Denied <i>'.$this->dirName.'</i> - destination path
not writable';
exit();
}
elseif(empty($this->filename))
{
echo '<b>Component Error!<b> Invalid argument data type <i>filename</i> - file name
expected';
exit();
}
if(strtolower($this->imgtype)!='jpg' && strtolower($this->imgtype)!='gif' && strtolower($this-
>imgtype)!='png')
{
echo '<b>Component Error!<b> Invalid argument <i>imgtype</i> - image type jpg/gif/png
expected';
exit();
}
return true;
}
/**
* Create image type is jpg
*
*/
private function foto($name,$i)
{
$dim = getimagesize($name);
if($i==1)
{
$this->tam1 = $dim[0];
$this->alt1 = $dim[1];
$this->img1 = imagecreatefromjpeg($name);
$this->name1 = $name;
}
elseif($i==2)
{
$this->tam2 = $dim[0];
$this->alt2 = $dim[1];
$this->img2 = imagecreatefromjpeg($name);
$this->name2 = $name;
}
}
/**
* Create image type is png
*
*/
private function fotoPng($name,$i)
{
$dim = getimagesize($name);
if($i==1)
{
$this->tam1 = $dim[0];
$this->alt1 = $dim[1];
$this->img1 = imagecreatefrompng($name);
$this->name1 = $name;
}
elseif($i==2)
{
$this->tam2 = $dim[0];
$this->alt2 = $dim[1];

Page 387 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

$this->img2 = imagecreatefrompng($name);
$this->name2 = $name;
}
}
/**
* merge and save the images
*
* @return images
*/
private function callMerge()
{
$this->mergePictures();
$this->merge();
$this->save();
}
private function validate($file)
{
$fileName=explode("/",$file);
$Index=count($fileName) - 1;
$fileName=$fileName[$Index];
$fileExt=explode(".",$file);
$Index=count($fileExt) - 1;
$fileExt=$fileExt[$Index];
return $fileExt;
}
/**
* merge the two pictures
*
* @return image
*/
private function mergePictures()
{
$fileExt1=$this->validate($this->file1);
$fileExt2=$this->validate($this->file2);
//echo $fileExt1; echo $fileExt2;
if(strtolower($fileExt1)!='jpg' && strtolower($fileExt1)!='png')
{
$this->error = 1;
$this->debug['errinfo'] = array(1001=>'file1 must be jpg or png format');
return false;
}
if(strtolower($fileExt2)!='jpg' && strtolower($fileExt2)!='png')
{
$this->error = 1;
$this->debug['errinfo'] = array(1002=>'file2 must be jpg or png format');
return false;
}
// it verifies which is the source picture type
if(strtolower(substr($this->file1,strlen($this->file1)-3 ,strlen($this->file1)))=="png")
{
$this->fotoPng($this->file1,1);
$png = true;
}
else
{
$png = false;
$this->foto($this->file1,1);
}
//same thing for the picture 2
if(strtolower( substr($this->file2,strlen($this->file2)-3 ,strlen($this->file2)))=="png")
$this-> fotoPng($this->file2,2);
else
$this->foto($this->file2,2);
//percentage of reduction of imagem2
$this->perc = 1;
if ($this->tam1 < $this->tam2)

Page 388 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

{
$this->perc= ($this->tam2 - $this->tam1)*100/ $this->tam2 ;
$this->perc =1- $this->perc/100;
}
if ($this->tam1 > $this->tam2)
{
$this->perc= ($this->tam1 - $this->tam2)*100/ $this->tam2 ;
$this->perc = 1 + $this->perc/100;
}
$this->x = $this->tam1;
$this->y = $this->alt1 + $this->alt2*$this->perc;
}
/**
* it catches image1 and it places on proportionally reduced image2
*
*/
private function over()
{
$this->image = imagecreatetruecolor($this->x,$this->alt2*$this->perc );
imagecopyresampled($this->image,$this->img2,0, 0,0,0 , $this->x ,$this->alt2*$this->perc, $this-
>tam2 ,$this->alt2);
imagecopy( $this->image, $this->img1 , 0 ,($this->alt2*$this->perc)-$this->alt1 , 0, 0, $this->tam1,
$this->alt1);
}
/**
* it catches proportionally reduced image 2 and it joins it with imagem1
*
*/
private function merge()
{
$this->image = @imagecreatetruecolor($this->x,$this->y);
switch (strtolower($this->position))
{
case "up":
@imagecopy( $this->image, $this->img1 , 0 , $this->alt2*$this->perc , 0, 0, $this-
>tam1, $this->alt1);
@imagecopyresampled($this->image,$this->img2,0, 0,0,0 , $this->tam1 ,$this->y-
$this->alt1 , $this->tam2 ,$this->alt2);
break;
case "down":
@imagecopy( $this->image, $this->img1 , 0 , 0, 0, 0, $this->tam1, $this->alt1);
@imagecopyresampled($this->image,$this->img2,0, $this->alt1,0,0 , $this->tam1
,$this->y-$this->alt1 , $this->tam2,$this->alt2);
break;
}
}
/**
* Saves the new picture
*
*/
private function save()
{
if($this->dirName!="")
$this->dirName.="/";
if($this->filename!="" and $this->imgtype!="" and (strtolower($this->imgtype)=="jpg" or
strtolower($this->imgtype)=="gif" or strtolower($this->imgtype)=="png"))
{
switch (strtolower($this->imgtype))
{
case "jpg":
@imagejpeg($this->image, $this->dirName.$this->filename.".jpg");
break;
case "gif":
@imagegif($this->image, $this->dirName.$this->filename.".gif");
break;
case "png":

Page 389 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

@imagepng($this->image, $this->dirName.$this->filename.".png");
break;
}
$this->result="true";
}
else
$this->result="false";
return true;
}
}
?>
Convert original image to image appears mirrored
<?php
/**
* MirrorImage
*
* This class contains functions that convert original image to image appears mirrored.
*
* @package Lib_MirrorImage
* @category Library

* @version 1.0
*/
// ------------------------------------------------------------------------
class Lib_MirrorImage
{
/**
* Stores function type's name
*
* @var string $type
*/
private $type;
/**
* Flag for error
*
* @var boolean $error
*/
private $error;
/**
* Stores error numbers and description
*
* @var array $debug
*/
public $debug = array();
/**
* Stores the output
*
* @var bool $result
*/
public $result;
/**
* source image path
*
* @var string $srcImage
*/
private $srcImage;
/**
* image destination path
*
* @var string $destPath
*/
private $destPath;
/**
* destination image name
*

Page 390 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

* @var string $destImageName


*/
private $destImageName;
/**
* destination image extension
*
* @var string $destImageType
*/
private $destImageType;

/**
* Constructs a Lib_MirrorImage object with given parameters
* also it will invoke mirror image process
*
* @param string $type
* @param string $srcImage
* @param string $destPath
* @param string $destImageName
* @param string $destImageType
* @return Lib_MirrorImage
*/

public function Lib_MirrorImage($type,$srcImage,$destPath,$destImageName,$destImageType)


{
$this->type = $type;
$this->srcImage = $srcImage;
$this->destPath = $destPath;
$this->destImageName = $destImageName;
$this->destImageType = $destImageType;

if($this->isValidCall())
{
if(strtolower($type)=='mirror')
$this->makeCall();
}
}

/**
* Check whether the function call is valid or not
*
* @return bool
*/
private function isValidCall()
{
if(strtolower($this->type)!='mirror')
{
echo '<b>Component Error!<b> Invalid argument <i>type</i> - mirror expected';
exit();
}
elseif(empty($this->srcImage))
{
echo '<b>Component Error!<b> Invalid argument data type <i>srcImage</i> - source file
path expected';
exit();
}
elseif(!file_exists($this->srcImage))
{
echo '<b>Component Error!<b> Invalid argument data type <i>'.$this->srcImage.'</i> -
source file path not found';
exit();
}
elseif(!file_exists($this->destPath))
{
echo '<b>Component Error!<b> Invalid argument data type <i>'.$this->destPath.'</i> -
destination file path not found';
exit();

Page 391 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

}
else if(!is_writable($this->destPath))
{
echo '<b>Component Error!<b> Access Denied <i>'.$this->destPath.'</i> - destination path
not writable';
exit();
}
elseif(empty($this->destImageName))
{
echo '<b>Component Error!<b> Invalid argument data type <i>destImageName</i> -
destination image name expected';
exit();
}
elseif(empty($this->destImageType))
{
echo '<b>Component Error!<b> Invalid argument data type <i>destImageType</i> -
destination image type expected';
exit();
}
elseif(strtolower($this->destImageType)!='jpg' && strtolower($this->destImageType)!='jpeg' &&
strtolower($this->destImageType)!='gif' && strtolower($this->destImageType)!='png')
{
echo '<b>Component Error!<b> Invalid argument data type <i>destImageType</i> -
destination image type must be jpg/jpeg/gif/png';
exit();
}
else if(!function_exists("gd_info"))
{
echo '<b>Component Error!<b> Invalid Stream <i>GD</i> - Cannot initialize new GD image
stream';
exit();
}
return true;
}

/**
* call sub functions and show the output
*
* @return string
*/

private function makeCall()


{
list($width,$height,$type)=getimagesize($this->srcImage);
if($type==1)
$outputImage = $this->imageMirror(imagecreatefromgif($this->srcImage));
else if($type==2)
$outputImage = $this->imageMirror(imagecreatefromjpeg($this->srcImage));
else if($type==3)
$outputImage = $this->imageMirror(imagecreatefrompng($this->srcImage));
else
{
$this->error = 1;
$this->debug['errinfo'] = array(1001=>'image must be gif/jpg/png');
return false;
}
$this->showImage($outputImage,$this->destImageType);
$this->result="true";
return true;
}

/**
* image convert to mirrored image
*
* @return image
*/

Page 392 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

private function imageMirror ($inputImage)


{
$width = imagesx($inputImage);
$height = imagesy($inputImage);
$outputImage = imagecreatetruecolor($width,$height);
$y = 1;

while ( $y < $height )


{
for ( $i = 1; $i <= $width; $i++ )
imagesetpixel ( $outputImage, $i, $y, imagecolorat ( $inputImage, ( $i ), ( $height - $y
) ) );
$y = $y + 1;
}

return $outputImage;
}

/**
* save the image to destination path
*
*/

private function showImage ($outputImage,$ext)


{
switch(strtolower($ext))
{
case "jpg":
imageJpeg ($outputImage,$this->destPath.'/'.$this->destImageName.'.jpg',75 );
break;
case "jpeg":
imageJpeg ($outputImage,$this->destPath.'/'.$this->destImageName.'.jpg',75 );
break;
case "gif":
imageGif ($outputImage,$this->destPath.'/'.$this->destImageName.'.gif' );
break;
case "png":
imagePng ($outputImage,$this->destPath.'/'.$this->destImageName.'.png' );
break;
}
imageDestroy ($outputImage);
}

}
?>
Get Site Page Ranks
<?php
/**
* PageRank
*
* This class contains functions retrieve page rank for given site.
*
* @package Lib_PageRank
* @category Library

* @version 1.0
*/
// ------------------------------------------------------------------------
class Lib_PageRank
{
/**
* Stores function type's name
*
* @var string $type

Page 393 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

*/
private $type;
/**
* Flag for error
*
* @var boolean $error
*/
private $error;
/**
* Stores error numbers and description
*
* @var array $debug
*/
public $debug = array();
/**
* Stores the output
*
* @var bool $result
*/
public $result;
/**
* domain info
*
* @var array $googleDomains
*/
private $googleDomains = Array(
"toolbarqueries.google.com",
"www.google.com",
"toolbarqueries.google.com.tr",
"www.google.com.tr",
"toolbarqueries.google.de",
"www.google.de",
"64.233.187.99",
"72.14.207.99");
/**
* debug result
*
* @var array $debugResult
*/
private $debugResult = Array();
/**
* user agent
*
* @var string $userAgent
*/
private $userAgent = "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.2.1) Gecko/20021204";
/**
* cache directory
*
* @var string $cacheDir
*/
private $cacheDir = "/tmp";
/**
* cache 24hour in seconds
*
* @var integer $maxCacheAge
*/
private $maxCacheAge = 86400;
/**
* cache useage flag
*
* @var bool $useCache
*/
private $useCache = false;
/**
* debug status flag

Page 394 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

*
* @var bool $debugStatus
*/
private $debugStatus = false;
/**
* page rank
*
* @var integer $pageRank
*/
private $pageRank = -1;
/**
* cache expired flag
*
* @var bool $cacheExpired
*/
private $cacheExpired = false;
/**
* site url
*
* @var string $url
*/
private $url;

/**
* Constructs a Lib_PageRank object with given parameters
* also it will invoke page rank process
*
* @param string $type
* @param string $url
* @return Lib_PageRank
*/

public function Lib_PageRank($type,$url)


{
$this->type = $type;
$this->url=$url;

if($this->isValidCall())
{
if(strtolower($type)=='page_rank')
$this->getPageRank();
}
}

/**
* Check whether the function call is valid or not
*
* @return bool
*/

private function isValidCall()


{
if(strtolower($this->type)!='page_rank')
{
echo '<b>Component Error!<b> Invalid argument <i>type</i> - page_rank expected';
exit();
}
else if(empty($this->url))
{
echo '<b>Component Error!<b> Invalid argument <i>url</i> - url expected';
exit();
}
else if(is_numeric($this->url))
{
echo '<b>Component Error!<b> Invalid argument <i>url</i> - url must be string';

Page 395 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

exit();
}
return true;
}

/**
* get page rank for given site
*
* @return string
*/

private function getPageRank()


{
$url=$this->url;
$forceNoCache = false;
if(!eregi("^(https?://)?(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-]+@)?(([0-
9]{1,3}\.){3}[0-9]{1,3}|([0-9a-z_!~*'()-]+\.)*([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\.[a-z]{2,6})(:[0-9]{1,4})?((/?)|(/[0-
9a-z_!~*'().;?:@&=+$,%#-]+)+/?)$",$url))
{
$this->error = 1;
$this->debug['errinfo'] = array(1001=>'Not a valid URL format');
return false;
}
$total_exec_start = $this->microtimeFloat();
$result=array("",-1);
if (($url.""!="")&&($url.""!="http://"))
{
$this->debugRes("url", $url);
$this->cacheDir .= (substr($this->cacheDir,-1) != "/")? "/":"";
// check for protocol
$url_ = ((substr(strtolower($url),0,7)!="http://")? "http://".$url:$url);
$host = $this->googleDomains[mt_rand(0,count($this->googleDomains)-1)];
$target = "/search";
$querystring = sprintf("client=navclient-auto&ch=%s&features=Rank&q=%s",
$this->checkHash($this->hashURL($url_)),urlencode("info:".$url_));
$contents="";
$this->debugRes("host", $host);
$this->debugRes("query_string", $querystring);
$this->debugRes("user_agent", $this->userAgent);
$query_exec_start = $this->microtimeFloat();
if ($forceNoCache == true)
{
$this->debugRes("force_no_cache", "true");
}
elseif ($contents = $this->readCacheResult($url))
{
$this->debugRes("read_from_cache", "true");
}
else
{
$this->cacheExpired = true;
}
// let's get ranking
if (strlen(trim($contents)) == 0)
if (@function_exists("curl_init"))
{
// allways use curl if available for performance issues
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://".$host.$target."?".$querystring);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
curl_setopt($ch, CURLOPT_USERAGENT, $this->userAgent);
if (!($contents = trim(@curl_exec($ch))))
{
$this->debugRes("error","curl_exec failed");
}

Page 396 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

curl_close ($ch);
$this->debugRes("method", "curl");
}
else
{
$this->debugRes("error","curl not installed, trying to use fsockopen");
// use fsockopen as secondary method, to submit user agent
if ($socket = @fsockopen($host, "80", $errno, $errstr, 30))
{
$request = "GET $target?$querystring HTTP/1.0\r\n";
$request .= "Host: $host\r\n";
$request .= "User-Agent: ".$this->userAgent."\r\n";
$request .= "Accept-Language: en-us, en;q=0.50\r\n";
$request .= "Accept-Charset: ISO-8859-1, utf-8;q=0.66, *;q=0.66\r\n";
$request .= "Accept: text/xml,application/xml,application/xhtml+xml,";
$request .= "text/html;q=0.9,text/plain;q=0.8,video/x-mng,image/png,";
$request .= "image/jpeg,image/gif;q=0.2,text/css,*/*;q=0.1\r\n";
$request .= "Connection: close\r\n";
$request .= "Cache-Control: max-age=0\r\n\r\n";
stream_set_timeout ( $socket,10);
fwrite( $socket, $request );
$ret = '';
while (!feof($socket))
{
$ret .= fread($socket,4096);
}
fclose($socket);
$contents = trim(substr($ret,strpos($ret,"\r\n\r\n") + 4));
$this->debugRes("method", "fsockopen");
}
else
{
$this->debugRes("error","fsockopen failed, trying file_get_contents");
// this way could cause problems because the Browser Useragent is not set...
if ($contents =
trim(@file_get_contents("http://".$host.$target."?".$querystring)))
{
$this->debugRes("method", "file_get_contents");
}
else
{
$this->debugRes("error","file_get_contents failed");
}
}
}
if ($this->cacheExpired == true)
$this->updateCacheResult($url,$contents);
$this->debugRes("query_exec_time",$this->microtimeFloat() - $query_exec_start);
$result[0]=$contents;
// Rank_1:1:0 = 0
// Rank_1:1:5 = 5
// Rank_1:1:9 = 9
// Rank_1:2:10 = 10 etc
$p=explode(":",$contents);
if (isset($p[2])) $result[1]=$p[2];
}
if($result[1] == -1) $result[1] = 0;
$this->pageRank =(int)$result[1];
$this->debugRes("total_exec_time", $this->microtimeFloat() - $total_exec_start);
$this->debugRes("result", $result);

if($this->pageRank<10)
{
$res=(50-($this->pageRank*5));
$less='<td width='.$res.'></td>';
}

Page 397 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

$width=$this->pageRank*5;
$output.='<table border="0" cellspacing="0" id="table2">
<tr>
<td>
<p align="center"><b><font face="Arial" size="1">'.$this->pageRank.'/10</font></b></td>
</tr>
<tr>
<td>
<table border="0" cellpadding="2" cellspacing="0" id="table3" style="border: 1px solid
#000000" width="50" height="5">
<tr>
<td bgcolor="#008000" width='.$width.'></td>'.$less.'

</tr>
</table>
</td>
</tr>
</table>';

$this->result=$output;
return true;
}
/**
* debug result
*
* @return array
*/

private function debugRes($what,$sowhat)


{
if($this->debugStatus == true)
{
$debugbt = debug_backtrace();
$what = trim($what);
$sowhat = trim($sowhat) . " (Line : ".$debugbt[0]["line"].")";
if ($what == "error")
{
$this->debugResult[$what][] = $sowhat;
}
else
{
$this->debugResult[$what] = $sowhat;
}
}
}
/**
* find micro time
*
* @return flot
*/

private function microtimeFloat()


{
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}
/**
* cache result
*
* @return bool
*/

private function readCacheResult($url)


{
if ($this->useCache != true)
{

Page 398 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

return false;
}
if (!is_dir($this->cacheDir))
{
$this->debugRes("error","please create {$this->cacheDir}");
return false;
}
$urlp = parse_url($url);
$host_ = explode(".",$urlp["host"]);
$path_ = (strlen($urlp["query"])>0)? urlencode($urlp["path"].$urlp["query"]):"default";
$cache_file = $this->cacheDir;
for ($i = count($host_)-1;$i>=0;$i--)
{
$cache_file .= $host_[$i]."/";
}
$cache_file .= $path_;
$this->debugRes("cache_file", $cache_file);
if (file_exists($cache_file))
{
$mtime = filemtime($cache_file);
if (time() - $mtime > $this->maxCacheAge)
{
$this->debugRes("cache", "expired");
$this->cacheExpired = true;
return false;
}
else
{
$this->cacheExpired = false;
$this->debugRes("cache_age", time() - $mtime);
return file_get_contents($cache_file);
}
}
$this->debugRes("error","cache file not exists (reading)");
return false;
}
/**
* update cache result
*
* @return bool
*/

private function updateCacheResult($url,$content)


{
if ($this->useCache != true)
{
return false;
}
if (!is_dir($this->cacheDir))
{
$this->debugRes("error","please create {$this->cacheDir}");
return false;
}
$urlp = parse_url($url);
$host_ = explode(".",$urlp["host"]);
$path_ = (strlen($urlp["query"])>0)? urlencode($urlp["path"].$urlp["query"]):"default";
$cache_file = $this->cacheDir;
for ($i = count($host_)-1;$i>=0;$i--)
{
$cache_file .= $host_[$i]."/";
}
$cache_file .= $path_;
if (!file_exists($cache_file))
{
$this->debugRes("error","cache file not exists (writing)");
$cache_file_tmp = substr($cache_file,strlen($this->cacheDir));

Page 399 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

$cache_file_tmp = explode("/",$cache_file_tmp);
$cache_dir_ = $this->cacheDir;
for ($i = 0;$i<count($cache_file_tmp)-1;$i++)
{
$cache_dir_ .= $cache_file_tmp[$i]."/";
if (!file_exists($cache_dir_))
{
if (!@mkdir($cache_dir_,0777))
{
$this->debugRes("error","unable to create cache dir: $cache_dir_");
//break;
}
}
}
if (!@touch($cache_file)) $this->debugRes("error","unable to create cache file");
if (!@chmod($cache_file,0777)) $this->debugRes("error","unable to chmod cache file");
}
if (is_writable($cache_file))
{
if (!$handle = fopen($cache_file, 'w'))
{
$this->debugRes("error", "unable to open $cache_file");
return false;
}
if (fwrite($handle, $content) === FALSE)
{
$this->debugRes("error", "unable to write to $cache_file");
return false;
}
fclose($handle);
$this->debugRes("cached", date("Y-m-d H:i:s"));
return true;
}
$this->debugRes("error", "$cache_file is not writable");
return false;
}

/**
* convert a string to a 32-bit integer
*
* @return integer
*/

private function strToNum($Str, $Check, $Magic)


{
$Int32Unit = 4294967296; // 2^32
$length = strlen($Str);
for ($i = 0; $i < $length; $i++)
{
$Check *= $Magic;
//If the float is beyond the boundaries of integer (usually +/- 2.15e+9 = 2^31),
// the result of converting to integer is undefined
// refer to http://www.php.net/manual/en/language.types.integer.php
if ($Check >= $Int32Unit)
{
$Check = ($Check - $Int32Unit * (int) ($Check / $Int32Unit));
//if the check less than -2^31
$Check = ($Check < -2147483648) ? ($Check + $Int32Unit) : $Check;
}
$Check += ord($Str{$i});
}
return $Check;
}

/**
* genearate a hash for a url

Page 400 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

*
* @return bool
*/

private function hashURL($String)


{
$Check1 = $this->strToNum($String, 0x1505, 0x21);
$Check2 = $this->strToNum($String, 0, 0x1003F);
$Check1 >>= 2;
$Check1 = (($Check1 >> 4) & 0x3FFFFC0 ) | ($Check1 & 0x3F);
$Check1 = (($Check1 >> 4) & 0x3FFC00 ) | ($Check1 & 0x3FF);
$Check1 = (($Check1 >> 4) & 0x3C000 ) | ($Check1 & 0x3FFF);

$T1 = (((($Check1 & 0x3C0) << 4) | ($Check1 & 0x3C)) <<2 ) | ($Check2 & 0xF0F );
$T2 = (((($Check1 & 0xFFFFC000) << 4) | ($Check1 & 0x3C00)) << 0xA) | ($Check2 & 0xF0F0000 );

return ($T1 | $T2);


}

/**
* genearate a checksum for the hash string
*
* @return string
*/

private function checkHash($Hashnum)


{
$CheckByte = 0;
$Flag = 0;
$HashStr = sprintf('%u', $Hashnum) ;
$length = strlen($HashStr);

for ($i = $length - 1; $i >= 0; $i --)


{
$Re = $HashStr{$i};
if (1 === ($Flag % 2))
{
$Re += $Re;
$Re = (int)($Re / 10) + ($Re % 10);
}
$CheckByte += $Re;
$Flag ++;
}

$CheckByte %= 10;
if (0 !== $CheckByte)
{
$CheckByte = 10 - $CheckByte;
if (1 === ($Flag % 2) )
{
if (1 === ($CheckByte % 2))
{
$CheckByte += 9;
}
$CheckByte >>= 1;
}
}
return '7'.$CheckByte.$HashStr;
}

}
?>
Give spelling suggestion for English words using yahoo API
<?php
/**
* SpellingSuggestion

Page 401 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

*
* This class contains functions give spelling suggestion for English words using yahoo API.
*
* @package Lib_SpellingSuggestion
* @category Library

* @version 1.0
*/
// ------------------------------------------------------------------------
class Lib_SpellingSuggestion
{
/**
* Stores function type's name
*
* @var string $type
*/
private $type;
/**
* Flag for error
*
* @var boolean $error
*/
private $error;
/**
* Stores error numbers and description
*
* @var array $debug
*/
public $debug = array();
/**
* Stores the output
*
* @var bool $result
*/
public $result;
/**
* input word
*
* @var string $word
*/
private $word;
/**
* input query
*
* @var string $query
*/
private $query;
/**
* The Yahoo Spelling Suggestion API URL
*
* @var string $query
*/
private $request_url = 'http://search.yahooapis.com/WebSearchService/V1/spellingSuggestion';
/**
* xml, json or php (serialized PHP format)
*
* @var string $output
*/
private $output = 'php';
/**
* yahoo API id
*
* @var string $output
*/
private $appid = '';

Page 402 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

/**
* temp store output
*
* @var string $response
*/
private $response = '';

/**
* Constructs a Lib_SpellingSuggestion object with given parameters
* also it will invoke spelling suggestion process
*
* @param string $type
* @param string $word
* @param string $appid
* @return Lib_SpellingSuggestion
*/

public function Lib_SpellingSuggestion($type,$word,$appid = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")


{
$this->type = $type;
$this->word=$word;
$this->appid=$appid;

if($this->isValidCall())
{
if(strtolower($type)=='spell')
$this->getSuggestedWord();

}
}

/**
* Check whether the function call is valid or not
*
* @return bool
*/

private function isValidCall()


{
$count=strlen($this->number);
if(strtolower($this->type)!='spell')
{
echo '<b>Component Error!<b> Invalid argument <i>type</i> - spell expected';
exit();
}
else if(empty($this->word))
{
echo '<b>Component Error!<b> Invalid argument <i>word</i> - word expected';
exit();
}
else if(is_numeric($this->word))
{
echo '<b>Component Error!<b> Invalid argument <i>word</i> - word must be string';
exit();
}
else if(empty($this->appid))
{
echo '<b>Component Error!<b> Invalid argument <i>appid</i> - appid expected';
exit();
}
return true;
}

/**
* search the given word

Page 403 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

*
* @return bool
*/

private function search( $query )


{
$this->query = $query;
if ( $this->response = file_get_contents( $this->request_url . "?appid=" . urlencode( $this->appid ) .
"&output=" . urlencode( $this->output ) . "&query=" . urlencode( $this->query ) ) )
return true;
else
return false;
}

/**
* give spelling suggestion for english words
*
* @return string
*/

private function getSuggestedWord()


{
$this->query = $this->word;
$this->setOutput( 'php' );
if( $this->search( $this->query ) )
{
$this->result = unserialize( $this->response );
if ( isset( $this->result['ResultSet']['Result'] ) )
return $this->result= $this->result['ResultSet']['Result'];
else
return $this->result="no suggestion";
}
else
{
return $this->result="no suggestion";
}
}

/**
* set output keyword
*
* @return string
*/

private function setOutput( $output )


{
$this->output = $output;
}

}
?>
Conver the Text to MP3 format file
<?php
/**
* TextToMP3
*
* This class contains functions convert Text into MP3 format.
*
* @package Lib_TextToMP3
* @category Library

* @version 1.0
*/
// ------------------------------------------------------------------------
class Lib_TextToMP3

Page 404 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

{
/**
* Stores function type's name
*
* @var string $type
*/
private $type;
/**
* Flag for error
*
* @var boolean $error
*/
private $error;
/**
* Stores error numbers and description
*
* @var array $debug
*/
public $debug = array();
/**
* Stores the output
*
* @var audio file $result
*/
public $result;
/**
* convert text
*
* @var string $ctext
*/
private $ctext;
/**
* mp3 filename
*
* @var string $mp3name
*/
private $mp3name='';
/**
* Text file name
*
* @var string $txtfilename
*/
private $txtfilename='';
/**
* Text
*
* @var string $txt
*/
private $txt = '';
/**
* bufor
*
* @var string $bufor
*/
private $bufor = '';
/**
* error file name
*
* @var string $error_file
*/
private $error_file = 'error.audio';
/**
* Constructs a Lib_TextToMP3 object with given parameters
* also it will invoke text to mp3 process
*
* @param string $type

Page 405 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

* @param string $txtfilename


* @param string $mp3name
* @return Lib_TextToMP3
*/

public function Lib_TextToMP3($type,$txtfilename,$mp3name)


{
$this->type = $type;
$this->txtfilename = $txtfilename;
$this->mp3name = $mp3name;

if($this->isValidCall())
{
if(strtolower($type)=='speech')
$this->textConverter();
}
}

/**
* Check whether the function call is valid or not
*
* @return bool
*/

private function isValidCall()


{
if(strtolower($this->type)!='speech')
{
echo '<b>Component Error!<b> Invalid argument <i>type</i> - speech expected';
exit();
}
elseif(empty($this->txtfilename))
{
echo '<b>Component Error!<b> Invalid argument data type <i>txtfilename</i> - text file
name expected';
exit();
}
elseif(!file_exists($this->txtfilename))
{
echo '<b>Component Error!<b> Invalid argument data type <i>'.$this->txtfilename.'</i> -
text file not found';
exit();
}
elseif(empty($this->mp3name))
{
echo '<b>Component Error!<b> Invalid argument data type <i>mp3name</i> - mp3 file name
expected';
exit();
}
return true;
}

/**
* set the header and download the file
*
* @return bool
*/

private function textConverter()


{
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . date('r'));
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', FALSE);
header('Pragma: no-cache');

Page 406 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

header("Content-type: audio/mpeg");
header("Content-Disposition: attachment; filename=\"".$this->mp3name.".mp3\"");

//Read the contents from file


$filename =$this->txtfilename;
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
fclose($handle);

$text=$contents;
$this->setPath($text, 'eng');
$this->result= $this->printBufor();
return true;
}

/**
* set the say.expressivo.com url path
*
*/

private function setPath ($text, $language="eng")


{
$limit=strlen($text);
$limit = ($limit > 1500) ? 1500 : $limit;

$this->txt = @substr(trim(strip_tags($text)), 0, $limit);


$this->txt .= ' ';
$lang = 3;
for ($c=0; $c<strlen($this->txt); $c+=0)
{
$check = &$this->check($this->txt, $c);
$num_z = strlen($check);
if ($num_z == 0)
{
break;
if ($c == 0)
{
$this->error = 1;
}
}

$kod = &$this->codeweb ('http://say.expressivo.com/xivonaonline.php',


array("\n", "\r", "\t"),
array("", "", ""),
"P",

"xajax=generateVoice&xajaxr=".time()."&xajaxargs[]=pl&xajaxargs[]=".urlencode($check)."&xajaxargs[]=".$lang."&xaja
xargs[]=true&xajaxargs[]=1"
);

@preg_match_all('/<a(.*?)href="(.*?)".*?>.*?<\/a>/i', $kod, $linki);


@usleep(30);

if ($linki[2][0] == '')
{
$this->error = 1;
break;
}
else
{
$file_mp3[] = $linki[2][0];
}
$c += $num_z;
}
if (@is_array($file_mp3))

Page 407 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

{
foreach ($file_mp3 as $url)
{
if ($s = @fopen($url, "rb"))
{
while (!feof($s))
{
$this->bufor .= @fread($s,1024);
}
@fclose($s);
}
else
{
$this->error = 1;
}
}
}
else
{
$this->error = 1;
}
}
/**
* file content to bufor
*
* @return string
*/

private function printBufor ()


{
if ($this->error == 1)
{
if ($s = @fopen($this->error_file, "rb"))
{
while (!feof($s))
{
$this->bufor .= @fread($s,1024);
}
@fclose($s);
}
}
return $this->bufor;
}
/**
* set the curl function
*
* @return string
*/

private function codeweb ($url, $tag1="", $tag2="", $tryb="GET", $post="")


{
$ch = @curl_init();
if ($tryb != "GET")
{
@curl_setopt($ch, CURLOPT_POST, 1);
@curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
}
@curl_setopt($ch, CURLOPT_URL, $url);
@curl_setopt($ch, CURLOPT_HEADER, 0);
@curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
@curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
@curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = @curl_exec($ch);
if (@is_array($tag1) && @is_array($tag2))
{
$data = str_replace($tag1, $tag2, $data);

Page 408 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

}
if ($data == '') {return false;}
return $data;
}
/**
* text validation
*
* @return string
*/

private function check ($t, $o=0, $l=200)


{
if (strlen($t) > $l)
{
$t = preg_replace("/\s+(\S+)?$/", "", substr($t, $o, $l));
}
return $t;
}
}

?>
Create thermo graph
<?php
/**
* ThermoGraph
*
* This class contains functions create thermo graph.
*
* @package Lib_ThermoGraph
* @category Library

* @version 1.0
*/
// ------------------------------------------------------------------------
class Lib_ThermoGraph
{
/**
* Stores function type's name
*
* @var string $type
*/
private $type;
/**
* Flag for error
*
* @var boolean $error
*/
private $error;
/**
* Stores error numbers and description
*
* @var array $debug
*/
public $debug = array();
/**
* Stores the output
*
* @var bool $result
*/
public $result;
/**
* current value
*
* @var integer $currentValue
*/

Page 409 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

private $currentValue;
/**
* goal value
*
* @var integer $goalValue
*/
private $goalValue;
/**
* image width
*
* @var integer $imgWidth
*/
private $imgWidth;
/**
* image height
*
* @var integer $imgHeight
*/
private $imgHeight;

/**
* Constructs a Lib_ThermoGraph object with given parameters
* also it will invoke thermo graph process
*
* @param string $type
* @param integer $currentValue
* @param integer $goalValue
* @param integer $imgWidth
* @param integer $imgHeight
* @return Lib_ThermoGraph
*/

public function Lib_ThermoGraph($type,$currentValue,$goalValue,$imgWidth = 60,$imgHeight=150)


{
$this->type = $type;
$this->currentValue = $currentValue;
$this->goalValue = $goalValue;
$this->imgWidth = $imgWidth;
$this->imgHeight = $imgHeight;

if($this->isValidCall())
{
if(strtolower($type)=='thermo')
$this->thermo();
}
}

/**
* Check whether the function call is valid or not
*
* @return bool
*/
private function isValidCall()
{
if(strtolower($this->type)!='thermo')
{
echo '<b>Component Error!<b> Invalid argument <i>type</i> - thermo expected';
exit();
}
else if(empty($this->currentValue))
{
echo '<b>Component Error!<b> Invalid argument <i>currentValue</i> - current value
expected';
exit();
}
else if(!is_numeric($this->currentValue))

Page 410 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

{
echo '<b>Component Error!<b> Invalid argument <i>currentValue</i> - current value must
be numeric';
exit();
}
else if(empty($this->goalValue))
{
echo '<b>Component Error!<b> Invalid argument <i>goalValue</i> - goal value expected';
exit();
}
else if(!is_numeric($this->goalValue))
{
echo '<b>Component Error!<b> Invalid argument <i>goalValue</i> - goal value must be
numeric';
exit();
}
else if($this->currentValue > $this->goalValue)
{
echo '<b>Component Error!<b> Invalid argument <i>currentValue</i> - current value must
be less than goal value';
exit();
}
else if(empty($this->imgWidth))
{
echo '<b>Component Error!<b> Invalid argument <i>imgWidth</i> - image width expected';
exit();
}
else if(!is_numeric($this->imgWidth))
{
echo '<b>Component Error!<b> Invalid argument <i>imgWidth</i> - image width must be
numeric';
exit();
}
else if(empty($this->imgHeight))
{
echo '<b>Component Error!<b> Invalid argument <i>imgHeight</i> - image height expected';
exit();
}
else if(!is_numeric($this->imgHeight))
{
echo '<b>Component Error!<b> Invalid argument <i>imgHeight</i> - image height must be
numeric';
exit();
}
return true;
}

/**
* This function create thermo graph
*
* @return image
*/

private function thermo()


{
$current=$this->currentValue;
$goal=$this->goalValue;
$width=$this->imgWidth;
$height=$this->imgHeight;
$font=1;
$bar = 0.50;
// create the image
$image = ImageCreate($width, $height);
$bg = ImageColorAllocate($image,255,255,255 );
$fg = ImageColorAllocate($image,255,0,0);
$tx = ImageColorAllocate($image,0,0,0);

Page 411 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

// Build background
ImageFilledRectangle($image,0,0,$width,$height,$bg);

// Build bottom bulb


imagearc($image, $width/2, $height-($width/2), $width, $width, 0, 360, $fg);
ImageFillToBorder($image, $width/2, $height-($width/2), $fg, $fg);

// Build "Bottom level


ImageFilledRectangle($image,($width/2)-(($width/2)*$bar),$height-
$width,($width/2)+(($width/2)*$bar),$height-($width/2),$fg );
// Draw Top Border
ImageRectangle( $image,($width/2)-(($width/2)*$bar),0,($width/2)+(($width/2)*$bar),$height-
$width,$fg);
// Fill to %
ImageFilledRectangle( $image,($width/2)-(($width/2)*$bar),($height-$width) * (1-
($current/$goal)),($width/2)+(($width/2)*$bar),$height-$width,$fg );
// Add tic's
for( $k=25; $k<100; $k+=25 )
{
ImageFilledRectangle( $image,($width/2)+(($width/2)*$bar) -5,($height-$width) - ($height-
$width)*($k/100) -1,
($width/2)+(($width/2)*$bar) -1,($height-$width) - ($height-
$width)*($k/100) +1, $tx );

ImageString($image, $font,($width/2)+(($width/2)*$bar) +2,


(($height-$width) - ($height-$width)*($k/100)) - (ImageFontHeight($font)/2),
sprintf( "%2d", $k),$tx);
}
// Add % over BULB
$pct = sprintf( "%d%%", ($current/$goal)*100 );

ImageString( $image, $font+2, ($width/2)-((strlen($pct)/2)*ImageFontWidth($font+2)),


($height-($width/2))-(ImageFontHeight($font+2) / 2),
$pct, $bg);

header("content-type: image/png");
imagepng($image);
}

}
?>
Working with yahoo travel api
<?php
/**
* Travel
*
* This class contains functions to work with yahoo travel api.
*
* @package Lib_Travel
* @category Library

* @version 1.0
*/
// ------------------------------------------------------------------------
class Lib_Travel
{
/**
* Stores function type's name
*
* @var string $type
*/
private $type;
/**
* Stores the output

Page 412 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

*
* @var string $result
*/
public $result;
/**
* Input tags
*
* @var string $category
*/
private $category;
/**
* Input application id
*
* @var string $appId
*/
private $appId;

/**
* Constructs a Lib_Travel object with given parameters
* also it will invoke Travel Item process
*
* @param string $type
* @param string $category
* @param string $appId
* @return Lib_Travel
*/

public function Lib_Travel($type,$category,$appId)


{
$this->type = $type;
$this->category = $category;
$this->appId = $appId;

if($this->isValidCall())
{
if(strtolower($type)=='travel')
$this->feedRead();

}
}

/**
* Check whether the function call is valid or not
*
* @return bool
*/
private function isValidCall()
{
if(strtolower($this->type)!='travel')
{
echo '<b>Component Error!<b> Invalid argument <i>type</i> - travel expected';
exit();
}
else if(empty($this->category))
{
echo '<b>Component Error!<b> Invalid argument <i>category</i> - category expected';
exit();
}
else if(empty($this->appId))
{
echo '<b>Component Error!<b> Invalid argument <i>appId</i> - appId expected';
exit();
}
return true;
}

Page 413 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

/**
* This function get the travel item list depend upon the given category ex:paris
*
* @return string $result
*/

private function feedRead()


{
$key=$this->appId;
$category=str_replace(" ","%20",$this->category);
$query = $category;
$SafeQuery = urlencode($query); // Make the query URL-friendly
$endpoint = 'http://travel.yahooapis.com/TripService/V1.1/tripSearch'; // URL to call
$responseEncoding = 'XML'; // Type of response we want back
$apicall ="$endpoint?appid=$key&query=$SafeQuery";
$resp = simplexml_load_file($apicall);
$res=$this->feedConversion($resp);
$this->result=$res;
return true;
}

/**
* This function split the each category feed
*
* @return string $res
*/

private function feedConversion($feed)


{
foreach($feed->Result as $item)
{
$re['latitude']=(string)$item->Geocode->Latitude;
$re['longitude']=(string)$item->Geocode->Longitude;
$re['url']=(string)$item->Url;
$re['title']=(string)$item->Title;
$re['date']=(string)$item->CreateDate;
$re['author']=(string)$item->Author;
$res[]=$re;
}
if(isset($res))
return $res;
else
return "No Results";
}

}
?>
Get the searching result from Wikipedia
<?php
/**
* Wikipedia
*
* This class contains functions shows wikipedia search.
*
* @package Lib_Wikipedia
* @category Library

* @version 1.0
*/
// ------------------------------------------------------------------------
class Lib_Wikipedia
{
/**
* Stores function type's name
*

Page 414 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

* @var string $type


*/
private $type;
/**
* Flag for error
*
* @var boolean $error
*/
private $error;
/**
* Stores error numbers and description
*
* @var array $debug
*/
public $debug = array();
/**
* Stores the output
*
* @var bool $result
*/
public $result;
/**
* search title
*
* @var string $title
*/
private $title;
/**
* callback status
*
* @var bool $callback
*/
private $callback = false;

/**
* Constructs a Lib_Wikipedia object with given parameters
* also it will invoke wikipedia search process
*
* @param string $type
* @param string $title
* @return Lib_Wikipedia
*/

public function Lib_Wikipedia($type,$title)


{
$this->type = $type;
$this->title=$title;

if($this->isValidCall())
{
if(strtolower($type)=='wiki')
$this->search();

}
}

/**
* Check whether the function call is valid or not
*
* @return bool
*/

private function isValidCall()


{
if(strtolower($this->type)!='wiki')
{

Page 415 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

echo '<b>Component Error!<b> Invalid argument <i>type</i> - wiki expected';


exit();
}
else if(empty($this->title))
{
echo '<b>Component Error!<b> Invalid argument <i>title</i> - title expected';
exit();
}
else if(is_numeric($this->title))
{
echo '<b>Component Error!<b> Invalid argument <i>title</i> - title must be string';
exit();
}
return true;
}

/**
* get the result from wikipedia site
*
* @return string
*/

private function search ()


{
$sourceurl = 'http://en.wikipedia.org/wiki/'; # This URL needs adjusting sometimes.
$pathfromroot = substr( $_SERVER['REQUEST_URI'], 0, strpos( $_SERVER['REQUEST_URI'], "?" ) );
$title_wiki = $_POST['title'];
if ($title_wiki == "")
$title_wiki = $this->title;
$nicetitle = str_replace( "_", " ", stripslashes( $title_wiki ) );

ob_start("callback");
$out= $this -> get( $sourceurl . $title_wiki );
if($out)
{
$buffer =$out;
# Separate the article content
$buffer = substr( $buffer, strpos( $buffer, '<!-- start content -->' ) );
$buffer = substr( $buffer, 0, strpos( $buffer, '<div class="printfooter">' ) );
# Replace relative links (use another wiki server)
$buffer = str_replace( '"/w/skin', '"http://en.wikipedia.org/w/skin', $buffer );
$buffer = str_replace( '"/skins', '"http://en.wikipedia.org/skins', $buffer );
# Replace relative links (use this server)
$buffer = str_replace( '"/wiki/', '"' . $pathfromroot . '?title=', $buffer );
# Remove edit links
$buffer = str_replace( ">edit<", "><", $buffer );
$buffer = str_replace( "[<", "<", $buffer );
$buffer = str_replace( ">]", ">", $buffer );
$buffer = str_replace( 'href="/w/index.php?', 'target="_blank" href="http://en.wikipedia.org/w/index.php?', $buffer
); # These are typically links to non-existent pages, so the Wikipedia edit page has to open.
if ( $buffer <> '' )
{
$buffer = '<table width=100% cellspacing=0 cellpadding=1 bgcolor="#EEEEEE" border=0><tr><td>
<p><font size="+2"><b>' . $nicetitle . '</b>&nbsp;<sup><a
href="http://en.wikipedia.org/w/index.php?title=' . $title_wiki . '&action=edit" title="Edit this article at Wikipedia"
target="_blank"><font color="red" size="-1">edit</font></a></sup></font>
<br><i><small>extracted from </small><a href="http://www.wikipedia.org"
target="_blank"><small>Wikipedia, the Free Encyclopedia</small></a></i></td>
<td><form method="post"><br><input type="text" name="title" size="30">&nbsp;<input
type="submit" value="search"></form></td>
<td></td></tr></table><p>' . $buffer;
}
else
{
$buffer = '<p>Unfortunately, no content could be extracted!
<p><a href="javascript:history.go(-1)">Return to the previous page</a> or consult the <a

Page 416 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

target="_blank" href="' . $sourceurl . $title_wiki . '">Wikipedia article on "' . $nicetitle . '"</a>.';


}
$output= $buffer;
}

ob_end_flush();
$this->result=$output;
return true;
}

/**
* create search panel
*
* @return string
*/

private function callback( $buffer )


{
global $nicetitle;
global $title_wiki;
global $sourceurl;
# Separate the article content
$buffer = substr( $buffer, strpos( $buffer, '<!-- start content -->' ) );
$buffer = substr( $buffer, 0, strpos( $buffer, '<div class="printfooter">' ) );
# Replace relative links (use another wiki server)
$buffer = str_replace( '"/w/skin', '"http://en.wikipedia.org/w/skin', $buffer );
$buffer = str_replace( '"/skins', '"http://en.wikipedia.org/skins', $buffer );
# Replace relative links (use this server)
$buffer = str_replace( '"/wiki/', '"' . $pathfromroot . '?title=', $buffer );
# Remove edit links
$buffer = str_replace( ">edit<", "><", $buffer );
$buffer = str_replace( "[<", "<", $buffer );
$buffer = str_replace( ">]", ">", $buffer );
$buffer = str_replace( 'href="/w/index.php?', 'target="_blank" href="http://en.wikipedia.org/w/index.php?', $buffer
); # These are typically links to non-existent pages, so the Wikipedia edit page has to open.
if ( $buffer <> '' )
{
$buffer = '<table width=100% cellspacing=0 cellpadding=1 bgcolor="#EEEEEE" border=0><tr><td>
<p><font size="+2"><b>' . $nicetitle . '</b>&nbsp;<sup><a
href="http://en.wikipedia.org/w/index.php?title=' . $title_wiki . '&action=edit" title="Edit this article at Wikipedia"
target="_blank"><font color="red" size="-1">edit</font></a></sup></font>
<br><i><small>extracted from </small><a href="http://www.wikipedia.org"
target="_blank"><small>Wikipedia, the Free Encyclopedia</small></a></i></td>
<td><form method="get"><br><input type="text" name="title" size="30">&nbsp;<input
type="submit" value="search"></form></td>
<td></td></tr></table><p>' . $buffer;
}
else
{
$buffer = '<p>Unfortunately, no content could be extracted!
<p><a href="javascript:history.go(-1)">Return to the previous page</a> or consult the <a
target="_blank" href="' . $sourceurl . $title_wiki . '">Wikipedia article on "' . $nicetitle . '"</a>.';
}
return $buffer;
}

/**
* call curl request
*
*/

private function doRequest($method, $url, $vars)


{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
#curl_setopt($ch, CURLOPT_HEADER, 1);

Page 417 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);


#curl_setopt($ch, CURLOPT_USERAGENT, 'User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)');
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt');
curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookie.txt');
if ($method == 'POST')
{
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $vars);
}
$data = curl_exec($ch);
curl_close($ch);
if ($data)
{
if ($this->callback)
{
$callback = $this->callback;
$this->callback = false;
return call_user_func($callback, $data);
}
else
{
return $data;
}
}
else
{
return curl_error($ch);
}
}
/**
* get request
*
*/

private function get($url)


{
return $this->doRequest('GET', $url, 'NULL');
}
/**
* post request
*
*/

private function post($url, $vars)


{
return $this->doRequest('POST', $url, $vars);
}
}
?>
Working with yahoo query API
<?php
/**
* YahooQuery
*
* This class contains functions to work with yahoo query api.
*
* @package Lib_YahooQuery
* @category Library

* @version 1.0
*/
// ------------------------------------------------------------------------
class Lib_YahooQuery

Page 418 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

{
/**
* Stores function type's name
*
* @var string $type
*/
private $type;
/**
* Stores the output
*
* @var string $result
*/
public $result;
/**
* Input tags
*
* @var string $category
*/
private $category;
/**
* Input appid
*
* @var string $appId
*/
private $appId;

/**
* Constructs a Lib_YahooQuery object with given parameters
* also it will invoke yahoo query Item process
*
* @param string $type
* @param string $category
* @param string $appId
* @return Lib_YahooQuery
*/

public function Lib_YahooQuery($type,$category,$appId)


{
$this->type = $type;
$this->category = $category;
$this->appId = $appId;

if($this->isValidCall())
{
if(strtolower($type)=='query')
$this->feedRead();

}
}

/**
* Check whether the function call is valid or not
*
* @return bool
*/
private function isValidCall()
{
if(strtolower($this->type)!='query')
{
echo '<b>Component Error!<b> Invalid argument <i>type</i> - query expected';
exit();
}
else if(empty($this->category))
{
echo '<b>Component Error!<b> Invalid argument <i>category</i> - category expected';
exit();

Page 419 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

}
else if(empty($this->appId))
{
echo '<b>Component Error!<b> Invalid argument <i>appId</i> - appId expected';
exit();
}
return true;
}

/**
* This function get the yahoo query item list depend upon the given category ex:car
*
* @return string $result
*/

private function feedRead()


{
$key=$this->appId;
$category=str_replace(" ","%20",$this->category);
$query = $category;
$SafeQuery = urlencode($query); // Make the query URL-friendly
$endpoint = 'http://answers.yahooapis.com/AnswersService/V1/questionSearch'; // URL to call
$responseEncoding = 'XML'; // Type of response we want back
$apicall ="$endpoint?appid=$key&query=$SafeQuery";
$resp = simplexml_load_file($apicall);
$res=$this->feedConversion($resp);
$this->result=$res;
return true;
}

/**
* This function split the each category feed
*
* @return string $res
*/

private function feedConversion($feed)


{
foreach($feed->Question as $item)
{
$re['title']=(string)$item->Subject;
$re['content']=(string)$item->Content;
$re['date']=(string)$item->Date;
$re['link']=(string)$item->Link;
$re['user']=(string)$item->UserId;
$re['userPhotoUrl']=(string)$item->UserPhotoURL;
$re['answers']=(string)$item->NumAnswers;
$re['comment']=(string)$item->NumComments;
$res[]=$re;
}
if(isset($res))
return $res;
else
return "No Results";
}

}
?>

Page 420 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

How to use the above mentioned 33 library tracks (callable codes)


<?php include_once('../classes/Lib/Date.php');
include_once('../classes/Lib/Advertisement.php');
include_once('../classes/Lib/Chart.php');
include_once('../classes/Lib/Zip.php');
include_once('../classes/Lib/AddressBook.php');
include_once('../classes/Lib/TagClouds.php');
include_once('../classes/Lib/Email.php');
include_once('../classes/Lib/Paging.php');
include_once('../classes/Lib/Category.php');
include_once('../classes/Lib/Localization.php');
//include_once('../classes/Lib/TagPost.php');
include_once('../classes/Lib/TagSearch.php');
include_once('../classes/Lib/upload.php');
include_once('../classes/Lib/Photos.php');
include_once('../classes/Lib/Cryption.php');
//include_once('../classes/Lib/TagSearchNew.php');
include_once('../classes/Lib/ImageFunctions.php');
include_once('../classes/Lib/Parser.php');
include_once('../classes/Lib/Converter.php');
include_once('../classes/Lib/Captcha.php');
include_once('../classes/Lib/Inbox.php');
include_once('../classes/Lib/Country.php');
include_once('../classes/Lib/BarChart.php');
include_once('../classes/Lib/Poll.php');
include_once('../classes/Lib/Answer.php');
include_once('../classes/Lib/Blog.php');
include_once('../classes/Lib/FlashNews.php');
include_once('../classes/Lib/Feedback.php');
include_once('../classes/Lib/Events.php');
include_once('../classes/Lib/Faq.php');
include_once('../classes/Lib/Articles.php');
include_once('../classes/Lib/SimpleRegistration.php');
include_once('../classes/Lib/Contact.php');
include_once('../classes/Lib/Career.php');
include_once('../classes/Lib/TellFriend.php');
include_once('../classes/Lib/YahooQuery.php');
include_once('../classes/Lib/Travel.php');
//include_once('../classes/Lib/Library.php');
include_once('../classes/Lib/Issue.php');
include_once('../classes/Lib/Paypal.php');
include_once('../classes/Lib/Egold.php');
include_once('../classes/Lib/MoneyBooker.php');
include_once('../classes/Lib/AlertPay.php');
include_once('../classes/Lib/SafePay.php');
include_once('../classes/Lib/Liberty.php');
include_once('../classes/Lib/Pecunix.php');
include_once('../classes/Lib/Stormpay.php');
include_once('../classes/Lib/GoogleMap.php');
//include_once('../classes/Lib/Arabic.php');
include_once('../classes/Lib/ChatGrammarCorrector.php');
include_once('../classes/Lib/RandomPassword.php');

Page 421 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

include_once('../classes/Lib/ImdbMovie.php');
include_once('../classes/Lib/Prime.php');
include_once('../classes/Lib/ConvertRoman.php');
include_once('../classes/Lib/AsciiArt.php');
include_once('../classes/Lib/ArrayDiagram.php');
include_once('../classes/Lib/DownloadImage.php');
include_once('../classes/Lib/ISDCode.php');
include_once('../classes/Lib/BackupDB.php');
include_once('../classes/Lib/MoonPhase.php');
//include_once('../classes/Lib/Sms.php');
include_once('../classes/Lib/LoveCalculator.php');
include_once('../classes/Lib/TagRemover.php');
include_once('../classes/Lib/Byte.php');
include_once('../classes/Lib/ArraySort.php');
include_once('../classes/Lib/Temperature.php');
include_once('../classes/Lib/NumericWords.php');
include_once('../classes/Lib/SpellingSuggestion.php');
include_once('../classes/Lib/GoogleTranslate.php');
include_once('../classes/Lib/SiteInfo.php');
include_once('../classes/Lib/DailyJoke.php');
include_once('../classes/Lib/PageRank.php');
include_once('../classes/Lib/MusicDownload.php');
include_once('../classes/Lib/CurrencyConverter.php');
include_once('../classes/Lib/Fibonacci.php');
include_once('../classes/Lib/Rainbow.php');
include_once('../classes/Lib/SmartGoogleMap.php');
include_once('../classes/Lib/LinkText.php');
include_once('../classes/Lib/FileLine.php');
include_once('../classes/Lib/LinearDistance.php');
//include_once('../classes/Lib/ThumbImage.php');
//include_once('../classes/Lib/ThumbImage_W.php');
include_once('../classes/Lib/BodyMassIndex.php');
include_once('../classes/Lib/Wikipedia.php');
include_once('../classes/Lib/ViewSource.php');
include_once('../classes/Lib/ViewText.php');
include_once('../classes/Lib/FileText.php');
include_once('../classes/Lib/Installment.php');
include_once('../classes/Lib/ArraySumRecursive.php');
include_once('../classes/Lib/WordCount.php');
include_once('../classes/Lib/SlideShow.php');
include_once('../classes/Lib/WeblogsRSS.php');
include_once('../classes/Lib/HitCounter.php');
include_once('../classes/Lib/BlocksImage.php');
include_once('../classes/Lib/AlexaPageRank.php');
include_once('../classes/Lib/BarCode.php');
//include_once('../classes/Lib/Unicode.php');
include_once('../classes/Lib/TextTranslate.php');
include_once('../classes/Lib/TextToMP3.php');
include_once('../classes/Lib/GIFDecoder.php');
include_once('../classes/Lib/ImageSplitter.php');
include_once('../classes/Lib/MergeImages.php');
include_once('../classes/Lib/DailyCartoon.php');

Page 422 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

//include_once('../classes/Lib/WinDrive.php');echo 'dfg';exit;
include_once('../classes/Lib/HtmlToDoc.php');
include_once('../classes/Lib/SplitFile.php');
include_once('../classes/Lib/SmartMusicDownload.php');
include_once('../classes/Lib/AsciiEncode.php');
include_once('../classes/Lib/BibleVerse.php');
include_once('../classes/Lib/ImageToPhp.php');
include_once('../classes/Lib/GradientImage.php');
include_once('../classes/Lib/PrintLogo.php');
include_once('../classes/Lib/FolderQuota.php');
include_once('../classes/Lib/StereoImages.php');
include_once('../classes/Lib/AutoFill.php');
include_once('../classes/Lib/GeoIP.php');
include_once('../classes/Lib/HexaColor.php');
include_once('../classes/Lib/BaseConversion.php');
include_once('../classes/Lib/ThermoGraph.php');
include_once('../classes/Lib/ImageSlicer.php');
include_once('../classes/Lib/DailyAstroImage.php');
include_once('../classes/Lib/PdfMail.php');
include_once('../classes/Lib/ScreenShot.php');
include_once('../classes/Lib/OnlineEditor.php');
include_once('../classes/Lib/MakeCartoon.php');
include_once('../classes/Lib/Pop3Mail.php');
include_once('../classes/Lib/MirrorImage.php');
include_once('../classes/Lib/WaterImage.php');
//include_once('../classes/Lib/ImageResize.php');
//$obj=new
Lib_ImageResize('resize','images/sony_ericsson_w960_zoom.jpg','images1','new_sony','jpg',200,
100);
//$obj=new Lib_WaterImage('water','images1/428226.gif','images','new428226');
//$obj=new Lib_MirrorImage('mirror','images/75.jpg','images1','newvi','jpg');
//$obj=new
Lib_Pop3Mail('pop3','[email protected]','test1234','[email protected]','mail.sec
ureserver.net','images/','pop3','110');
//$obj=new Lib_MakeCartoon('cartoon','images/428226.jpg','images','newste','jpg');
//$obj=new Lib_OnlineEditor('editor','tab/Register.html');
//$obj=new Lib_ScreenShot('screen_shot','http://www.yahoo.com');
//$obj=new Lib_PdfMail('pdfmail','[email protected]','stephen','hai this is a test
mail');
//$obj=new Lib_DailyAstroImage('astro');
//$obj=new Lib_ImageSlicer('image_slice','images/Sunset.jpg',4,4,'images1/');
//$obj=new Lib_ThermoGraph('thermo',75,100);
//$obj=new Lib_BaseConversion('base',10,10,2);
//$obj=new Lib_HexaColor('hexa_color');
//$obj=new Lib_GeoIP('geoip','114.30.47.10');
$db=mysql_connect('localhost','root','');
mysql_select_db('sql_tutorial',$db);
$sql="SELECT img_path from advertisement";
//$db_event->query($sql);
$result=mysql_query($sql);
$i=0;
while($fetch = mysql_fetch_row($result))

Page 423 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

{
//$n=$fetch[0];
// $s=$fetch[1];
// $new1=$n.','.$s;
// $records[$i] = $new1;
// $i++;
//$records[0] = $fetch;
$records[$i]=$fetch;
//$records[$i]='<a href="www.google.com">'.$fetch[0].'</a>';
$i++;
}//echo '<pre>';print_r($records);
//for($j=0;$j<count($records);$j++)
//$options[$j,$j] = $records[$j][0],$records[$j][1];
//print_r($options);
//exit;
//$obj=new Lib_AutoFill('autofill',"txtAuto",$records,50);
//$obj=new
Lib_StereoImages('stereoimage',"images/Camera3.jpg","images/Camera6.jpg","images/","stereo"
,"png");
//$obj=new Lib_FolderQuota('quota','tab/',450000,'Tab Folder Space');
//$obj=new
Lib_PrintLogo('logo','images/Sunset.jpg','images/logo.png','images1/','sunlogo');
//$obj=new Lib_GradientImage('gradient','#FFFA94','E35A28',100,200,200);
//$obj=new Lib_ImageToPhp('img_php','t/','test1','tab/');
//$obj=new Lib_BibleVerse('verse');
//$obj=new Lib_AsciiEncode('asciiencode','hello','encode','0');
//$obj=new Lib_SmartMusicDownload('music_download','music/');
//$obj=new Lib_SplitFile('split_file','tab/aj_doc.doc','tab/',5);
//$obj=new Lib_HtmlToDoc('html_doc','tab/Register.html','reg_doc1','tab/');
//$obj=new Lib_HtmlToDoc('url_doc','http://ajdf.ajsquare.com','aj_doc','tab/');
//$obj=new Lib_WinDrive('windrive');
//$obj=new Lib_DailyCartoon('cartoon');
//$obj=new
Lib_MergeImages("mergeimage","images/dhas1.jpg","images/sriram1.jpg","images/","combine","
jpg","up");
//$obj=new Lib_ImageSplitter('splitter','images/Sunset.jpg','images/');
//$obj=new Lib_GIFDecoder('gifdecode','images/dock.gif','images/');
//$obj=new Lib_TextToMP3('speech','tab/cookies.txt','music');
//$obj = new Lib_TextTranslate('translation','Fri 10-10-2009','en','no');
//$obj = new Lib_Unicode('unicode');
//$obj = new Lib_BarCode('barcode',123456789345,'Fonts/ARIAL.TTF');
//$obj = new Lib_AlexaPageRank('alexa_rank','www.ajsquare.com');
//$obj = new Lib_BlocksImage('block_image','images/deva1.jpg');
//$obj = new Lib_HitCounter('hitcounter','tab/hit.txt');
//$obj = new Lib_WeblogsRSS('weblogs_rss');
//$obj = new Lib_SlideShow('slideshow','images/',100,100);
//$obj = new Lib_WordCount('word_count','This class contains functions count the number
of words in a text string');
$array = array(10, 20, 5,
array(5, 2, 3,
array(5, 3,
array(2, 10,

Page 424 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

array(19, 1)
),3
), 2, 7
), 3
);
//$obj = new Lib_ArraySumRecursive('array_sum',$array);
//$obj = new Lib_Installment('installment',1234.40,4);
//$obj = new Lib_FileText('filetext','css/expand.css');
//$obj = new Lib_ViewText('viewtext','www.google.com');
//$obj = new
Lib_ViewSource('viewsource','http://www.tipsgaming.com/odds/odds_html.asp?status=1&hours=
&time=');
//$obj = new Lib_Wikipedia('wiki','asp.net');
//$obj = new Lib_BodyMassIndex('index',1.98,78);
//$obj = new Lib_ThumbImage('thumb',"images/nokia-tube-press.jpg",100);
//$obj = new Lib_ThumbImage('thumb',"images/nokia-tube-press.jpg",'images1',100);
//for width
//$obj = new Lib_LinearDistance('linear',11,3,5,7);
//$obj = new Lib_FileLine('line','../templates/home.php');
//$obj = new Lib_LinkText('text','<a href="http://www.phpclasses.org" class="something"
id="link_id" >Url Text Link Here</a>');
//$obj = new Lib_SmartGoogleMap('smart_googlemap');
//$obj = new Lib_Rainbow('rainbow','hai, how are you. how is your job.');
//$obj = new Lib_Unicode('unicode');
//$obj = new Lib_Fibonacci('fibonacci',1234);
//$obj = new Lib_BarCode('barcode',123456789012,'Fonts/ARIAL.TTF');
//$obj=new Lib_CurrencyConverter('currency','usd', 'cad', '5.70');
//$obj=new Lib_MusicDownload('music_download','music/');
//$obj=new Lib_PageRank('page_rank','www.ajsquare.com');
//$obj=new Lib_DailyJoke('joke');
//$obj=new Lib_SiteInfo('site_link','http://www.phpclasses.org/');
//$obj=new Lib_SiteInfo('site_image','http://www.phpclasses.org/');
//$obj=new Lib_GoogleTranslate('translation','http://www.phpclasses.org','en','es');
//$obj=new Lib_SpellingSuggestion('spell','stephn');
//$obj=new Lib_NumericWords('numeric_word',99999999);
//$obj=new Lib_Temperature('fahrenheit',98);
//$obj=new Lib_Temperature('celsius',208.4);
$arr=array('she','he','it');
//$obj=new Lib_ArraySort('sort',$arr);
//$obj=new Lib_Byte('byte',242343);
//$obj=new Lib_TagRemover('tag_remove','<xml><head>xgf</head><body>hello h r
u</xml>');
//$obj=new Lib_LoveCalculator('love','stephen','jesus');
//$obj=new
Lib_Sms('sms','stejes2000','ste2000','stephen',919994303022,'hai','4054558877313721682');
//$obj=new Lib_MoonPhase('moon','12/09/2007');

//$obj=new Lib_BackupDB('backup','root','','localhost','sql_tutorial','images/');
//$obj=new Lib_ISDCode('select_all');
//$obj=new Lib_ISDCode('select_single',3);

//$obj=new Lib_DownloadImage('download','jesus',10,350,'images/');

Page 425 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

$arr = array('this' => array('is' => array('just' => array('a'),


'test'),
'to' => array('test' => array('my',
'new' => array('class',
'called'),
'diagram')),
'graph'));

$arr1 = array('sdg','sdfg');

//$obj=new Lib_ArrayDiagram('diagram',$arr);
//$obj=new Lib_AsciiArt('asciiart','images/01.jpg',3);
//$obj=new Lib_ConvertRoman('roman',10);
//$obj=new Lib_Prime('prime',69);
//$obj=new Lib_ImdbMovie('movie','terminator');
//$obj = new Lib_AddressBook('gmail','durai010181','american','a.php','hai','how r u');
//$obj = new Lib_RandomPassword('password',9);
//$obj = new Lib_ChatGrammarCorrector('grammer',"thats gr8!! how r u?!?!? i am fine");
$arr=array('I go to the market on Monday',
'How much tea do you want',
'How many tomatoes do you want',
'They walk in the mountains at the weekend',
'Does a secretary type letter',
'They are good players',
'They sometimes play basketball at the sports hall',
'Did he leave his bag in front of the house','how are you');
//$obj = new Lib_Arabic('arabic',$arr);
$obj=new Lib_GoogleMap('googlemap','ABQIAAAAoM-
kEW8yHxWwveOZAouVXhTkQdzC1XuexHlQDsWmu58XcfHJ8xQB-
xtA9nt_7NDWTsfJfHHxosdNZg','madurai');
//$obj=new
Lib_Stormpay('stormpay','[email protected]','1000','success.php','failure.php','index.php');
//$obj=new
Lib_Pecunix('pecunix','[email protected]','1000','success.php','failure.php');
//$obj=new Lib_Liberty('liberty','12345','1000','success.php','failure.php');
//$obj=new Lib_SafePay('safepay','12345','12345','1000','success.php','failure.php');
//$obj=new Lib_AlertPay('alertpay','12345','1000','success.php','failure.php');
//$obj=new
Lib_MoneyBooker('booker','[email protected]','1000','success.php','failure.php');
//$obj=new
Lib_Egold('egold','123456','1000','success.php','failure.php','ajsquare','[email protected]');
//$obj=new Lib_Paypal('paypal','123456','1000','success.php','failure.php');
$projAry=array('ajdf');
$comAry=array('document');
$catAry=array('task');
$priAry=array('critical');
$issueAry=array('2','2','2','2','ajdf','ajdf task occur');
$singleAry=array('2');
//$obj = new Lib_Issue('insert_project',$projAry);
//$obj = new Lib_Issue('insert_component',$comAry);
//$obj = new Lib_Issue('insert_category',$catAry);
//$obj = new Lib_Issue('insert_priority',$priAry);

Page 426 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

//$obj = new Lib_Issue('insert_issue',$issueAry);


//$obj = new Lib_Issue('select_singleissue',$singleAry);
//$obj = new Lib_Issue('select_allissue');
//$obj = new Lib_Issue('select_project');
//$obj = new Lib_Issue('select_component');
//$obj = new Lib_Issue('select_category');
//$obj = new Lib_Issue('select_priority');
//$obj = new Lib_Library('query','1060');
//$obj = new
Lib_Travel('travel','paris',"dJR83KrV34FiB.FBGiccQfYnB2mvLDz5kyIlwnSmX4PfcBseF_RI_YoLXG92P
p0tFQ--
//ebay-ajsquare-d126-4b9f-a233-6ecaf96a053a");
//$obj = new Lib_YahooQuery('query','car');
//$obj->Feed_conversion('dsf');
//$obj = new Lib_AddressBook('gmail','car','dfdf','dfdf','dsfdf');

//$obj = new Lib_TellFriend('friend','[email protected]','[email protected]','sub','comm');


//$obj = new Lib_Career('select_resume');
$arycon=array('ste','[email protected]','simple comment');
//$obj = new Lib_Contact('insert_contact',$arycon);
//$obj = new Lib_Contact('select_contact');
$arysimp=array('francis','[email protected]','gift','male','south street');
$arysimp1=array('2');
//$obj = new Lib_SimpleRegistration('insert_simplereg',$arysimp);
//$obj = new Lib_SimpleRegistration('update_inactive_status',$arysimp1);
//$obj = new Lib_SimpleRegistration('update_active_status',$arysimp1);
//$obj = new Lib_SimpleRegistration('select_active');
//$obj = new Lib_SimpleRegistration('select_inactive');
$aryart=array('ajdf','ajdf content','2');
$aryart1=array('2','ajdf source1','4');
$aryart3=array('2');
//$obj = new Lib_Articles('insert_article',$aryart);
//$obj = new Lib_Articles('insert_comment',$aryart1);
//$obj = new Lib_Articles('select_article');
//$obj = new Lib_Articles('select_comment',$aryart3);
$aryfaq=array('what is function','It is a project support functions');
//$obj = new Lib_Faq('insert_faq',$aryfaq);
//$obj = new Lib_Faq('select_faq');
$aryevent=array('festival','today christmas festival','2008-09-22','madurai');
//$obj = new Lib_Events('insert_event',$aryevent);
//$obj = new Lib_Events('select_past_event');
//$obj = new Lib_Events('select_future_event');
$aryfeed=array('raj','[email protected]','ajdf subject','ajdf
comment','[email protected]');
//$obj = new Lib_Feedback('insert_feedback',$aryfeed);
//$obj = new Lib_Feedback('select_feedback');
$arynews=array('ajdf source','http://ajsquare.com','2008-09-23','2008-09-29');
//$obj = new Lib_FlashNews('insert_news',$arynews);
//$obj = new Lib_FlashNews('select_news');
$aryblog=array('1000','function','function content','2');
$aryblog1=array('2','function source','1');
$aryblog3=array('1');

Page 427 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

//$obj = new Lib_Blog('insert_blog',$aryblog);


//$obj = new Lib_Blog('insert_comment',$aryblog1);
//$obj = new Lib_Blog('select_blog');
//$obj = new Lib_Blog('select_comment',$aryblog3);
$aryAns=array('what is function','function description','1001','501','2','5');
$aryAns1=array('1','ajdf is functions','4');
$aryAns2=array('1');
$aryAns3=array('1','2');
//$obj = new Lib_Answer('insert_question',$aryAns);
//$obj = new Lib_Answer('insert_answer',$aryAns1);
//$obj = new Lib_Answer('select_question',$aryAns2);
//$obj = new Lib_Answer('select_answer',$aryAns2);
//$obj = new Lib_Answer('update_best',$aryAns3);

if(empty($obj->debug))
print_r($obj->result);
else
print_r($obj->debug);

$ary1=array('2');
$ary2=array('2','nice');
//$obj = new Lib_Poll('select_quest',$ary1);
//$obj = new Lib_Poll('select_qa',$ary1);
//$obj = new Lib_Poll('update_points',$ary2);
//$obj = new Lib_Poll('select_points',$ary1);
//print_r($obj->result);
//$data = array("Jan" => 55,"Feb" => 54,"Mar" => 53,"Apr" => 33,"May" => 13,"Jun"
=> 15,"Jul" => 23,"Aug" => 200,"Sep" => 32,"Oct" => 45,"Nov" => 73,"Dec" => 71);
//$r=new Lib_BarChart('barchart',$data);

//print_r($r->result);
$stateAry=array('17');
$countryAry=array('102','combo');
$cityAry=array('102','17','combo');
//$r=new Lib_Country('country_list',$stateAry);
//$r=new Lib_Country('state_list',$countryAry);
//$r=new Lib_Country('city_list',$cityAry);
//print_r($r->result);
//$ranAry=array('Adver');
//$r=new Lib_Advertisement('random');
//print_r($r->result);
//$inboxarray1=array('[email protected]','[email protected]','test4','hello how are you
4');
//$inboxarray2=array('[email protected]','[email protected]','draft test3','draft hello
how are you 2');
//$inboxarray3=array('[email protected]');
//$inboxarray4=array('[email protected]');
//$inboxarray5=array('[email protected]','M_5','D_1');
//$crt=new Lib_Inbox('mail_sent',$inboxarray1);
//$crt=new Lib_Inbox('mail_save',$inboxarray2);
//$crt=new Lib_Inbox('inbox_list',$inboxarray3);
//$crt=new Lib_Inbox('sent_list',$inboxarray4);

Page 428 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

//$crt=new Lib_Inbox('draft_list',$inboxarray4);
//$crt=new Lib_Inbox('trash_list',$inboxarray4);
//$crt=new Lib_Inbox('trash_delete',$inboxarray5);
//print_r($crt->result);
//$crt=new Lib_Ebay('ebay','ipod',"ajsquare-d126-4b9f-a233-6ecaf96a053a");
//print_r($crt->result);
//$crt=new Lib_Flickr('flickr','flower');
//print_r($crt->result);
//$crt=new Lib_Youtube('youtube','sports');
//print_r($crt->result);
//$crt1=new Lib_Youtube('author','david');
//print_r($crt1->result);
//$s=$crt1->result;
//$crt2=new Lib_Youtube('single',$s[0]['id']);
//print_r($crt2->result);
//$crt=new Lib_Cryption('encrypt','hai how are you');
//$crs=$crt->result;
//print_r($crt->result);
//$crt1=new Lib_Cryption('decrypt',$crs);
//print_r($crt1->result);
$ar1=array("test3","1");
//$cap = new Lib_Photos('addalbum',$ar1);
//print_r($cap->result);
$ar=array("gif","jpg");
//$cap = new Lib_UploadFiles("d:\\nws_men.gif","images/",$ar,23478,23478,'jpg');
//print_r($cap->debug);
//$cap = new Lib_Captcha('captcha',200,200,5,'Fonts/ARIAL.TTF',70);
//print_r($cap->result);
$queryObj=new Bin_Query();
$sql="SELECT * FROM language_master";
$queryObj->executeQuery($sql);
$totRowsObj= $queryObj->records;//print_r($totRowsObj);exit;
//$obj1=new Lib_Converter('xmlconverter',$totRowsObj);
//print_r($obj1->result);
//$obj1=new Lib_Converter('tabconverter',$totRowsObj);
//print_r($obj1->result);
//$obj1=new Lib_Converter('excelconverter',$totRowsObj);
//print_r($obj1->result);
//$obj5=new Lib_Converter('csvconverter',$totRowsObj);//'csv\abc12.csv');
//print_r($obj5->result);
/*Hai i use php5 version and mysql.I have one doubt.what is a meaning in php.whenever
after before.paging version homesearch category email chart mysql good,localhost
compile,action"d:\Blue hills.jpg" ,"hello",100,100,'C:\WINDOWS\Fonts\Arial.ttf',18,"images/"*/
//$in=getimagesize("d:\\nws_men.gif");
//print_r($in);
$imgarr=array("d:\\nws_men.gif","win",'Fonts/ARIAL.TTF',8,"images/",10,10,360);
$samary=array("f:\\tt.jpeg",50,50,"images/");
//$aryCrop=array('images/Sunset.jpg',200,200,"images1/",0,0);
//$aryFormat=array("images/428226.jpg",'gif',"images1/");
//$objFormat=new Lib_ImageFunctions('image_format', $aryFormat);
//$objFormat->result;
//$objCrop=new Lib_ImageFunctions('image_crop', $aryCrop);

Page 429 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

//$obj=new Lib_ImageFunctions('image_resize',$samary);
//print_r($obj->debug);
//$obj=new Lib_ImageFunctions('watermark', $imgarr);//,50,50
);//("D:\wrc.jpeg",'gif',"images/",'100');//"..\classes\lib");
//print_r($obj->result);
//$obj=new Lib_TagPost('tagpost',"mea",'15');
//print_r($obj->result);
$imgarr1=array("version chart good,factory,meaning");
$imgarr2=array("images chart",3);
//$obj1=new Lib_TagSearchNew('tagsearch',$imgarr1);
//print_r($obj1->result);
//$obj1=new Lib_TagSearchNew('tagpost',$imgarr2);
//print_r($obj1->result);
$arytab=array('tab\SalesTaxRate.csv');
//$obj1=new Lib_Parser('tabparser','tab\SalesTaxRate.csv');
//print_r($obj1->result);
//$aryxml='xml\sample.xml';
//$obj1=new Lib_Parser('xmlparser',"xml/wp_posts.xml",1);
//print_r($obj1->result['root']['wp_posts'][0]['ID']);
//$arycsv=array('csv\abc.csv');
//$obj12=new Lib_Parser('csvparser','csv\vendor.csv');
//print_r($obj12->result);
//$aryexcel=array('excel\report3.xls');
//$objres=new Lib_Parser('excelparser',"excel\\report.xls");
//print_r($objres->result);
//print_r($obj->result);
//$obj=new Lib_Category('category',0,'categories','id','name','parent','?do=admin');
//print_r($obj->result);
//return $obj->result;
//$obj=new Lib_Localization('localization','japnish');
//print_r($obj->result);
//$obj=new Lib_Paging('paging','student_adv','10','?do=admin');
//print_r($obj->result);
/* SELECT a.mainid, b.mainid
FROM `category` a, `category` b
WHERE a.mainid = b.subid
LIMIT 0 , 30 */
/* SELECT a.category_id, b.category_id
FROM `category1` a, `category1` b
WHERE a.category_id = b.reference_id
ORDER BY a.category_id
LIMIT 0 , 30 */
//$arr=array("883605600","1216798238");
$arr=array(883605600,1216798238);
$arr1=array("883605600","12");
$arr2=array("883605600","1216798238","100");
$arr2=array("883605600","1216798238",20);
//$obj=new Lib_Date('datedif',$arr);
//$obj1=new Lib_Date('weekdif',$arr);
//$obj2=new Lib_Date('find_date',$arr1);
//$obj3=new Lib_Date('get_week',$arr2);
//$obj4=new Lib_Date('get_month',$arr2);

Page 430 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

//print_r($obj->result);
//print_r($obj1->result);
//print_r($obj2->result);
//print_r($obj3->result);
//print_r($obj4->result);
//$b=new Bin_Base();
/*$datedif=$b->dateDifference(883605600,1216798238);//(1997-12-31,2008-7-23)
$weekdif=$b->weekDifference(883605600,1216798238);
$finddate=$b->findDate(883605600,-10);
$getweek=$b->getWeeks(883605600,1216798238,10);
$getMonth=$b->getMonths(883605600,1216798238,10);*/
//$obja=new
Lib_AddressBook('aol','checkmailaj','square123456','a.php','subject','message');
//$obja=new Lib_AddressBook('gmail','stejes2000','','a.php','subject','message');
//$obja=new Lib_AddressBook('yahoo','stejes2000','','a.php','subject','message');
//$obja=new Lib_AddressBook('hotmail','testingaj','aj123456','a.php','subject','message');
//print_r($obja->result);
//$gmailAddress=$b->gmailAddress('a','a','Gmail.php');
//$yahooAddress=$b->yahooAddress('a','a','yahoo.php');
//$hotmailAddress=$b->hotmailAddress('a','a','Hotmail.php');
//$aolAddress=$b->aolAddress('a','a','AOLmail.php');
$tagWords=array(
array("Computer","http://www.yahoo.com",2300),
array("SuperComputer","http://www.gmail.com",180),
array("uuuuu","http://www.gmail.com",60),
array("ooooo","http://www.gmail.com",1240),
array("hai","http://www.ajsquare.com",0),
array("wwwww","http://www.ajsquare.com",20),
array("uuuuu","http://www.gmail.com",160),
array("ooooo","http://www.gmail.com",70),
array("wwwww","http://www.ajsquare.com",2000),
array("wwwww","http://www.ajsquare.com",7000)
);

//$obj1=new Lib_TagClouds('tag',$tagWords);
//print_r($obj1->result );
//exit();
//$obj12=new Lib_Email('mail','[email protected]','[email protected]','sub','hai');
//print_r($obj12->debug);
//$tagClouds=$b->tagClouds($tagWords);
//$get_month=$b->get_months(883605600,1216798238,10);

//$ary=array("10*9*11*10","Apple*Banana*Mango*Orange");
//$ary=array("0*1*0","Apple*Banana*Mango");
//$obj=new Lib_Chart('piechart',$ary);
//$obj->result;
//$data="10*9*11*10";
//$label="Denmark*Germany*USA*Sweden";
//$arr11=array("10*9*11*10","Denmark*Germany*USA*Sweden");
//$b1=new Lib_Chart('piechart',$arr11);
//print_r($b1->result);
//return $b1->result;

Page 431 of 432


M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886

//echo "<img src='".$b1->pieChart()."' />";


/*print_r($datedif);
print_r($weekdif);
print_r($finddate);
print_r($getweek);
print_r($getMonth);
print_r($tagClouds);*/
//$b2=new Lib_Zip('zip',"Functions","..\classes\lib\zipmmmmm12.zip");
//$b2=new Lib_Zip('zip',"images/","images1\zipmmmmm12.zip");
//$b23=new Lib_Zip('unzip',"c:\zip5555.zip","D:\debug1");
//print_r($b23->debug);
//print_r($b2->result);
//$b->zipFiles("Functions","c:\zipmmmmmm.zip");
//$b->unZip("zip\zip555.zip","c:\zipfolder5551");
?>

Page 432 of 432

You might also like