PHP Code Resources Part 5

localman

New Member
PHP:
### PHP Error Handling 


<?php
if(!file_exists("welcome.txt"))
  {
  die("File not found");
  }
else
  {
  $file=fopen("welcome.txt","r");
  }
?>
PHP:
### Creating a Custom Error Handler 
/*
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)
*/


function customError($errno, $errstr)
  {
  echo "<b>Error:</b> [$errno] $errstr<br />";
  echo "Ending Script";
  die();
  }
PHP:
### Set Error Handler 

<?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);
?>
PHP:
### 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.
*/

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

/*
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
*/ 

<?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);
  }
?>
PHP:
### Send an Error Message by E-Mail

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

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

//trigger error
$test=2;
if ($test>1)
  {
  trigger_error("Value must be 1 or below",E_USER_WARNING);
  }
?>
PHP:
### Basic Use of Exceptions

<?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);
?>
PHP:
### Try, throw and catch

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

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

//catch exception
catch(Exception $e)
  {
  echo 'Message: ' .$e->getMessage();
  }
?>
PHP:
### Creating a Custom Exception Class

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

$email = "[email protected]";

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

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

/*
Example explained:

The code above throws an exception and catches it with a custom exception class:
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
The errorMessage() function is created. This function returns an error message if an e-mail address is invalid
The $email variable is set to a string that is not a valid e-mail address
The "try" block is executed and an exception is thrown since the e-mail address is invalid
The "catch" block catches the exception and displays the error message

*/
PHP:
### Multiple Exceptions

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

$email = "[email protected]";

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

catch (customException $e)
  {
  echo $e->errorMessage();
  }

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

/*
The code above tests two conditions and throws an exception if any of the conditions are not met:
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
The errorMessage() function is created. This function returns an error message if an e-mail address is invalid
The $email variable is set to a string that is a valid e-mail address, but contains the string "example"
The "try" block is executed and an exception is not thrown on the first condition
The second condition triggers an exception since the e-mail contains the string "example"
The "catch" block catches the exception and displays the correct error message
*/
PHP:
### Re-throwing Exceptions
<?php
class customException extends Exception
  {
  public function errorMessage()
    {
    //error message
    $errorMsg = $this->getMessage().' is not a valid E-Mail address.';
    return $errorMsg;
    }
  }

$email = "[email protected]";

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

catch (customException $e)
  {
  //display custom message
  echo $e->errorMessage();
  }
?>
/*
Example explained:

The code above tests if the email-address contains the string "example" in it, if it does, the exception is re-thrown:
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
The errorMessage() function is created. This function returns an error message if an e-mail address is invalid
The $email variable is set to a string that is a valid e-mail address, but contains the string "example"
The "try" block contains another "try" block to make it possible to re-throw the exception
The exception is triggered since the e-mail contains the string "example"
The "catch" block catches the exception and re-throws a "customException"
The "customException" is caught and displays an error message
*/
PHP:
### Set a Top Level Exception Handler

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

set_exception_handler('myException');

throw new Exception('Uncaught Exception occurred');
?>
 

جدیدترین ارسال ها

بالا