Powered By Blogger

Friday, 29 July 2011

Error Handling

When creating scripts and web applications, error handling is an important part. If your code lacks error checking code, your program may look very unprofessional and you may be open to security risks.
This tutorial contains some of the most common error checking methods in PHP.
We will show different error handling methods:
  • Simple "die()" statements
  • Custom errors and error triggers
  • Error reporting 
    Basic Error Handling: Using the die() function
    The first example shows a simple script that opens a text file:
    <?php
    $file=fopen("welcome.txt","r");
    ?>
    If the file does not exist you might get an error like this:
    Warning: fopen(welcome.txt) [function.fopen]: failed to open stream:
    No such file or directory in C:\webfolder\test.php on line 2
    To avoid that the user gets an error message like the one above, we test if the file exist before we try to access it:
    <?php
    if(!file_exists("welcome.txt"))
      {
      die("File not found");
      }
    else
      {
      $file=fopen("welcome.txt","r");
      }
    ?>
    Now if the file does not exist you get an error like this:
    File not found
    The code above is more efficient than the earlier code, because it uses a simple error handling mechanism to stop the script after the error.
    However, simply stopping the script is not always the right way to go. Let's take a look at alternative PHP functions for handling errors.

    Creating a Custom Error Handler
    Creating a custom error handler is quite simple. We simply create a special function that can be called when an error occurs in PHP.
    This function must be able to handle a minimum of two parameters (error level and error message) but can accept up to five parameters (optionally: file, line-number, and the error context):
    Syntax
    error_function(error_level,error_message,
    error_file,error_line,error_context)

    Parameter
    Description
    error_level
    Required. Specifies the error report level for the user-defined error. Must be a value number. See table below for possible error report levels
    error_message
    Required. Specifies the error message for the user-defined error
    error_file
    Optional. Specifies the filename in which the error occurred
    error_line
    Optional. Specifies the line number in which the error occurred
    error_context
    Optional. Specifies an array containing every variable, and their values, in use when the error occurred
    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)
    Now lets create a function to handle errors:
    function customError($errno, $errstr)
      {
      echo "<b>Error:</b> [$errno] $errstr<br />";
      echo "Ending Script";
      die();
      }
    The code above is a simple error handling function. When it is triggered, it gets the error level and an error message. It then outputs the error level and message and terminates the script.
    Now that we have created an error handling function we need to decide when it should be triggered.

    Set Error Handler
    The default error handler for PHP is the built in error handler. We are going to make the function above the default error handler for the duration of the script.
    It is possible to change the error handler to apply for only some errors, that way the script can handle different errors in different ways. However, in this example we are going to use our custom error handler for all errors:
    set_error_handler("customError");
    Since we want our custom function to handle all errors, the set_error_handler() only needed one parameter, a second parameter could be added to specify an error level.
    Example
    Testing the error handler by trying to output variable that does not exist:
    <?php
    //error handler function
    function customError($errno, $errstr)
      {
      echo "<b>Error:</b> [$errno] $errstr";
      }

    //set error handler
    set_error_handler("customError");

    //trigger error
    echo($test);
    ?>
    The output of the code above should be something like this:
    Error: [8] Undefined variable: test


    Trigger an Error
    In a script where users can input data it is useful to trigger errors when an illegal input occurs. In PHP, this is done by the trigger_error() function.
    Example
    In this example an error occurs if the "test" variable is bigger than "1":
    <?php
    $test=2;
    if ($test>1)
    {
    trigger_error("Value must be 1 or below");
    }
    ?>
    The output of the code above should be something like this:
    Notice: Value must be 1 or below
    in C:\webfolder\test.php on line 6
    An error can be triggered anywhere you wish in a script, and by adding a second parameter, you can specify what error level is triggered.
    Possible error types:
    • E_USER_ERROR - Fatal user-generated run-time error. Errors that can not be recovered from. Execution of the script is halted
    • E_USER_WARNING - Non-fatal user-generated run-time warning. Execution of the script is not halted
    • E_USER_NOTICE - Default. User-generated run-time notice. The script found something that might be an error, but could also happen when running a script normally
    Example
    In this example an E_USER_WARNING occurs if the "test" variable is bigger than "1". If an E_USER_WARNING occurs we will use our custom error handler and end the script:
    <?php
    //error handler function
    function customError($errno, $errstr)
      {
      echo "<b>Error:</b> [$errno] $errstr<br />";
      echo "Ending Script";
      die();
      }

    //set error handler
    set_error_handler("customError",E_USER_WARNING);

    //trigger error
    $test=2;
    if ($test>1)
      {
      trigger_error("Value must be 1 or below",E_USER_WARNING);
      }
    ?>
    The output of the code above should be something like this:
    Error: [512] Value must be 1 or below
    Ending Script
    Now that we have learned to create our own errors and how to trigger them, lets take a look at error logging.

    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.
    Send an Error Message by E-Mail
    In the example below we will send an e-mail with an error message and end the script, if a specific error occurs:
    <?php
    //error handler function
    function customError($errno, $errstr)
      {
      echo "<b>Error:</b> [$errno] $errstr<br />";
      echo "Webmaster has been notified";
      error_log("Error: [$errno] $errstr",1,
      "someone@example.com","From: webmaster@example.com");
      }

    //set error handler
    set_error_handler("customError",E_USER_WARNING);

    //trigger error
    $test=2;
    if ($test>1)
      {
      trigger_error("Value must be 1 or below",E_USER_WARNING);
      }
    ?>
    The output of the code above should be something like this:
    Error: [512] Value must be 1 or below
    Webmaster has been notified
    And the mail received from the code above looks like this:
    Error: [512] Value must be 1 or below
    This should not be used with all errors. Regular errors should be logged on the server using the default PHP logging system.

Thursday, 28 July 2011

Session Variables


When you are working with an application, you open it, do some changes and then you close it. This is much like a Session. The computer knows who you are. It knows when you start the application and when you end. But on the internet there is one problem: the web server does not know who you are and what you do because the HTTP address doesn't maintain state.
A PHP session solves this problem by allowing you to store user information on the server for later use (i.e. username, shopping items, etc). However, session information is temporary and will be deleted after the user has left the website. If you need a permanent storage you may want to store the data in a database.
Sessions work by creating a unique id (UID) for each visitor and store variables based on this UID. The UID is either stored in a cookie or is propagated in the URL.

Starting a PHP Session
Before you can store user information in your PHP session, you must first start up the session.
Note: The session_start() function must appear BEFORE the <html> tag:
<?php session_start(); ?>

<html>
<body>

</body>
</html>
The code above will register the user's session with the server, allow you to start saving user information, and assign a UID for that user's session.

Storing a Session Variable
The correct way to store and retrieve session variables is to use the PHP $_SESSION variable:
<?php
session_start();
// store session data
$_SESSION['views']=1;
?>

<html>
<body>

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

</body>
</html>
Output:
Pageviews=1
In the example below, we create a simple page-views counter. The isset() function checks if the "views" variable has already been set. If "views" has been set, we can increment our counter. If "views" doesn't exist, we create a "views" variable, and set it to 1:
<?php
session_start();

if(isset($_SESSION['views']))
$_SESSION['views']=$_SESSION['views']+1;
else
$_SESSION['views']=1;
echo "Views=". $_SESSION['views'];
?>


Destroying a Session
If you wish to delete some session data, you can use the unset() or the session_destroy() function.
The unset() function is used to free the specified session variable:
<?php
unset($_SESSION['views']);
?>
You can also completely destroy the session by calling the session_destroy() function:
<?php
session_destroy();
?>
Note: session_destroy() will reset your session and you will lose all your stored session data.


number and a message describing the error is sent to the browser

What is a Cookie?


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

How to Create a Cookie?

The setcookie() function is used to set a cookie.
Note: The setcookie() function must appear BEFORE the <html> tag.

Syntax

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

Example 1

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);
?>

<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).

Example 2

You can also set the expiration time of the cookie in another way. It may be easier than using seconds.
<?php
$expire=time()+60*60*24*30;
setcookie("user", "Alex Porter", $expire);
?>

<html>
.....
In the example above the expiration time is set to a month (60 sec * 60 min * 24 hours * 30 days).

How to Retrieve a Cookie Value?

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

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

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

// A way to view all cookies
print_r($_COOKIE);
?>
In the following example we use the isset() function to find out if a cookie has been set:
<html>
<body>

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

</body>
</html>


How to Delete a Cookie?

When deleting a cookie you should assure that the expiration date is in the past.
Delete example:
<?php
// set the expiration date to one hour ago
setcookie("user", "", time()-3600);
?>


What if a Browser Does NOT Support Cookies?

If your application deals with browsers that do not support cookies, you will have to use other methods to pass information from one page to another in your application. One method is to pass the data through forms (forms and user input are described earlier in this tutorial).
The form below passes the user input to "welcome.php" when the user clicks on the "Submit" button:
<html>
<body>

<form action="welcome.php" method="post">
Name: <input type="text" name="name" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>

</body>
</html>
Retrieve the values in the "welcome.php" file like this:
<html>
<body>

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

</body>
</html>

Tuesday, 8 February 2011

Back-tick operator

Backtick operator is actually a combination of two back ticks...... back ticks are not  quotes.... back tick is usually located on the same key on which the tilde mark can be found .



back tics are used to execute what ever comes between these two individuals ....as a server command depending upon server command line language


`command to execute`

The error suppression operator

error suppression operator @ should be kept before the anything that evaluates  to be some value.

$a=@(300/0);

in this way the divide by zero error will not be generated during the runtime although you will need to write some error handling code when the warning is generated.....

if you have track_error option enabled in php.ini file then this message will be stored in $php_errormsg variable.....

Parse the URL


Lets take a simple example of an URL with some attached Query string
WWW. Facebook.com?&src=india&sid=2748472&ver=2hqhwu&height=123

so as u see that now if you need  to use these parameters those have come to you in the form of a query string you  have to parse them down so here is  what you can try

$src = urldecode($_GET['src']);

$sid = urldecode($_GET['sid']);

$ver = trim(urldecode($_GET['ver']));

$height = urldecode($_GET['h']);





here we are using the urlencode() function to convert the values of the $_GET[] global array in human readable form

The magical operator:The ternary operator

Ternary the magical operator is a very useful tool while you need to code frequently .....it enables you to work more frequently while you need to push a value on a variable depending upon the evaluation of any condition

                                                    condition ? 'value1' : 'value2'

if the condition evaluates to be true then the outcome of the above line will be 'value1' else value2....

until now i know your mind must be striking to say ohhhh    i can do this with then if ...else logic

but my friend i will love to say just taste it once and u will definitely become the fan of it's spice.......


very recently i was looking at some work done by my seniors..where i could see the really intense and smart utilization of this amazing tool........