Thursday, December 24, 2009

Error Handing in PHP

Here are some of the Error Handling Techniques

It is important to configure PHP's error reporting settings depending on which phase of development the web application is currently in. Generally, the programmer wants to see all warnings and errors in the web browser during the initial phase of development, and later, once the site has launched, send error messages to a log file so that visitors do not see them.
Error Reporting for Development

During development, you want to display all errors and warnings to the browser.

// Report all PHP errors
ini_set('error_reporting', E_ALL);

// Set the display_errors directive to On
ini_set('display_errors', 1);

Error Reporting for Production

In production, you may want to lower the error reporting level and not display errors to the browser.

// Report simple running errors
ini_set('error_reporting', E_ALL ^ E_NOTICE);

// Set the display_errors directive to Off
ini_set('display_errors', 0);

// Log errors to the web server's error log
ini_set('log_errors', 1);

Logging errors

You can use the PHP function error_log() to send errors to your own log file or an e-mail address. This is particularly important since most developers on campus do not have access to the web servers logs. Used in conjunction with a custom error handler, error_log() is especially useful.

// Destinations
define("ADMIN_EMAIL", "test@test.com");
define("LOG_FILE", "/error/errors.log");

// Destination types
define("DEST_EMAIL", "1");
define("DEST_LOGFILE", "3");

/* Examples */

// Send an e-mail to the administrator
error_log("Please fix this!", DEST_EMAIL, ADMIN_EMAIL);

// Write the error to our log file
error_log("Error", DEST_LOGFILE, LOG_FILE);

Create a custom error handler

It is possible to override PHP's default mechanism for handling errors. This option gives the programmer full control over what actions to take when an error is raised. Note that since this method completely replaces PHP's native functionality, it is important to pay special care when writing a custom error handler.

// Destinations
define("ADMIN_EMAIL", "test@test.com");
define("LOG_FILE", "/error/errors.log");

// Destination types
define("DEST_EMAIL", "1");
define("DEST_LOGFILE", "3");

/**
* my_error_handler($errno, $errstr, $errfile, $errline)
*
* Author(s): thanosb, ddonahue
* Date: May 11, 2008
*
* custom error handler
*
* Parameters:
* $errno: Error level
* $errstr: Error message
* $errfile: File in which the error was raised
* $errline: Line at which the error occurred
*/

function my_error_handler($errno, $errstr, $errfile, $errline)
{
switch ($errno) {
case E_USER_ERROR:
// Send an e-mail to the administrator
error_log("Error: $errstr \n Fatal error on line $errline in file $errfile \n", DEST_EMAIL, ADMIN_EMAIL);

// Write the error to our log file
error_log("Error: $errstr \n Fatal error on line $errline in file $errfile \n", DEST_LOGFILE, LOG_FILE);
break;

case E_USER_WARNING:
// Write the error to our log file
error_log("Warning: $errstr \n in $errfile on line $errline \n", DEST_LOGFILE, LOG_FILE);
break;

case E_USER_NOTICE:
// Write the error to our log file
error_log("Notice: $errstr \n in $errfile on line $errline \n", DEST_LOGFILE, LOG_FILE);
break;

default:
// Write the error to our log file
error_log("Unknown error [#$errno]: $errstr \n in $errfile on line $errline \n", DEST_LOGFILE, LOG_FILE);
break;
}

// Don't execute PHP's internal error handler
return TRUE;
}


// Use set_error_handler() to tell PHP to use our method
$old_error_handler = set_error_handler("my_error_handler");

Error Report levels

These error report levels are the different types of error the user-defined error handler can be used for:
Value Constant Description
2 E_WARNING Non-fatal run-time errors. Execution of the script is not halted
8 E_NOTICE Run-time notices. The script found something that might be an error, but could also happen when running a script normally
256 E_USER_ERROR Fatal user-generated error. This is like an E_ERROR set by the programmer using the PHP function trigger_error()
512 E_USER_WARNING Non-fatal user-generated warning. This is like an E_WARNING set by the programmer using the PHP function trigger_error()
1024 E_USER_NOTICE User-generated notice. This is like an E_NOTICE set by the programmer using the PHP function trigger_error()
4096 E_RECOVERABLE_ERROR Catchable fatal error. This is like an E_ERROR but can be caught by a user defined handle (see also set_error_handler())
8191 E_ALL All errors and warnings, except level E_STRICT (E_STRICT will be part of E_ALL as of PHP 6.0)

Leia Mais…

Monday, December 7, 2009

Curl Setting in PHP

Below are the steps to configure the CURL option

1. Locate XAMPP install directory
2. open php/php.ini (probably C:\xampp\php\php.ini
or C:\ program files\apachefriends\xampp\php\php.ini)
3. do a search for the word ‘curl’ and uncomment (remove the leading semicolon) that line
before removing ;extension=php_curl.dll
after removing: extension=php_curl.dll
4. save & close
5. open apache/bin/php.ini (probably C:\xampp\apache\php.ini
or C:\ program files\apachefriends\xampp\apache\php.ini)
6. search for curl, uncomment as before (step 3)
7. save & close
8. Do not forget!javascript:void(0) restart apache

Leia Mais…

Monday, October 12, 2009

Using SimpleXML To Read & Parse XML in PHP

Using PHP we can read and execute the XML files. We can use the XML files to store the information as we do with the database.

PHP provides all the methods needed for the reading, writing and executing the XML files.Before that we need to know the XML.

An XML document comprises elements, attributes, processing instructions, comments, and entities

Element: Text delimited by an opening and a closing tag. A tag is a name enclosed within angle brackets.

Attribute: A piece of qualifying information for an element. An attribute consists of a name, an equals sign, and an attribute value delimited by either single-quotes or double-quotes.

Processing instruction: The software that is reading an XML document is referred to as a processor. A processing instruction is additional information embedded in the document to inform the processor and possibly change its behaviour.

Comment: An XML comment begins with the characters: less-than, exclamation mark, minus, minus; and ends with the characters: minus, minus, greater-than. Any text within a comment is intended for a human reader and is ignored by the processor.

Entity: An entity is a compact form that represents other text. Entities are used to specify problematic characters and to include slabs of text defined elsewhere. An entity reference consists of an ampersand, a name, and a semi-colon.

A simple XML file we will

<?xml version="1.0" encoding="utf-8" ?>

<people title="students"
>

<name1> student name 1
</name1>

<name2> student name 2
</name2>

<name3> student name 3
</name3>

</people>

Steps for reading this simple XML file is:

$xml = simplexml_load_file('names.xml');
This step will load the xml files. It Interprets an XML file into an object.Returns an object of class SimpleXMLElement with properties containing the data held within the XML document. On errors, it will return FALSE.

To read the data from the simple xml file we write code as
$xml = simplexml_load_file('names.xml');
print $xml->name1;
# Seperates outputs (easier to read & understand)
print "

";
# You call an attribute just like you would with an array: $array['arrayname/number']
print $xml['title'];

outputs : student name 1 ## Title output is -- name1

For an XML with multiple Items we write code as

<?xml version="1.0" encoding="utf-8" ?>
<student title="students">

<item id="1">
<name>
<first>ram</first>
<last>test</last>
</name>
<ageᡢ</age>
</item>

<item id="2">
<name>
<first>prince</first>
<last>kumar</last>
</name>
<ageᡃ </item>

<item id="3">
<name>
<first>raju</first>
<last>ramesh</last>
</name>
<ageᡍ</age>
</item>

</student>



# Load the test.xml file
$xml = simplexml_load_file('test.xml');
# Start a foreach loop. Translation: for every in the xml file put it into the var $item.
# now the $item can display all the elements inside the
foreach($xml->item as $item) {
# These three print's will display the attribute of the (ID), display the first and last name joined together
# and then the age. The
and

are for spacing out the results
print "ID: " . $item['id'] . "
";
print "Name: " . $item->name->first . " " . $item->name->last . "
";
print "Age: " . $item->age . "

";
}

If we want to provide the conditions when executing the XML files then the code will be

# Load the test.xml file
$xml = simplexml_load_file('test.xml');
# Start a foreach loop. Translation: for every in the xml file put it into the var $item.
# now the $item can display all the elements inside the
foreach($xml->item as $item) {
$age = $item->age;
if ($age >= 10) {
if ($age <= 21) {
# These three print's will display the attribute of the (ID), display the first and last name joined together
# and then the age. The
and

are for spacing out the results
print "ID: " . $item['id'] . "
";
print "Name: " . $item->name->first . " " . $item->name->last . "
";
print "Age: " . $item->age . "

";
}
}
}

Leia Mais…

Monday, October 5, 2009

Download functionality in PHP

The common usable component in any of the website is to provide the user with the download option. when providing the download option we cannot restrict the user with one the specific type like doc or ppt or pdf... We need to provide the most convenient way to the user so that the user can easily download the files.

Below is such script where we can have the multiple options provided.

$filename is the file name which we want to download

$file_extension = strtolower(substr(strrchr($filename,"."),1));

$folderpath="foldername/".$filename;

if( $filename == "" )
{
echo "No File Found";
exit;
} elseif ( ! file_exists( $folderpath ) )
{
echo "File Not Found";
exit;
};

// If file exits then it is ready for download.

switch( $file_extension )
{
case "pdf": $ctype="application/pdf"; break;
case "exe": $ctype="application/octet-stream"; break;
case "zip": $ctype="application/zip"; break;
case "doc": $ctype="application/msword"; break;
case "xls": $ctype="application/vnd.ms-excel"; break;
case "ppt": $ctype="application/vnd.ms-powerpoint"; break;
case "gif": $ctype="image/gif"; break;
case "png": $ctype="image/png"; break;
case "jpeg":
case "jpg": $ctype="image/jpg"; break;
default: $ctype="application/force-download";
}

// Decides the header... which type if download you are providing to the user.

header("Pragma: public"); // required
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false); // required for certain browsers
header("Content-Type: $ctype");
// change, added quotes to allow spaces in filenames, by Rajkumar Singh
header("Content-Disposition: attachment; filename=\"".basename($filename)."\";" );
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize($filename));
readfile("$folderpath");
exit();


Copy the above code if you want to download any type of the file in the given options

Leia Mais…

Friday, September 25, 2009

Php Arrays

An array is a data structure that stores one or more values in a single value.An array in PHP is actually an ordered map. A map is a type that associates values to keys. This type is optimized for several different uses; it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more. As array values can be other arrays, trees and multidimensional arrays are also possible

Each element in the array has its own index so that it can be easily accessed.

In PHP, there are three kind of arrays:

* Numeric array - An array with a numeric index
* Associative array - An array where each ID key is associated with a value
* Multidimensional array - An array containing one or more arrays

Numeric array
A numeric array stores each array element with a numeric index.

Example:

General:
$example=array("abc",123,"xyz","test");

In the following example we assign the index manually:
$example[0]="abc";
$example[1]=123;
$example[2]="xyz";
$example[3]="test";

we call the Indexed array as
echo $example[0] . " and " . $example[1] ;

or

foreach ($example as $i => $value) {
echo $value;
}

Associative Array
An associative array, each ID key is associated with a value.

Initializing an Associative Array

The following code creates an associative array with product names as keys and prices as values.

$prices = array( 'test1'=>100,
'test2'=>10, 'test3'=>4,'test4'=>5 );

There are different ways we can initialize the associative array

$prices = array( 'test1'=>100 );
$prices['test2'] = 10;
$prices['test3'] = 4;

Using Loops with Associative Arrays
Because the indices in this associative array are not numbers, we cannot use a simple counter in a for loop to work with the array. We can use the foreach loop or the list() and each() constructs.

The foreach loop has a slightly different structure when using associative arrays. We can use it exactly as we did in the previous example, or we can incorporate the keys as well:

foreach ($prices as $key => $value)
echo $key.'=>'.$value.'
';

The following code lists the contents of our $prices array using the each() construct:

while( $element = each( $prices ) )
{
echo $element[ 'key' ];
echo ' - ';
echo $element[ 'value' ];
echo '
';
}

Some of the Usefull methods are:

$b = array_values($a);

This will assign the the array a to the b and b will be considered as a array.

unset($arr[5]);
This will removes the particular element in the array

Leia Mais…