PHP Error Handling

Posted on 2003-02-20
Medium Priority
Last Modified: 2007-12-19

     I am writing some error handling into my PHP application. The problem is, when an error occurs, the standard PHP error stuff shows up in addition to the error message I coded to show up. For example, here is a certain piece of code:

            $fp = fsockopen("$server", $port, $errno, $errstr, 60);

            if (!$fp)
                $this->ERROR = "Could not connect: Error [$errno] [$errstr]";
                return false;
            return true;

This is some code to connect to a server. If I enter an invalid server name, the following shows up:

Warning: fsockopen() [function.fsockopen]: php_hostconnect: connect failed in /var/www/dev.headlevel.com/htdocs/headmail/v2/headmail.php on line 19

Warning: fsockopen() [function.fsockopen]: unable to connect to localhost:999 in /var/www/dev.headlevel.com/htdocs/headmail/v2/headmail.php on line 19
Could not connect: Error [111] [Connection refused]

So I just want to know how to remove the first messages, and leave my own.

Thank you.
Question by:aether
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions

Expert Comment

ID: 7991734
write error_reporting(0); on top of your file..
it may help not sure...

Accepted Solution

laurly earned 150 total points
ID: 7992024
put an @ in frount of the command thats spitting out the error to turn error reporting off for just that function.

 $fp = @fsockopen("$server", $port, $errno, $errstr, 60);

LVL 40

Expert Comment

by:Richard Quadling
ID: 7992381
You can also set PHP to record errors in a log file rather than show them on the screen.

This is probably more useful as you get your error messages displayed and the error message from PHP logged.

This is from the PHP.INI-dist file, showing all the error logging options.

; Error handling and logging ;

; error_reporting is a bit-field.  Or each number up to get desired error
; reporting level
; E_ALL             - All errors and warnings
; E_ERROR           - fatal run-time errors
; E_WARNING         - run-time warnings (non-fatal errors)
; E_PARSE           - compile-time parse errors
; E_NOTICE          - run-time notices (these are warnings which often result
;                     from a bug in your code, but it's possible that it was
;                     intentional (e.g., using an uninitialized variable and
;                     relying on the fact it's automatically initialized to an
;                     empty string)
; E_CORE_ERROR      - fatal errors that occur during PHP's initial startup
; E_CORE_WARNING    - warnings (non-fatal errors) that occur during PHP's
;                     initial startup
; E_COMPILE_ERROR   - fatal compile-time errors
; E_COMPILE_WARNING - compile-time warnings (non-fatal errors)
; E_USER_ERROR      - user-generated error message
; E_USER_WARNING    - user-generated warning message
; E_USER_NOTICE     - user-generated notice message
; Examples:
;   - Show all errors, except for notices
;error_reporting = E_ALL & ~E_NOTICE
;   - Show only errors
;   - Show all errors except for notices
error_reporting  =  E_ALL & ~E_NOTICE

; Print out errors (as a part of the output).  For production web sites,
; you're strongly encouraged to turn this feature off, and use error logging
; instead (see below).  Keeping display_errors enabled on a production web site
; may reveal security information to end users, such as file paths on your Web
; server, your database schema or other information.
display_errors = On

; Even when display_errors is on, errors that occur during PHP's startup
; sequence are not displayed.  It's strongly recommended to keep
; display_startup_errors off, except for when debugging.
display_startup_errors = Off

; Log errors into a log file (server-specific log, stderr, or error_log (below))
; As stated above, you're strongly advised to use error logging in place of
; error displaying on production web sites.
log_errors = Off

; Set maximum length of log_errors. In error_log information about the source is
; added. The default is 1024 and 0 allows to not apply any maximum length at all.
log_errors_max_len = 1024

; Do not log repeated messages. Repeated errors must occur in same file on same
; line until ignore_repeated_source is set true.
ignore_repeated_errors = Off

; Ignore source of message when ignoring repeated messages. When this setting
; is On you will not log errors with repeated messages from different files or
; sourcelines.
ignore_repeated_source = Off

; If this parameter is set to Off, then memory leaks will not be shown (on
; stdout or in the log). This has only effect in a debug compile, and if
; error reporting includes E_WARNING in the allowed list
report_memleaks = On

; Store the last error/warning message in $php_errormsg (boolean).
track_errors = Off

; Disable the inclusion of HTML tags in error messages.
;html_errors = Off
; If html_errors is set On PHP produces clickable error messages that direct
; to a page describing the error or function causing the error in detail.
; You can download a copy of the PHP manual from http://www.php.net/docs.php 
; and change docref_root to the base URL of your local copy including the
; leading '/'. You must also specify the file extension being used including
; the dot.
;docref_root = /phpmanual/
;docref_ext = .html
; String to output before an error message.
;error_prepend_string = "<font color=ff0000>"

; String to output after an error message.
;error_append_string = "</font>"

; Log errors to specified file.
;error_log = filename

; Log errors to syslog (Event Log on NT, not valid in Windows 95).
;error_log = syslog

also check ...

http://www.php.net/manual/en/function.ini-set.php (for setting PHP.INI settings at runtime for your own code, rather than serverwide).


Expert Comment

ID: 7999278

prepend any function you need with the at-mark:


$str = @trim('wrong', 'parameters', 'list');

if(!str) {
   echo "there was some kind of error";


Maxim Maletsky

Expert Comment

ID: 8019740
Below is a custom error handling php file.  to use this just include this file at the top of all of your pages.

Use the above users suggestions of @ to stop php exceptions.  Then you can do your own error checking and throw an error using the function trigger_error(LEVEL);

// redefine the user error constants
define ("FATAL",E_USER_ERROR);
// we will do our own error handling
// user defined error handling function
function userErrorHandler ($errno, $errmsg, $filename, $linenum, $vars) {
// timestamp for the error entry
$dt = date("Y-m-d H:i:s (T)");
// define an assoc array of error string
// in reality the only entries we should
// consider are 2,8,256,512 and 1024
$errortype = array (
          1   =>  "Error",
          2   =>  "Warning",
          4   =>  "Parsing Error",
          8   =>  "Notice",
          16  =>  "Core Error",
          32  =>  "Core Warning",
          64  =>  "Compile Error",
          128 =>  "Compile Warning",
          256 =>  "User Error",
          512 =>  "User Warning",
          1024=>  "User Notice"
// set of errors for which a var trace will be saved
$user_errors = array(E_USER_ERROR, E_USER_WARNING, E_USER_NOTICE);

$err = "<errorentry>\n";
$err .= "\t<datetime>".$dt."</datetime>\n";
$err .= "\t<errornum>".$errno."</errornum>\n";
$err .= "\t<errortype>".$errortype[$errno]."</errortype>\n";
$err .= "\t<errormsg>".$errmsg."</errormsg>\n";
$err .= "\t<scriptname>".$filename."</scriptname>\n";
$err .= "\t<scriptlinenum>".$linenum."</scriptlinenum>\n";

if (in_array($errno, $user_errors)){
    $v = ob_get_contents();
    $err .= "\t<vartrace>$v</vartrace>\n";
$err .= "</errorentry>\n\n";

if($debug && $errno !=8){
   echo "<pre>$err</pre>";

// save to the error log, and e-mail me if there is a critical user error
if(!$debug && $errno != E_NOTICE){
   error_log($err, 3, "/home/espider/logs/error.log");
if ($errno == E_USER_ERROR ){
    mail("ganger2@adelphia.net","Critical User Error",$err);
  //redirect the user to the critical error page
  <META HTTP-EQUIV=Refresh CONTENT="0; URL=http://www.espiderwebdesign.com/gopost/error.html">


// set to the user defined error handler
$old_error_handler = set_error_handler("userErrorHandler");

 function user_msg($msg) {
    <script language="JavaScript">


Featured Post

WordPress Tutorial 4: Recommended Plugins

Now that you have WordPress installed, understand the interface, and know how to install new parts, let’s take a look at our recommended plugins.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Author Note: Since this E-E article was originally written, years ago, formal testing has come into common use in the world of PHP.  PHPUnit (http://en.wikipedia.org/wiki/PHPUnit) and similar technologies have enjoyed wide adoption, making it possib…
Many old projects have bad code, but the budget doesn't exist to rewrite the codebase. You can update this code to be safer by introducing contemporary input validation, sanitation, and safer database queries.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
Suggested Courses

777 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question