PHP Tutorial
PHP Tutorial
PHP Tutorial
VALIDATION
JAVASCRIPT
PHP - XML
WEBSERVICES
HTACCESS
CURL
OOPS – PHP
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
?>
(or)
<?PHP
?>
(or)
If the shorthand function is enabled in php.ini configuration file (Its dangerous syntax)
<?
?>
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;
?>
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.
<?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
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>
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
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
$names[2] = "Joe";
<?php
$names[0] = "Peter";
$names[1] = "Quagmire";
$names[2] = "Joe";
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";
?>
<?php
$a = array(―one‖,‖Two‖,‖three‖);
echo count($a);
?>
Output
Syntax
array_merge(array1,array2,...,arrayn);
Example
<?php
$a = array(―one‖);
$b = array(―two‖);
$c = array_merge($a,$b);
print_r($c);
?>
<?php
print_r($array);
?>
Page 9 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886
<?php
$a = array("Ram","Subbu","Vijay","Kannan","Bala","Ashok","Ganga");
$tmpArray = array();
$found = FALSE;
$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
$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
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.
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
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 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
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
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
Example
The following example demonstrates a loop that will print the values of the given array:
<html>
<body>
<?php
$arr=array("one", "two", "three");
</body>
</html>
Output
Value: one
Value: two
Value: three
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
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 />";
}
Page 16 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886
writeMyName("Kai Jim");
</body>
</html>
Output
Example
<html>
<body>
<?php
function add($x,$y)
{
$total = $x + $y;
return $total;
}
</body>
</html>
Output
1 + 16 = 17
Page 17 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886
</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.
<html>
<body>
</body>
</html>
Output
Welcome John.
You are 28 years old.
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
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):
Output
Welcome Ram
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
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):
Output
Welcome Ram
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
gmdate("i‖); // minutes
Page 20 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886
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
Page 21 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886
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)
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>
<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":
<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 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
</body>
</html>
Error message:
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:
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>
Closing a File
The fclose() function is used to close an open file:
<?php
$file = fopen("test.txt","r");
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: 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);
?>
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
?>
<html>
<body>
</body>
</html>
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
<?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"]);
}
?>
$_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.
Note: The setcookie() function must appear BEFORE the <html> tag.
Syntax
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).
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"];
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>
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
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.
Note: The session_start() function must appear BEFORE the <html> tag:
<html>
<body>
</body>
</html>
<?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.
<?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.
Syntax
mail(to,subject,message,headers,parameters)
Page 32 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886
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.";
?>
<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");
}
?>
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
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();
}
//trigger error
$test=2;
if ($test>1)
{
trigger_error("Value must be 1 or below",E_USER_WARNING);
}
?>
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
<?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]");
}
//trigger error
$test=2;
if ($test>1)
{
trigger_error("Value must be 1 or below",E_USER_WARNING);
}
?>
And the mail received from the code above looks like this:
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.
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
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.
If an exception is not caught, a fatal error will be issued with an "Uncaught Exception" message.
<?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);
?>
Page 37 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886
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
<?php
//create function with an exception
function checkNum($number)
{
if($number>1)
{
throw new Exception("Value must be 1 or below");
}
return true;
}
//catch exception
catch(Exception $e)
{
echo 'Message: ' .$e->getMessage();
}
?>
Example explained:
The code above throws an exception and catches it:
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.
The custom exception class inherits the properties from PHP's exception class and you can add
custom functions to it.
<?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);
}
}
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");
}
}
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
<?php
function myException($exception)
{
echo "<b>Exception:</b> " , $exception->getMessage();
}
set_exception_handler('myException');
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.
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
<?php
$int = 123;
if(!filter_var($int, FILTER_VALIDATE_INT))
{
echo("Integer is not valid");
}
else
{
echo("Integer is valid");
}
?>
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");
$hour = $hour - 7;
$minute = $minute + 1;
?>
The below program is used to get a widht and height in a given file.
<?php
$source = ―c:\sample\sample.jpg‖;
echo $width."<br>";
echo $height;
?>
<?php
$imagepath = "c:\sample\sample.jpg";
$modwidth = 280;
Page 43 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886
$modheight = 200;
$image = imagecreatefromjpeg($file) ;
if($imagename1[1] == "png")
$image = imagecreatefrompng($file) ;
if($imagename1[1] == "gif")
$image = imagecreatefromgif($file) ;
$uploadfile1_1 = substr($save,3,strlen($save));
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) ;
?>
<?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.";
foreach($staticparaexplode as $val)
if($val == "ISAPI")
break;
else
echo $msg;
Page 45 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886
?>
<?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.";
foreach($staticparaexplode as $val)
if(substr($val,0,5) == "Micro")
break;
else
echo $msg;
?>
<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];?>><?=$a[$i];?></option>
<? }
}?>
</select>
<table>
<DIV ID=files>
</DIV>
</td></tr>
</table>
Page 47 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886
<SCRIPT>
var nfiles = 1;
function Expand(){
nfiles++
files.insertAdjacentHTML('BeforeEnd',adh);
return false;
};
</script>
Validation
Checkbox Validation
<?php
function valid()
if (chks[i].checked)
hasChecked = true;
var confrm;
Page 48 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886
return confrm;
break;
if (!hasChecked)
chks[0].focus();
return false;
?>
<script>
function charonly(e)
Page 49 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886
return false
//disable key press
function numbersonly(e){
if (unicode!=8){ //if the key isn't the backspace key (which we should allow)
</script>
URL Validation
PHP
<?php
function isValidURL($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)) {
else {
?>
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>
URL:
</form>
</body>
</html>
IP Address Validation
<script language=‖javascript‖>
errorString = "";
theName = "IPaddress";
if (IPvalue == "0.0.0.0")
Page 52 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886
if (ipArray == null)
else {
thisSegment = ipArray[i];
i = 4;
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>
<?php
?>
Syntax
nl2br(string)
Example
<?php
$a = ―Sample \n Text‖;
echo nl2br($a);
?>
Ouput
Sample
Text
String Replace
Syntax
Example
<?php
$a = "PHP is a one of the good webdevelopment software‖;
echo str_replace("good","best",$a);
?>
<?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".
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
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());
}
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
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();
}
mysql_close($con);
?>
Page 57 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886
Page 58 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886
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
mysql_query($sql,$con);
?>
Page 59 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886
Syntax
You can also specify the columns where you want to insert the data:
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_close($con);
?>
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.
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
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)
?>
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);
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']).
Page 62 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886
Peter Griffin
Glenn Quagmire
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
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);
?>
Firstname Lastname
Glenn Quagmire
Peter Griffin
Page 63 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886
Syntax
SELECT column FROM table
WHERE column operator value
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.
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);
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'] . " " . $row['LastName'];
echo "<br />";
}
?>
Peter Griffin
Page 64 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886
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);
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
Glenn Quagmire 33
Peter Griffin 35
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
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
Syntax
UPDATE table_name
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_close($con);
?>
After the update, the "Person" table will look like this:
The DELETE FROM statement is used to delete records from a database table.
Syntax
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:
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_close($con);
?>
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).
With an ODBC connection, you can connect to any database, on any computer in your network,
as long as an ODBC connection is available.
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.
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','','');
$rs=odbc_exec($conn,$sql);
Retrieving Records
The function takes two parameters: the ODBC result identifier and an optional row number:
odbc_fetch_row($rs)
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");
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.
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
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.
<from>Jani</from>
Page 70 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886
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.
An XML File
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
</note>
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();
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: ";
}
}
//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)));
}
?>
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
Page 73 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886
An XML File
The XML file below will be used in our example:
Example
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();
?>
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
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 />";
}
?>
#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
Compared to DOM or the Expat parser, SimpleXML just takes a few lines of code to read text data
from an element.
SimpleXML is fast and easy to use when performing basic tasks like:
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:
We want to output the element names and data from the XML file above.
Example
<?php
$xml = simplexml_load_file("test.xml");
Page 76 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886
foreach($xml->children() as $child)
{
echo $child->getName() . ": " . $child . "<br />";
}
?>
note
to: Tove
from: Jani
heading: Reminder
body: Don't forget me this weekend!
Page 77 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886
Page 78 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886
}
$xml->asxml("test3.xml");
exit;
?>
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.
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)
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).
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.
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.
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.
However, in this tutorial we will focus more on actual examples running on a PHP server, and less
on how AJAX works.
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.
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")
}
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;
}
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
<html>
<head>
<script src="clienthint.js"></script>
</head>
<body>
<form>
First Name:
<input type="text" id="txt1"
onkeyup="showHint(this.value)">
</form>
</body>
Page 82 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886
</html>
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:
If the input field is empty, the function simply clears the content of the txtHint placeholder.
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.
AJAX applications can only run in web browsers with complete XML support.
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.
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";
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];
}
}
}
}
If there is any text sent from the JavaScript (strlen($q) > 0) the following happens:
Page 86 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886
<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
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:
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"];
$x=$xmlDoc->getElementsByTagName('ARTIST');
$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:
The Database
The database we will be using in this example looks like this:
<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
<p>
<div id="txtHint"><b>User info will be listed here.</b></div>
</p>
</body>
</html>
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.
If an item in the drop down box is selected the function executes the following:
Page 92 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886
The code runs a SQL query against a database and returns the result as an HTML table:
<?php
$q=$_GET["q"];
mysql_select_db("ajax_demo", $con);
$result = mysql_query($sql);
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:
Page 93 of 432
M.N. Ramasubbu
[email protected]
Ph : +91-99408 38886
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:
<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>
<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>
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.
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 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"];
mysql_select_db("ajax_demo", $con);
$result = mysql_query($sql);
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
AJAX can be used for a more user friendly and interactive search.
<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>
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;
}
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:
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 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');
}
}
}
}
<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">
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
{
// 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;
}
Every time an option is selected in the input field this function executes the following:
<?php
//get the q parameter from URL
$q=$_GET["q"];
AJAX Suggest
In the AJAX example below we will demonstrate a poll where the web page can get the result
without reloading.
<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>
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.
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).
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
}
This function executes when "yes" or "no" is selected in the HTML form.
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
<?php
$vote = $_REQUEST['vote'];
if ($vote == 0)
{
$yes = $yes + 1;
}
if ($vote == 1)
{
$no = $no + 1;
}
<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>
<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>
Note: To convert between calendar formats, you must first convert to Julian day count, then to
the calendar format.
<?php
?>
Function Description PH
P
libxml_clear_errors() Clear libxml error buffer 5
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
()
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
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
--------------------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)
return
var url="destinationajax.php"
url=url+"?comm="+str
xmlHttp.onreadystatechange=stateChanged
xmlHttp.open("GET",url,true)
xmlHttp.send(null)
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>
<span id="comment"></span>
destinationajax.php
<?php
?>
----------AJAX OVER--------------
<?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
Standard Setup
SOAP
XML-RPC
REST
This talk covers
SOAP Client
SOAP Server
XML-RPC (just a little)
REST Client
Querying Amazon.Com
Protocols
SOAP
<?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();
?>
Machine readable description (XML) of a web service. Used here to define server's methods and
parameters.
<?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
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
)
)
)
<?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
SOAP Server
<?php
require_once 'SOAP/Server.php';
class SOAP_Server_rot13 {
function rotate($input) {
return str_rot13($input);
}
}
<?php
require_once 'SOAP/Client.php';
$client = new SOAP_Client('http://localhost/rot13.php');
$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
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
<?php
$url = 'http://xml.amazon.com/onca/xml3?';
<?php
$c = curl_init($url);
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
$hits = curl_exec($c);
curl_close($c);
?>
XML Results
<TotalResults>165</TotalResults>
<Details url="http://www.amazon.com/...">
<Asin>B00004OCKR</Asin>
<ProductName>OXO Good Grips Salad Spinner</ProductName>
<Catalog>Kitchen</Catalog>
<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>
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;
<?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);
}
}
}
?>
<?php
function end_element($parser, $tag) {
// Each product ends with a closing Details tag
if ('Details' == $tag) {
$this->item->display();
unset($this->item);
}
}
?>
<?php
class Amazon_item {
?>
Output
HTML
Resources
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.
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}
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
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]
Example #3:
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:
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
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
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:
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.
SetEnv TZ Europe/London
SetEnv TZ US/Central
SetEnv TZ US/Midwest
<Files .htaccess>
order allow,deny
deny from all
</Files>
<files secretfile.jpg>
order allow,deny
deny from all
</files>
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]
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.
session.gc_maxlifetime specifies the number of seconds after which data will be seen as 'garbage'
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]
// Example 2008-01-25
var re = /\s*((\S+\s*)*)/;
return value.replace(re, "$1");
var re = /((\s*\S+)*)\s*/;
return value.replace(re, "$1");
return LTrim(RTrim(value));
function test()
{
var a = "sample ";
alert(trim(a));
}
use this function for cut the whole words and display all words .
$temp = '';
$l = strlen($content);
for($i=0;$i<$l;$i = $i+$s)
{
$temp = $temp.substr($content,$i,$s).'<br>';
}
return $temp;
}
<?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?
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>
Returns an array with all keys from input lowercased or uppercased. Numbered indices are left as
is.
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
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_intersect() returns an array containing all the values of array1 that are present in all the
arguments. Note that keys are preserved.
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.
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.
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
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_unique() takes input array and returns a new array without duplicate values.
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.
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 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>
<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
<html>
<head>
<script>
function alert_stat()
{
var f = document.getElementById("f");
var a = "";
a += "form.method = " + f.method + "\n\r\n\r";
XML Parsing
userdetail.xml file structure
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));
// original
//echo "<xmp>OLD:\n". $xml->saveXML() ."</xmp>";
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]);
$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();
}
}
?>
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;
}
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.
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
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 |
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:
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.
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:
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) |
+--------------------------------------+
| 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.
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).
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 |
+----------------------------+
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.
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.
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
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)
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()
Syntax:
SELECT CEILING(number)
Example:
mysql> SELECT CEILING(4.84);
+---------------+
| 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)
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.
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()
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|
+-----------------+
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 |
| 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)
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)
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'
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)
+--------------------------------+
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
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
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
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
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.
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 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?
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?
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
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
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.
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
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
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.
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:
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.
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/
If you are using an older version of XAMPP (like XAMPP version 1.4) without the httpd-vhosts.conf
file, use the instructions below.
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"
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.
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 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.
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.
Below are some examples which should make the working of cURL more clearer.
The below piece of PHP code uses cURL to download Google‘s RSS feed.
<?php
/**
*/
$ch = curl_init();
/**
*/
curl_setopt($ch, CURLOPT_URL,
'http://news.google.com/news?hl=en&topic=t&output=rss');
/**
*/
/**
*/
/**
*/
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.
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.
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
/**
*/
$ch = curl_init();
/**
*/
curl_setopt($ch, CURLOPT_URL,
'http://news.google.com/news?hl=en&topic=t&output=rss');
/**
*/
/**
*/
/**
*/
curl_exec ($ch);
/**
*/
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.
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.)
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.
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.
BIT_XOR(expr)
Returns the bitwise XOR of all bits in expr. The calculation is performed with 64-bit
(BIGINT) precision.
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(*) 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.
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:
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.
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.
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.
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.
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_SAMP(expr)
Returns the sample standard deviation of expr (the square root of VAR_SAMP(). This
function was added in MySQL 5.0.3.
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.
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_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.
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.
SIMPLE USAGE
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
curl http://www.weirdserver.com:8000/
curl ftp://cool.haxx.se/
curl dict://dict.org/m:curl
curl ftps://files.are.secure.com/secrets.txt
or use the more appropriate FTPS way to get the same file:
Get a file from an SSH server using SCP using a private key to authenticate:
curl -g "http://[2001:1890:1112:1::20]/"
DOWNLOAD TO A FILE
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:
USING PASSWORDS
FTP
curl ftp://name:[email protected]: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
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
PROXY
Get an ftp file using a proxy named my-proxy that uses port 888:
Get a file from a HTTP server that requires user and password, using the
same proxy as above:
A comma-separated list of hosts and domains which do not use the proxy can
be specified as:
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.
Curl also supports simple ranges for FTP files as well. Then you can only
specify start and stop position.
UPLOADING
curl -T - ftp://ftp.upload.com/myfile
Upload data from a specified file, login with user and password:
Upload a local file to the remote site, and use the local file name remote
too:
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:
HTTP
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:
DETAILED INFORMATION
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.
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.
curl -d "name=Rafael%20Sagula&phone=3320780"
http://www.where.com/guest.cgi
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).
<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:
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],cat.gif"
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.
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:
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
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").
it means the server wants that first pair passed on when we get anything in
a path beginning with "/foo".
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:
... you can then in a second connect to that (or another) site, use the
cookies from the 'headers' file like:
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:
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:
PROGRESS METER
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:
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:
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
"bandwidth throttle").
or
Or prevent curl from uploading data faster than 1 megabyte per second:
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.
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
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:
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:
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:
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
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:
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):
NETWORK INTERFACE
Get a web page from a server using a specified port for the interface:
or
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.
Example:
curl https://www.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/
(*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
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:
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:
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 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
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
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
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
ALL_PROXY
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.
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).
CUSTOM OUTPUT
To display the amount of bytes downloaded together with some text and an
ending newline:
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:
There's no use for a password on the -u switch, but a blank one will make
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.
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.
As is mentioned above, you can download multiple files with one command line
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:
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
curl-announce
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.
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
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.
<?php
class First extends Controller
{
public function __construct()
{
parent::Controller(); // Mandatory line to all
classes.
}
function displayname()
{
echo "Ramasubbu";
}
}
?>
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.
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
<?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";
}
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);
}
}
$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()
{
$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> </td>
<td><label>
if(document.loginfrm.username.value == "")
{
alert("Please enter your Username");
document.loginfrm.username.focus();
return false;
}
}
</script>
a. Combo 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'); ?>
/>
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)
$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
$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]');
return $this->form_validation->run();
}
12. Controller File Path
a. /system/application/controllers/filename&sameclassname.php
a. /system/application/models/filename&sameclassname.php
a. /system/libraries/ filename.php
a. /system/plugins/filename&sameclassname.php
a. /system/application/config/config.php
a. /system/application/config/database.php
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
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.
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
8. node.tpl.php
9. comment.tpl.php
a. This file is used to display the ―Story‖ page comments listing with styles.
10. box.tpl.php
11. themename.info
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">
Output
(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'];
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">
Output
<?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
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:
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.
Benefits of Encapsulation:
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.
Now based on the above example, In Object Oriented terms following are true:
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:
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:
Let us use the instanceof operator to check determine whether Mammal is actually an Animal,
and dog is actually an Animal
interface Animal{}
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.
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:
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
OR
1. Compile time polymorphism -- achieved when a derived class overrides a base class
method or implements an interface method.
Example:
Now the Deer class is considered to be polymorphic since this has multiple inheritance. Following
are true for the above example:
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.
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.
When you would compile above class then you would get following error:
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.
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:
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.
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 written in a file with a .java extension, with the name of the interface
matching the name of the file.
Interfaces appear in packages, and their corresponding bytecode file must be in a directory
structure that matches the package name.
An interface cannot contain instance fields. The only fields that can appear in an interface
must be declared both static and final.
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:
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.
Example:
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.
Mammal eats
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.
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.
//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);
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.
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:
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.
<?php
private $age;
$this->age = $age;
return $this->age;
interface insurable {
private $name;
parent::__construct($age);
$this->name = $name;
return $this->name;
return ("Priceless");
?>
<?php
?>
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)
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.
What ever the OOP language used, it should be the same concept.(Those are pure OOP concepts)
mysql_ping($connectionobject)
function sample($a)
function sample($a)
“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.
<?php
class BaseClass {
?>
<?php
// 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 ->.
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
return self::$my_static;
return parent::$my_static;
?>
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";
}
}
<?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 />";
}
}
$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.
<?php
class A
function A() { }
$a = func_get_args();
echo $a[$t];
?>
Overridding
<?php
class vehicle {
var $brand_name;
var $number_of_wheels;
var $seating_capacity;
function message() {
var $doors;
var $rooftype;
var $powersteering;
var $powerwindows;
function message() {
parent::message() // or vehicle::message();
$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.
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.
+------+---------------+----------+
+------+---------------+----------+
|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 |
+------+---------------+----------+
+---------+-------------+------+
+---------+-------------+------+
| 111 | Monitor |1 |
| 112 | Processor |2 |
| 113 | Keyboard |2 |
| 114 | Mouse |3 |
| 115 | CPU |5 |
+---------+-------------+------+
+------+---------------+----------+
+------+---------------+----------+
|1 | A K Ltd | Delhi |
|2 | V K Associate | Mumbai |
|3 | R K India | Banglore |
|5 | A T Ltd | Delhi |
+------+---------------+----------+
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 :
+------+---------+-------+
+------+---------+-------+
|1 | A K Ltd | Delhi |
|5 | A T Ltd | Delhi |
+------+---------+-------+
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 :
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 :
+------+---------------+----------+-------------+
+------+---------------+----------+-------------+
+------+---------------+----------+-------------+
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 :
In the following example we are dropping the view that we have created above. Example of
Dropping the View Statement :
MYSQL – Triggers
» MySQL Triggers » 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:
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.
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
DELIMITER $$
employeeNumber = OLD.employeeNumber,
lastname = OLD.lastname,
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
Now when you can see the changes audited automatically in the employees_audit table by
executing the following query
SELECT *
FROM employees_audit
ON table_name
BEGIN
...
END
* The trigger name should follow the naming convention [trigger time]_[table name]_[trigger
event], for example before_employees_update
* 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.
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 |
+--------+--------+---------+------+------------+-------+
+----------+-------+---------+------+------------+------------+
| 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.
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;
SELECT
t1.event,
t2.event,
COUNT(*)
FROM
lentus AS t1,
lentus AS t2,
twin_project AS tp
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
Some explanations:
• 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.
Adwards
http://www.google.com/adwards
1. Signup in Google
2. Set your time zone and currency preferences (Automatically set the
below fields values)
3. Finally display the success message with ―Sign in to your AdWords account‖ url
and ―optimization tips.‖ url.
http://www.google.com/adsense
Fillup the personal detail form only. After confirmation from google, the adsense account will
active.
Maps
2. http://code.google.com/apis/maps/documentation/staticmaps/
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/
2. Signup in Google
1. Last Name
2. First Name
3. Country or territory
5. Accept the User Aggrement – click the ―Create New Account‖ button
7. Note : Paste the google analytics api code before the </body> tag in your footer.
Visualization
INT GOLD
Return values:
$_POST['AMOUNT']
$_POST['TRANSACTION_ID']
$_POST['BUYERACCOUNTID']
PAYPAL REAL
Return values
$_POST['payment_gross'] ->Amount
$_POST['txn_id'] -> Transaction ID
$_POST[‗mc_gross‘] -> Amount
PAYPAL TEST/SANDBOX
Return values
$_POST['payment_gross'] ->Amount
$_POST['txn_id'] -> Transaction ID
$_POST[‗mc_gross‘] -> Amount
STROM PAY
Return values:
$_POST['amount']
$_POST['transaction_id']
$_POST['payer_name']
E BULLION
Return values:
$_POST['ATIP_PAYMENT_AMOUNT']
$_POST['ATIP_TRANSACTION_ID']
$_POST['ATIP_ACCOUNT']
MONEY BOOKER
Return values:
$_POST['AMOUNT']
$_POST['TRANSACTION_ID']
ALERT PAY
Return values:
$_POST['AMOUNT']
$_POST['TRANSACTION_ID']
SAFEPAY SOLUTIONS
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>">
Return values:
$_POST['AMOUNT']
$_POST['lr_transfer']
PECUNIX
Return values:
$_POST['PAYMENT_AMOUNT']
$_POST['TRANSACTION_ID']
<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>
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.
Before you can start processing HTML posts in this manner, you must enable the HTML API in your
merchant account as follows:
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>
Library Lits
1. Get the Gmail, Yahoo, Hotmail and AOL address book contacts
9. Create Barcode
10. Given byte to Byte, Kilo byte, Mega byte, Giga byte, TB and Pb
14. Shows the Astronomy picture of today. Fetched from the NASA website
19. Get geographical location of the IP address using web service of http://www.geoplugin.com
28. Give spelling suggestion for English words using yahoo API
*/
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
*/
/**
* This function is use to find out the address book of gmail and send invitation mail to all members.
*
* @return array $result
*/
$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);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
$content = curl_exec ($ch);
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);
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
*/
$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
{
$varURL = "http://www.AddressBookImport.com/trial/";
$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);
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);
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
*/
$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
{
$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);
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);
$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;
}
/**
* This function is use to validate the subject.
*
* @return array $array
*/
/**
* This function is use to delete the file.
*
* @return array $fileName
*/
/**
* This function is use to set the username.
*
* @return array $username
*/
/**
* This function is use set the password.
*
* @return array $password
*/
/**
* This function is use to initialize the variable.
*
* @return array _username
*/
/**
* This function is use to initialize the variable.
*
* @return array _password
*/
/**
* This function is use to collect all the contact list of aol.
*
* @return array $result
*/
$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 );
$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 );
// 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
}
// 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
*/
$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))
{
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++)
{
/**
* This function is use get server variables.
*
* @return array fnGet
*/
{
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
*/
/**
* Constructs a Lib_AlexaPageRank object with given parameters
* also it will invoke page rank process
*
* @param string $type
* @param string $url
* @return Lib_AlexaPageRank
*/
if($this->isValidCall())
{
if(strtolower($type)=='alexa_rank')
$this->getAlexaRank();
}
}
/**
* Check whether the function call is valid or not
*
* @return bool
*/
/**
* get page rank for given site
*
* @return string
*/
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
*/
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
<?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
*/
$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);
// allocate colors
$this->allocateColor("imRectBgColor", $this->rectBgColor);
$this->allocateColor("imRectBorderColor", $this->rectBorderColor);
$this->allocateColor("im_fontcolor", $this->fontcolor);
// 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
*
*/
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
$top -= $this->spacepadding;
imageline($this->im, $startx, $top, $endx, $top, $this->imRectBorderColor);
}
/**
* get maximum width
*
*/
}
}
return $c;
}
/**
* get maximum deepness
*
*/
/**
* draw the rectangle
*
*/
/**
* allocate color
*
*/
}
?>
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
{
/**
*/
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
*/
if($this->isValidCall())
{
if(strtolower($type)=='asciiart')
$this->asciiart();
}
}
/**
* Check whether the function call is valid or not
*
* @return bool
*/
/**
* set the rgb color
*
*/
function rgb2HEX($rgb)
{
return sprintf("%02X%02X%02X",$rgb["red"],$rgb["green"],$rgb["blue"]);
}
/**
* render the pixel
*
*/
switch ($mode)
{
case 1:
$brightness = $rgb["red"] + $rgb["green"] + $rgb["blue"];
$this->imageHTML .= $this->_replaceCharacters[$replaceCharacterNo];
break;
case 2:
$brightness = $rgb["red"] + $rgb["green"] + $rgb["blue"];
if ($this->fontTagOpen)
{
$this->imageHTML .= "</font>";
}
{
$this->imageHTML .= $fixedChar;
}
else
{
if ($this->fontTagOpen)
{
$this->imageHTML .= "</font>";
}
/**
* set the image css
*
*/
/**
* render html image
*
*/
if ($resolution < 1)
{
$resolution = 1;
}
{
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
*
*/
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];
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
*
*/
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; ');
$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
{
/**
* 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
*/
if($this->isValidCall())
{
if(strtolower($type)=='asciiencode')
$this->getResult();
}
/**
* Check whether the function call is valid or not
*
* @return bool
*/
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
);
break;
}
return $return;
}
/**
* Decode from ASCII.
*
* @return string
*/
// 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
);
$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
*/
$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
*/
/**
* Call encode/decode.
*
* @return string
*/
}
?>
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
*
/**
* 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
*/
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';
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
*
*/
/**
* This function create auto fill text box
*
* @return string
*/
}
/**
* This function set input data array
*
*/
/**
* This function set data display limit
*
*/
/**
* This function set the fill status
*
*/
/**
* This function load the java script
*
* @return string
*/
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;
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)
{
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
{
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;
}
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
*/
}
?>
Take the Database Backup
<?php
/**
* BackupDB
*
* This class contains functions backup to database.
*
* @package Lib_BackupDB
* @category Library
* @version 1.0
*/
// ------------------------------------------------------------------------
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;
/**
if($this->isValidCall())
{
if(strtolower($type)=='backup')
$this->backup();
}
}
/**
* Check whether the function call is valid or not
*
* @return bool
*/
}
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
*/
$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);
{
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
* @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
*/
if($this->isValidCall())
{
if(strtolower($type)=='barchart')
$this->barChart();
}
}
/**
/**
* This function create bar chart image for the given inputs.
*
* @return image barChart
*/
$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;
}
}
// 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);
}
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
*
if($this->isValidCall())
{
if(strtolower($type)=='barcode')
$this->barcodeDisplay();
}
/**
* Check whether the function call is valid or not
*
* @return bool
*/
/**
* configuration end's heare.
*
* @return integer
*/
/**
* encodes with EAN-13 using built in functions.
*
* @return array
*/
$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)
$text.=" ";
$text.="$pos:12:{$ean[$a]}";
if ($a==0)
$pos+=12;
else if ($a==6)
$pos+=12;
else
$pos+=7;
}
/**
* Generate the bar code image content
*
* @return image
*/
$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));
$height2=round($total_y-$space['bottom']);
/**
* Generate the barcode text
*
* @return string
*/
/* 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))
{
//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
*/
/**
* built-in encoder
*
* @return array
*/
)
{
/* 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
*/
?>
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
*/
if($this->isValidCall())
{
if(strtolower($type)=='byte')
$this->getSize();
}
}
/**
* Check whether the function call is valid or not
*
* @return bool
*/
/**
* get the size for given byte value
*
* @return string
*/
}
?>
Draw the Pie Chart
<?php
/**
* Chart
*
* This class contains functions to handle the pie chart.
*
* @package Lib_Chart
* @category Library
* @version 1.0
*/
// ------------------------------------------------------------------------
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
*/
if($this->isValidCall())
{
if(strtolower($type)=='piechart')
$this->pieChart();
}
}
/**
* Check whether the function call is valid or not
*
* @return bool
*/
{
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
*/
$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)
$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));
else
{
$this->error = 1;
$this->debug['errinfo'] = array(1005=>'First array is numeric
& second one is string');
return false;
}
}
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
*/
/**
* 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;
}
/**
* 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",
/**
* Constructs a Lib_ChatGrammarCorrector object with given parameters
* also it will invoke grammar correction process
*
* @param string $type
* @param string $data
* @return Lib_ChatGrammarCorrector
*/
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();
}
return true;
}
/**
* This function replaces repeated punctuation.
*
* @return string $msg
*/
return $msg;
}
/**
* This function correct the text.
*
* @return string $result
*/
$msg = $this->replaceRepeatedPunctuation($msg);
$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));
}
else
{
$w = strtolower($w);
}
}
$new[] = $w;
}
}
?>
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);
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;
* @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
*/
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
*/
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
*/
/**
* This function create astronomy image
*
* @return image
*/
}
?>
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
*
* @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
*/
if($this->isValidCall())
{
if(strtolower($type)=='cartoon')
$this->callCartoon();
}
/**
* Check whether the function call is valid or not
*
* @return bool
*/
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)) ;
/**
* select the cartoon
*
* @return string
*/
$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)
{
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 ;
{
$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
$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
*/
$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
*/
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
*/
if($this->isValidCall())
{
if(strtolower($type)=='joke')
$this->getJoke();
}
}
/**
* Check whether the function call is valid or not
*
* @return bool
*/
/**
* get joke from jokes2go site
*
* @return string
*/
{
$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 ;
/**
* 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
*/
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';
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
*/
/**
* create a list of google image urls
*
* @return image
*/
$j += 20;
}
return $returnArray;
}
/**
* download images from google
*
*/
@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
*/
$link=trim(substr($str1,$pos1,$pos2-$pos1));
$return[]=$link;
}
}
return $return;
}
/**
* get source code of a url
*
* @return string
*/
}
?>
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
}
}
/**
* 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;
$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
}
}
?>
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
*/
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 );
}
{
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
*
* 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)
{
$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;
}
/**
* 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;
}
}
/**
* @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="";
/**
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
{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
.'(:[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);
}
/**
* 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
*
}
}
/**
* 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();
}
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);
}
}
}
$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;
/**
* 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();
}
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
{
$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
*/
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;
}
}
?>
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;
/**
{
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];
$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)
{
$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":
@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
*
/**
* 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
*/
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();
}
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
*/
/**
* image convert to mirrored image
*
* @return image
*/
return $outputImage;
}
/**
* save the image to destination path
*
*/
}
?>
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
*/
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
*
* @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
*/
if($this->isValidCall())
{
if(strtolower($type)=='page_rank')
$this->getPageRank();
}
}
/**
* Check whether the function call is valid or not
*
* @return bool
*/
exit();
}
return true;
}
/**
* get page rank for given site
*
* @return string
*/
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>';
}
$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
*/
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
*/
$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
*/
/**
* genearate a hash for a url
*
* @return bool
*/
$T1 = (((($Check1 & 0x3C0) << 4) | ($Check1 & 0x3C)) <<2 ) | ($Check2 & 0xF0F );
$T2 = (((($Check1 & 0xFFFFC000) << 4) | ($Check1 & 0x3C00)) << 0xA) | ($Check2 & 0xF0F0000 );
/**
* genearate a checksum for the hash string
*
* @return string
*/
$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
*
* 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 = '';
/**
* 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
*/
if($this->isValidCall())
{
if(strtolower($type)=='spell')
$this->getSuggestedWord();
}
}
/**
* Check whether the function call is valid or not
*
* @return bool
*/
/**
* search the given word
*
* @return bool
*/
/**
* give spelling suggestion for english words
*
* @return string
*/
/**
* set output keyword
*
* @return string
*/
}
?>
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
{
/**
* 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
if($this->isValidCall())
{
if(strtolower($type)=='speech')
$this->textConverter();
}
}
/**
* Check whether the function call is valid or not
*
* @return bool
*/
/**
* set the header and download the file
*
* @return bool
*/
header("Content-type: audio/mpeg");
header("Content-Disposition: attachment; filename=\"".$this->mp3name.".mp3\"");
$text=$contents;
$this->setPath($text, 'eng');
$this->result= $this->printBufor();
return true;
}
/**
* set the say.expressivo.com url path
*
*/
"xajax=generateVoice&xajaxr=".time()."&xajaxargs[]=pl&xajaxargs[]=".urlencode($check)."&xajaxargs[]=".$lang."&xaja
xargs[]=true&xajaxargs[]=1"
);
if ($linki[2][0] == '')
{
$this->error = 1;
break;
}
else
{
$file_mp3[] = $linki[2][0];
}
$c += $num_z;
}
if (@is_array($file_mp3))
{
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
*/
}
if ($data == '') {return false;}
return $data;
}
/**
* text validation
*
* @return string
*/
?>
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
*/
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
*/
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))
{
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
*/
// Build background
ImageFilledRectangle($image,0,0,$width,$height,$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
*
* @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
*/
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;
}
/**
* This function get the travel item list depend upon the given category ex:paris
*
* @return string $result
*/
/**
* This function split the each category feed
*
* @return string $res
*/
}
?>
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
*
/**
* Constructs a Lib_Wikipedia object with given parameters
* also it will invoke wikipedia search process
*
* @param string $type
* @param string $title
* @return Lib_Wikipedia
*/
if($this->isValidCall())
{
if(strtolower($type)=='wiki')
$this->search();
}
}
/**
* Check whether the function call is valid or not
*
* @return bool
*/
/**
* get the result from wikipedia site
*
* @return string
*/
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> <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"> <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
ob_end_flush();
$this->result=$output;
return true;
}
/**
* create search panel
*
* @return string
*/
/**
* call curl request
*
*/
* @version 1.0
*/
// ------------------------------------------------------------------------
class Lib_YahooQuery
{
/**
* 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
*/
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();
}
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
*/
/**
* This function split the each category feed
*
* @return string $res
*/
}
?>
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');
//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))
{
//$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,
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/');
$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);
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);
//$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);
//$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);
//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;