Return error php

return error php

Error handling is the process of catching errors raised by your program and then taking appropriate action. If you would handle errors properly then it may. If your Slim Framework application throws a PHP Runtime error (PHP 7+ only), the application invokes its PHP Error handler and returns a HTTP/1.1 500. errorLevel - int - The level of errors you are interested in capturing. Use the built-in PHP error constants, and bitmasks to select the level of error you are.

Join: Return error php

Return error php
ERROR CODE 2000-014 HARD DRIVE
Return error php
HARD DISK FAILURE ERROR MESSAGE

Improve PHP Error Messages in IIS 7

  • Article
  • 5 minutes to read

by Tali Smith

PHP errors often do not provide sufficient detail to help diagnose errors that occur within the framework. These include return error php errors such as 404 Not Found. Because of this, the default "detailed error" experience for PHP applications may be ineffective for troubleshooting basic errors.

Internet Information Services (IIS) improves PHP return error php handling by intercepting common error conditions and providing redirection for common HTTP status codes.

By default, IIS is configured to return detailed error messages to local clients and to return generic error messages to remote clients. This is done to allow effective troubleshooting locally, while protecting production applications from disclosing sensitive details to remote clients when errors occur.

IIS generates very detailed error messages for most errors. These contain, at minimum, information about the request and the error, including which module generated the error and during which part of the request processing. For errors caused by IIS and its built-in modules, the errors also contain likely resolutions. This dramatically simplifies the troubleshooting process for most errors.

This article, based on the hands-on labs in the PHP on Windows Training Kit, describes how IIS takes care of basic errors handling and how IIS diagnoses application-level errors by enabling PHP error messages.

Basic Error Handling

IIS improves PHP error handling by intercepting common error conditions and providing redirection for common HTTP status codes.

Note that IIS also support error messages generated by application frameworks, which often offer application-specific information to help diagnose application errors. For example, Microsoft® ASP.NET takes advantage of this to provide detailed exception stack traces and other information.

If you request the page from Windows® Internet Explorer®, you get a default "Not Found" error—a non-descriptive 404 error page.

Screenshot of a browser window with a non-descriptive 404 error message displayed.
Figure 1: A non-descriptive 404 error message

The default IIS "Not Found" error message provides useful information to help diagnose the error condition; it correctly identifies the error and suggests solutions for most common error conditions by providing information such as the source (module, notification) of the error and background information such as the URL, mapped physical path, and the authentication method being used. For example:

  • Response information: HTTP 404 Not Found.
  • Detailed error information: The module (IIS Web Core), the Notification (MapRequestHandler), the handler (StaticFileHandler), and the error code (0x80070002 – File Not Found).
  • Request information: The requested URL and the physical path .
  • The "Most likely causes" section correctly suggests the most likely error cause to be: "The directory or file specified does not exist on return error php Web server".
  • The "Things you can try" section suggests the corresponding solution: "Create the content on the Web server".

Screenshot of a browser window displaying a detailed 404 error message.
Figure 2: Detailed 404 error message

You can also get Return error php detailed errors syntax error 2 original some PHP errors return error php configuring IIS to perform some additional validation of PHP requests.

To configure IIS to provide additional validation of PHP requests, return error php, use the following steps:

  1. Switch to the IIS Manager. If it is closed, return error php, click Start,and then select Internet Information Services (IIS) Manager.

  2. In the tree view on the left, click the server node.

  3. Under IIS, double-click Handler Mappings to edit the PHP handler mapping.

  4. Right-click the PHP via FastCGI entry, and then click Edit.

  5. Click Request Restrictions.

  6. Select the Invoke handler only if request is mapped to check box.

  7. Leave the return error php option button selected.

  8. Click OK twice.

  9. Click Yes in the Edit Module Mapping dialog box.

  10. To test, trigger a "Not Found" condition again to verify that the PHP 404 error is now handled by IIS, return error php, providing more detail. Using Internet Explorer, request (this page does not exist).

  11. You receive an IIS detailed error indicating that the Notfound.php page was not found on the server.

    An IIS 401.3 Unauthorized detailed error also provides information; it indicates that the request does not have the permission to view the page due to access control list (ACL) configuration and provides an extensive explanation of how to resolve this issue.

    Screenshot of a browswer window with an unauthorized detailed error displayed.
    Figure 3: An Access Denied error

Enable PHP Error Messages to Diagnose Application-Level Errors

Configuring IIS to validate requests causes IIS to attempt to open the PHP script file corresponding to the request URL and generates detailed error messages for any conditions that preclude this, return error php. This typically includes:

  • File not found
  • Access denied due to incorrect permissions
  • Access denied due to insufficient authentication
  • For most other error conditions, especially those that occur at the application level, IIS detailed error messages do not contain sufficient information to help diagnose the error effectively.

The biggest examples of such errors are script parsing and script interpretation errors. While you can force IIS detailed error messages for these errors, this typically does not provide any value in diagnosing the pixma mp140 error 5100 cause of the error. In these cases, you must rely on the information provided by PHP to diagnose these errors.

By default, PHP is not configured to display these errors to the response to prevent disclosure of sensitive information.

Notethat for local debugging, return error php, you can enable PHP error display to diagnose PHP errors while debugging. Consider disabling PHP error display for production applications.

If you request a page with a script error, you receive the IIS detailed error message. This happens because by default PHP does not generate a response with the error details, so IIS inserts its generic "500 Server Error" detailed error. While this error correctly suggests that PHP has returned a 500 error code, it does not provide application-specific information about what caused the error.

You can configure PHP to display errors in responses.

  1. Using Windows® Explorer, return error php, browse to .

  2. Open the Php.ini filein the PHP installation directory.

  3. Find and set the display_errors = On directive:

  4. Save and close the file.

  5. Reset IIS. Click Start,and then select Command Prompt, right click and select Runas administrator to open a command-line window.

  6. Type iisreset.exe

  7. Press Enter.

If you request a page with a script error now, you get a PHP parse error:

If you see only the default Internet Explorer HTTP 500 Internal Server Error page, you must disable friendly error messages. Within Internet Explorer Go to Tools, Internet Options, Advanced tab, and then clear the Show friendly HTTP error messages check box.

Note that PHP also provides options for customizing keygen terrorist takedown 2 error handling or completely overriding it.

Note: This article return error php material from the PHP on Windows Training Kit, published on August 25, 2009.

See also

A PHP application might produce many different levels of earning and errors during its execution. Being able to see these errors is essential for developers trying to troubleshoot a misbehaving application. However, developers often have trouble when trying to display errors from their PHP applications. Instead, their apps just fail silently.

If you are having problems with your PHP web application and need to display all the errors and warnings, you are in the right place. In this tutorial, we will explain all the different ways to enable PHP errors and warnings. We will also discuss how to write the errors to a log file and even collect them via the Retrace’s error tracking feature.

Quickly Show All PHP Errors

The quickest way to display all php errors and warnings is to add these lines to your PHP code file:

ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL);

What Do These Lines of Code Do Exactly?

The ini_set function will try to override the configuration found in your PHP ini file.

The display_errors and display_startup_errors are just two of the directives that are available. The display_errors directive will determine if the errors will be displayed or hidden to the user. Usually, the dispay_errors directive should be turned off after development.

The display_startup_errors, however, is a separate directive because the display_errors doesn’t handle the errors that will be encountered during PHP’s startup sequence. The list of the directives that can be overridden by the ini_set function is found in the official documentation.

Unfortunately, return error php, these two directives won’t be able to display parse errors such as missing semicolons or missing curly braces. In this case, the PHP ini configuration must be modified.

Configure PHP.ini to Display All Errors

If adding some of the PHP code errors doesn’t show in the browser during testing, then the PHP ini configuration has some additional directives to handle this.

display_errors = on

The display_errors directive must be set to “on” in the PHP ini file. This will display all the errors including syntax or parse errors that cannot be displayed by just calling the ini_set function in the PHP code. The PHP ini file can be found in the displayed output of phpinfo() function and is labeled loaded configuration file. This directive in the ini configuration must be set to off, if the web application is in production.

Display PHP Errors via .htaccess Configuration

Developers usually have access to the directory files. The directive for showing PHP errors can also be enabled or disabled using the .htaccess file located in the root or public directory of the project.

php_flag display_startup_errors on php_flag display_errors on

Similar to what will be added to the PHP code to show PHP errors. htaccess also has directives for display_startup_errors and display_errors. The advantage of showing or disabling error messages in this manner is that development and production can have different .htaccess files, where the production suppresses the displaying of errors.

Depending on which files you have access to and how you do deployments and server configurations, you may want to configure display_errors in .htaccess or your PHP.ini file. Many hosting providers will not allow you to modify your PHP.ini file to enable display_errors.

In the .htaccess file, a custom error log can also be enabled as long as the log folder or the log file is writable by the web server, return error php. The log file can be a relative path to where the .htaccess is located, or it can be an absolute path such as /var/www/html/website/public/logs.

php_value error_log logs/all_errors.log

Enable Detailed Warnings and Notices

Sometimes, the warnings that seem not to affect return error php application at the start will cause some fatal errors in certain conditions. These warnings must be fixed because this means that the application won’t run normally under certain scenarios. In case these warnings cause a lot of errors, then it would be more practical to hide the errors and just show what the warning messages are.

error_reporting(E_WARNING);

For a developer, return error php, showing warnings and hiding errors is just as simple as adding a single line of code. To show warnings and notices, the parameter for the error reporting function will be “E_WARNING

How To Return Status Codes In PHP

Status codes, the status of a p[age being requested from a web server can be generated in a number of different ways. Here we show you how this is done in PHP code – a language that can be used to generate HTML web pages directly.

When browsing the internet as a user, you are probably unaware of the secret messaging that is being sent back and forth between where the website is being hosted and your browser. 

For example, domain names are actually a series of numerical combinations. Status codes are similar in that they give information about if a page has loaded successfully or not, and the root cause of any errors. PHP is a scripting language that can generate status-code data.

While your content management system, possibly (WordPress) and your web server (possibly Apache) can generate these codes, the scripting language PHP, which is the basis of WordPress, can also generate these codes.

Why use PHP to generate status codes?

PHP is the language that WordPress is built on. If you are thinking of adapting your WordPress theme, or even writing additional pages using Return error php, you might want to use status codes to return a positive status code, to redirect the request to another page or site, or to advise that a page is not available. For example, you have deleted a lot of content and you want to provide a special landing page to tell robots and users that this specific content has been removed, and why. Or, return error php, you may want to write a simple PHP script to tell users when the site is under maintenance.

What are Status Codes?

HTTP status codes are a way that servers communicate with clients (browsers). For the most part, the page loads successfully and so an ‘ok’ 2xx code will be generated, return error php. In such a case, status codes remain invisible to the user. But status codes are there to cover all eventualities, such as a 404 error or even a 502 bad gateway, which will be visually displayed on the page as an error message. 

Understanding status codes will allow you to enhance your user experience, especially if your website visitors are receiving error codes that originate from your server as an example. 

As the practice is quite technical, status codes are usually implemented manually by someone who understands coding such as a web developer. However, if your website is on WordPress, then plugins do exist to help you make sense and implement status codes. 

Of course, as a website user, you may also come across status codes on other websites too. For example, return error php forbidden can be generated if you try to access a section of a website that you don’t have permission to view.  

HTTP Status Code Types – Overview

  • 1xx informational return error php success
  • 3xx redirection
  • 4xx client errors
  • 5xx server errors
  • Unofficial status codes

More detail is available in our http status code overview article.

PHP – An Overview

PHP stands for hypertext preprocessor. As you may have noticed, the acronym is a little confusing and that’s because PHP originally stood for personal home page. Remember, return error php, the way we develop websites has changed immensely in the short time the internet has existed, return error php, so sometimes terms need to be updated to keep up to modern standards.

Whenever you request a URL, a complex chain occurs between the server and the browser. PHP is usually involved in this process, as it’s responsible for interpreting the data. A common example of where you would see PHP in action is a login page, return error php. As you enter your credentials, a request to the server is made, and PHP will communicate with the database to log you in. 

Essentially, PHP is a scripting language that is embedded into HTML. For a quick example, left click on any webpage and select ‘view page source’. Doing so will bring up the code that makes up that page. It is your browser that interprets the code into the functional version of the website. 

With PHP, code can either be processed client side (HTML, Javascript and CSS) or server side (PHP). In essence, the server side of PHP is software that is installed on the server. This software can include Linux, Apache, MySQL and finally PHP. In that order, these 4 elements make up what’s known as a LAMP stack. The PHP is the scripting layer of return error php combination which websites and web applications run off.

Returning A Status Code In PHP

To return a status code in PHP, the simplest way is to use the http_response_code() function, along with the relevant HTTP status code parameter into your website, followed by the exit() command which stops any more output being set.

This means the likes of 400 bad requests and 404 not found can all be implemented with just one line of code.

Important: The http_response_code and header() commands must be used before any HTML is returned. 

Example: Return a 400 bad request status code

Example: Return a 404 not found status code

Example: Return a 301 moved permanently status code

This example php code also requires that you provide the new URL, to which the users browser will automatically redirect. For this you need to use the more details header() function.

The exit command return error php that no other php code or html code will be output from the page.

Here’s example code for a 503 temporary error page that also includes additional information that is shown in the browser.

Why Status Codes Matters For SEO

As the name suggests, SEO is all about catering to search engines, so that users are more likely to come across your site, return error php. Search engines actively crawl status codes and will determine how your site is indexed as a result. 

For example, return error php, if your site has plenty of 404 errors that exist from internal or external, links then this can harm your rankings because this will not generate a helpful experience for users, return error php. In a nutshell, search engines are looking out for healthy status codes, as this indicates everything is ticking over as it should be. 

Further Reading

The above gives a brief overview of returning status codes in PHP. However, given the complex nature of coding it’s impossible to cover everything in just one article alone. So we definitely suggest doing some further reading to increase your understanding. 

Resources you may find helpful include the official PHP website. In particular, their Using PHP section covers common errors you may encounter, especially as you get to grips with it.  

Remember, when building any code it’s essential to test it. Even a small error or even a bug can disrupt the final result, so it’s good to remember that PHP isn’t just about the writing of the script, but seeing it through to a working page. Plus, looking out for any errors that may occur further down the line. 

23.12.2020

Handling Errors ¶

Yii includes a built-in error handler which makes error handling a much more pleasant experience than before. In particular, the Yii error handler does the following to improve error handling:

  • All non-fatal PHP errors (e.g. warnings, notices) are converted into catchable exceptions.
  • Exceptions and fatal PHP errors are displayed with detailed call stack information and source code lines in debug mode.
  • Supports using a dedicated controller action to display errors.
  • Supports different error response formats.

The error handler is enabled by default. You may disable it by defining the constant to be in the entry script of your application.

Using Error Handler ¶

The error handler is registered as an application component named. You may configure it in the application configuration like the following:

With the above configuration, the number of source code lines to be displayed in exception pages will be up to 20.

As aforementioned, return error php, the error handler turns all non-fatal PHP errors into catchable exceptions. This means you can use the following code to deal with PHP errors:

If you want to show an error page telling the user that his request is invalid or unexpected, you may simply throw an HTTP exception, such as yii\web\NotFoundHttpException. The error handler will correctly set the HTTP status code of the response and use an appropriate error view to display the error message.

Customizing Error Display ¶

The error handler adjusts the error display according to the value of the constant. When is (meaning in debug mode), the error handler will display exceptions with detailed call stack information and source code lines to help easier debugging. Return error php when isonly the error message will be displayed to prevent revealing sensitive information about the application.

Info: If an exception is a descendant of yii\base\UserException, no call stack will be displayed regardless the value of. This is because such exceptions are considered to be caused by user mistakes and the developers do not need to fix anything.

By default, the error handler displays errors using two views:

  • : used when errors should be displayed WITHOUT call stack information. When isreturn error php, this is the only error view to be displayed.
  • : used when errors should be displayed WITH call stack information.

You can configure the errorView and exceptionView properties of the error handler to use your own views to customize the error display.

Using Error Actions ¶

A better way of customizing the error display is to use dedicated error actions. To do so, return error php, first configure the errorAction property of the component like the following:

The errorAction property takes a route to an action. Return error php above configuration states that when an error needs to be displayed without call stack information, return error php, the action should be executed.

You can return error php the action as follows,

The above code defines the action using the yii\web\ErrorAction class which renders an error using a view named .

Besides using yii\web\ErrorAction, you may also define the action using an action method like the following,

You should now create a view file located at. In this view file, return error php, you can access the following variables if the error action is defined as yii\web\ErrorAction:

  • : the name of the error;
  • : the error message;
  • : the exception object through which you can retrieve more useful information, such as HTTP status code, error code, return error php, error call stack, etc.

Info: If you are using the basic project template or the advanced project template, the error action and the error view are already defined for you.

Note: If you need to redirect in an error handler, do it the following way:

Customizing Error Response Format ¶

The error handler displays errors according to the format setting of the response. If the response format isreturn error php will use the error or exception view to display errors, as described in the last subsection. For other response formats, the error handler will assign the array representation of the exception to the yii\web\Response::$data property which will then be converted to different formats accordingly. For example, if the response format isyou may see the following response:

You may customize the error response format by responding to the event of the component in the application configuration:

The above code will reformat the error response like the following:

” character represents either one as long as it is true. These two characters have the same meaning in PHP conditions OR and AND.

error_reporting(E_ALL); error_reporting(-1); ini_set('error_reporting', E_ALL);

These three lines of codes do exactly the same thing, it will show all PHP errors. The error_reporting(E_ALL) is the most widely used among developers to show error messages because it is more readable and understandable.

Log PHP errors to a file using the error_log() function

During production, error messages must not be shown to the end users, but this information must still be recorded for tracing samba read_fd_with_timeout client 0.0.0.0 read error. The best way to record these error messages on a production web application is to store it in log files.

One easy way to use log files is to use the error_log function, which accepts four parameters. The only required parameter is the first parameter, which contains the details about the error or what’s to be logged. The type, destination, and header are all optional parameters for this function.

error_log("There is something wrong!", 0);

The type parameter, if not defined, will be 0 by default, which means this log information will be appended to whatever log file is defined in the web server.

error_log("Email this error to someone!", 1, "[email protected]");

The type 1 parameter will email an error log specified in return error php third parameter. To make this feature work, the PHP ini must have a proper SMTP configuration to be able to send out emails. These SMTP ini directives include host, encryption type, username, return error php, password, and port. This kind of error reporting is advisable to logging or notifying errors that need to be fixed as soon as found.

error_log("Write this error down to a file!", 3, "logs/my-errors.log");

To log messages in a separate file defined by the configuration of the web server, then type 3 must be used. The third parameter will serve as the location of the log file and must be writable by the web server. The location of the log file can be a relative path to where this code is called or an absolute path.

Log PHP Errors Through the Web Server Configuration

To avoid l7 critical error 84 42 parameters in the .htaccess or adding some lines in the PHP code to show errors, return error php, then the best way to log errors is defining it in the web server configuration file.

ErrorLog "/var/log/apache2/my-website-error.log"

For Apache, these files must be added return error php the virtual host of the specific website or application, return error php located inside the sites-available folder for Ubuntu or httpd-vhosts file in Windows.

error_log /var/log/nginx/my-website-error.log;

For nginx, similar to Apache, the directive is just called error_log. For both Apache and nginx web servers, the log files must be writable by the web server. Luckily, upon installation, the folders for the log files of these two web servers are already writable.

Automatically Collect PHP Errors With Retrace APM

Retrace is an APM (Application Performance Management) tool offered by Stackify. But the tool goes beyond monitoring the performance of your application. It allows you to do centralize logging, return error php, perform code profiling, and stay on top of server and application metrics.

One of the great features of Retrace is its ability to automatically collect all unhandled errors in your PHP application. Our PHP extension will catch the exception and forward them automatically to Retrace.

With Retrace, all the errors are automatically logged and formatted so that it can be viewed easily. Retrace will not only show what errors have occurred but also analyzes where return error php what caused it. The time and number of occurrences are also shown in the logs so that it would be a lot easier to focus on which issue to prioritize.

To learn more about Retrace, please check out the Retrace feature page on error tracking. Also, try Stackify’s free code profiler, Prefix, to write better code on your workstation. Prefix works with .NET, Java, PHP, Node.js, Ruby, return error php, and Python.

About Juliet Mendez

Juliet Mendez is a Professor in the Department of Computer and Information Sciences and a PhD student specializing in Information Technology. She has a background in CCNA, computer programmings such as PHP, JAVA, Mobile Development, and Project Management.

return error php

Return error php - regret, that

The new interface

While PHP 7 provides both Error and Exception classes, let’s check the Throwable interface first. Both Error and Exception classes implement Throwable interface – it's a basis for any object that can be thrown via throw statement. It only has one exception to notice, it cannot be implemented in userland classes directly, but only through extending the Exception class. Also, it provides a single point for catching both types of error in a single statement:

List of available built-in exception classes since PHP 7.4:

More Exception classes can be found inside PHP’ Standard Library. And the most notable one that comes from the JSON extension is the JsonException class.

Error, what?

In previous versions of PHP, errors were treated quite differently than exceptions. An error was something that was produced in the engine and as long as it was not fatal, it could be handled by a user-defined function.

The problem was that there were several errors that were fatal and that could not be handled by a user-defined error handler. This meant that you couldn’t handle fatal errors in PHP gracefully. There were several side-effects that were problematic, such as the loss of runtime context, destructors would not be called and dealing with them was clunky. In PHP 7, fatal errors are now exceptions and we can handle them very easily. Fatal errors result in an error exception being thrown. You need to handle non-fatal errors with an error-handling function.

Here is an example of catching a fatal error in PHP 7.1. Notice how the non-fatal error is not caught.

This script will output a notice error for the attempt to access an invalid variable. Trying to call a function that does not exist would result in a fatal error in earlier versions of PHP, but in PHP 7.1 you can catch it. Here is the output for the script:

Error constants

PHP has a lot of constants that are used in relation to errors. These constants are used when configuring PHP to hide or display errors of certain classes.

Here are some of the most commonly seen error codes:

  • E_DEPRECATED – the interpreter will generate this type of warnings if you use a deprecated language feature. The script will definitely continue to run without errors.
  • E_STRICT – similar to E_DEPRECATED, this indicates that you are using a language feature that is not standard currently and might not work in the future. The script will continue to run without any errors thrown.
  • E_PARSE – your syntax could not be parsed so your script won’t start. Script execution will not even start.
  • E_NOTICE – the engine will just print out an informational message. Script execution won’t break and none of the errors will be thrown.
  • E_ERROR – the script cannot continue running and it is being terminated. Will throw errors and how these are going to be handled depends on the error handler.
  • E_RECOVERABLE_ERROR – it indicates that a probably dangerous error occurred, but did not leave the Engine in an unstable state. Further execution depends on the error handler and error will definitely be thrown.

For full list of constants please consult the PHP manual.

Error handler function

The set_error_handler() function is used to tell PHP how to handle standard engine errors that are not instances of the Error exception class. You cannot use an error-handler function for fatal errors. Error exceptions must be handled with try/catch statements. set_error_handler() accepts a callable as its parameter. Callables in PHP can be specified in two ways: either by a string denoting the name of a function or by passing an array that contains an object and the name of a method (in that order). You can specify protected and private methods as the callable in an object. You can also pass null to tell PHP to revert to the usage of the standard error-handling mechanism. If your error handler does not terminate the program and returns, your script will continue executing at the line after the one where the error occurred.

PHP passes parameters to your error-handler function. You can optionally declare these in the function signature if you want to use them in your function.

Here is an example of custom:

If you run this code in PHP console php -a you should receive similar output:

The most prominent PHP libraries that do extensive usage of PHP’s set_error_handler() and can do nice representations of exceptions and error are Whoops or Symony’s Debug and ErrorHandler components. My suggestion is to use one of those. If not, you can always draw inspiration from their code. While Debug component has extensive usage within the Symfony ecosystem, Whoops remains library of choice for Laravel framework. 

For detailed and advanced usage, please consult PHP manual on error handler.

Displaying or suppressing the non-fatal error message

When you application reaches production, you want to hide all system error messages while in production and your code must run without generating warnings or messages. If you are going to show an error message, make sure that it is the one you’ve generated and that it does not include information that could help an attacker break into your system.

In your development environment, you want all errors to be displayed so that you can fix all the issues they relate to, but while in production, you want to suppress any system messages being sent to the user.

To accomplish this, you need to configure PHP using the following settings in your php.ini file:

  • display_errors – can be set to false to suppress messages
  • log_errors – can be used to store error messages in log files
  • error_reporting – can be set to configure which errors trigger a report

The best practice is to handle errors in your application gracefully. In production, you should rather log unhandled errors instead of allowing them to be displayed to the user. The error_log() function can be used to send a message to one of the defined error handling routines. You can also use the error_log() function to send emails, but personally, would rather use a good solution for logging errors and receiving notifications when an error occurs like Sentry or Rollbar.

There is a thing called Error Control Operator – the at-sign (@) – that in the essence can ignore and suppress errors. The usage is very easy – just prepend any PHP expression with at-sign and generated error will be ignored. Although using this operator may look interesting, I urge you not to do that. I like to call it the living relict from the past.

More information for all PHP error related function can be found in manual.

Exceptions

Exceptions are a core part of object-oriented programming and were first introduced in PHP 5.0. An exception is a program state that requires special processing because it’s not running in an expected manner. You can use an exception to change the flow of your program, for example, to stop doing something if certain preconditions are not met.

An exception will bubble up through the call stack if you do not catch it. Let’s check a simple example:

PHP includes several standard exception types, and the standard PHP library (SPL) includes a few more. Although you don’t have to use these exceptions, doing so means you can use more fine-grained error detection and report. The Exception and Error classes both implement the Throwable interface and, like any other classes, can be extended. This allows you to create flexible error hierarchies and tailor your exception handling. Only a class that implements the Throwable class can be used with the throw keyword. In other words, you can’t declare your own base class and then throw it as an exception.

Robust code can encounter an error and cope with it. Handling exceptions in a sensible way improves the security of your application and makes logging and debugging easier. Managing errors in your application will also allow you to offer your users a better experience. In this section, we cover how to trap and handle errors that occur in your code.

Catching exceptions

Let’s look at this simple example:

As you can see, there are two catch clauses. Exceptions will be matched against the clauses from top to bottom until the type of exception matches the catch clause. This very simple throwMyCustomException() function throws MyCustomException and we expect it to be caught in the first block. Any other exceptions that will occur will be caught by the second block. Here we are calling getMessage() method from the base Exception class. You can find more information about additional method in Exception PHP docs.

You can also specify multiple exceptions by separating them with a pipe (

PHP - Error & Exception Handling



Error handling is the process of catching errors raised by your program and then taking appropriate action. If you would handle errors properly then it may lead to many unforeseen consequences.

Its very simple in PHP to handle an errors.

Using die() function

While writing your PHP program you should check all possible error condition before going ahead and take appropriate action when required.

Try following example without having /tmp/test.xt file and with this file.

<?php if(!file_exists("/tmp/test.txt")) { die("File not found"); }else { $file = fopen("/tmp/test.txt","r"); print "Opend file sucessfully"; } // Test of the code here. ?>

This way you can write an efficient code. Using above technique you can stop your program whenever it errors out and display more meaningful and user friendly message.

Defining Custom Error Handling Function

You can write your own function to handling any error. PHP provides you a framework to define error handling function.

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);
Sr.NoParameter & Description
1

error_level

Required - Specifies the error report level for the user-defined error. Must be a value number.

2

error_message

Required - Specifies the error message for the user-defined error

3

error_file

Optional - Specifies the file name in which the error occurred

4

error_line

Optional - Specifies the line number in which the error occurred

5

error_context

Optional - Specifies an array containing every variable and their values in use when the error occurred

Possible Error levels

These error report levels are the different types of error the user-defined error handler can be used for. These values cab used in combination using

PHP Error Functions

NameDefaultDescriptionChangeableerror_reportingNULLSets the error reporting level (either an integer or  named constants)PHP_INI_ALLdisplay_errors"1"Specifies whether errors should be printed to the screen, or if they should be hidden from the user.
Note: This feature should never be used on production systems (only to support your development)PHP_INI_ALLdisplay_startup_errors"0"Even when display_errors is on, errors that occur during PHP's startup sequence are not displayed
Note: It is strongly recommended to keep display_startup_errors off, except for debuggingPHP_INI_ALLlog_errors"0"Defines whether script error messages should be logged to the server's error log or error_log.
Note: It is strongly advised to use error logging instead of error displaying on production web sitesPHP_INI_ALLlog_errors_max_len"1024"Sets the maximum length of log_errors in bytes. The value "0" can be used to not apply any maximum length at all. This length is applied to logged errors, displayed errors, and also to $php_errormsg (available since PHP 4.3)PHP_INI_ALLignore_repeated_errors"0"Specifies whether to log repeated error messages. When set to "1" it will not log errors with repeated errors from the same file on the same line (available since PHP 4.3)PHP_INI_ALLignore_repeated_source"0"Specifies whether to log repeated error messages. When set to "1" it will not log errors with repeated errors from different files or source lines (available since PHP 4.3)PHP_INI_ALLreport_memleaks"1"If set to "1" (the default), this parameter will show a report of memory leaks detected by the Zend memory manager (available since PHP 4.3)PHP_INI_ALLtrack_errors"0"If set to "1", the last error message will always be present in the variable $php_errormsgPHP_INI_ALLhtml_errors"1"Turns off HTML tags in error messagesPHP_INI_ALL
PHP_INI_SYSTEM in PHP <= 4.2.3.xmlrpc_errors"0"Turns off normal error reporting and formats errors as XML-RPC error message (available since PHP 4.1)PHP_INI_SYSTEMxmlrpc_error_number"0"Used as the value of the XML-RPC faultCode element (available since PHP 4.1)PHP_INI_ALLdocref_root""(available since PHP 4.3)PHP_INI_ALLdocref_ext""(available since PHP 4.3.2)PHP_INI_ALLerror_prepend_stringNULLSpecifies a string to output before an error messagePHP_INI_ALLerror_append_stringNULLSpecifies a string to output after an error messagePHP_INI_ALLerror_logNULLSpecifies the name of the file where script errors should be logged. The file should be writable by the web server's user. If the special value syslog is used, the errors are sent to the system logger insteadPHP_INI_ALL

PHP error reporting

  1. TL;DR
  2. The Rules
  3. Bad, bad examples
  4. Just leave them alone!
  5. What if some function refuses to raise an error?
  6. Converting errors to exceptions
  7. Showing a nice page for a user
  8. The universal handling function
  9. Handling fatal errors
  10. The complete error handling example code
  11. Comments (7)

Due to various historical reasons, there are thousands of bad practices in the area of error handling and reporting. As a result, the error reporting is often inflexible, hard to maintain, not user-friendly or even harmful.

All the confusion is coming from the fact that every site has two kinds of customers: a programmer and a user, who require totally different treatment in regard of error messages:

  • a programmer who needs to see every error possible with every minute detail provided
  • a regular site user who must see not a single error message, but rather a generic excuse page instead

The exact moment you'll have these things sorted out, you'll know what to do with error messages in PHP. Below you will find a set of basic principles that will help you to satisfy such contradicting demands, as well as their complete practical implementation

TL;DR

As a rule, do not add error reporting operators to your PHP code (especially ones that output the error message right to the screen). Instead, make PHP generate errors by itself. And then, configure PHP to direct these messages appropriately: on a dev server they have to be shown on-screen; whereas on a live server they should be logged while only a generalized error page without any particular details should be shown to a site visitor.

To do so, configure your PHP as follows:

  • On a development server

    • should be set to value;
    • should be set to 1
    • could be set to 1
  • On a production server
    • should be set to value;
    • should be set to 0
    • should be set to 1

Note that these values are better to be set in or in the the server's configuration:

  • for the Apache's mod_php it should be set in or
  • for PHP CGI it should be set in the local file
  • for php-fpm it should be set in the corresponding file in .

Only as a last resort set them right in the script using command:

but it will fail for some errors (parse errors for example).

And then create an error handler for a live site that is showing an excuse page in case of PHP error.

To put it short: write your scripts without any dedicated error reporting code. Instead, just configure PHP to report errors by itself. Only by the time your code goes live you will need some error handling code but that could be a short code snippet that would handle all errors the uniform and centralized way.

The Rules

To configure error reporting the right way, one should always follow these two cornerstone rules:

  • On a developer's PC the error message should be shown in the full detail, along with other useful information, to ease the development process.
  • On a live site, not a single word from the error message should be shown to a site user. Because:
    • for a casual user it is pretty cryptic and confusing.
    • it it essentially useless for the site programmer/admin as they likely won't be browsing the site at the moment and will have no idea the error has been occurred.
    • the information provided in the error message is extremely useful for a potential hacker, as it provides them with the feedback for their actions and may leak some sensitive information about your site.

Instead, the error message should be logged for the future reference, whereas just a generic error page should be shown to a site visitor.

Bad, bad examples

And such a separation - between a live and a dev server - is the very source of confusion. As a matter of fact, many newbie PHP users are writing their code as though they will always be the only users of their site, bluntly directing error messages right on the screen. Don't you believe me? How many times did you see such a code:

or

?

Many php tutorials, including, sadly, the PHP manual, are using this terrible approach. Given the rules above, you can tell why it's wrong: it is intended for the development only, but absolutely unsuitable for a live site.

Also, error messages must not be suppressed. This includes

  • the use of operator
  • setting to zero (this is a most common one as people often confuse (which actually stands for "error reporting level") with which they're actually looking for)
  • an empty block
  • an if operator that checks the function call's result but does nothing in case of error (or outputs some meaningless stuff like "Error!", "Query failed", etc.). Like:

All these bad practices prevent PHP from telling a programmer what the problem is . And we already learned that error messages are extremely important.

So, how to arrange the error handling to fulfill such contradicting guidelines: showing errors in the full force for a developer yet hide them completely from a site visitor?

Just leave them alone!

The answer is surprisingly simple: just leave error messages alone

Although it sounds quite alien to many PHP users (who cannot imagine a single database interaction without several lines of diligently written error handling code), yet this is the very truth: by leaving the error message alone, one will make its handling flexible and easily configurable, making it possible to switch between modes with just a single PHP configuration option!

Just think of it: there is a directive called . By setting it to 1 we will switch our site into development mode, as PHP will start showing every error occurred automatically, without any effort from our side! And by setting it to 0, we will mute error messages completely, barring a hacker from the critical information and making a user less confused. Still, we need to show a page with excuses, but that's a little different story which we will discuss later.

The same goes for exceptions: an uncaught Exception makes a regular PHP error, so it makes no sense to write a special code only to show it: PHP can show you errors already! So just leave it alone and it will behave exactly as any other error, according to the site-wide rules.

What if some function refuses to raise an error?

There are some PHP modules which, by default, silently fail instead of raising an error. Well, most likely they have a secret configuration option that will make them behave as good boys - raise errors by themselves. If some PHP function doesn't raise an error but apparently fails, then look around for the option to turn error reporting on for its module. For example, PDO could (and should) be configured to throw exceptions, as well as mysqli.

But sometimes there is no way at all to make a function report its error by itself. A good example is the late function or : both will silently return in case of error. In this situation you should look around once more and search the error message provider dedicated to this function. In our case it will be and respectively.

But again, these functions' output should never ever be fed to the notorious operator!

Instead, it should be transferred into a PHP error. The simplest way to do so is to use the function:

in case you have to deal with legacy code that is ultimately using this outdated extension that has been completely removed from the language in 2015, at least the error reporting should be done this way.

Even better would be to throw an exception. The simplest way is just to test the function's result and to add a operator (note that you cannot use it neatly with operator, the condition should be explicit):

But that's just a quick and dirty solution. The best way would be to create a dedicated Exception class for such an error. It's not a big deal, basically it's just a single line:

yet after defining the dedicated class we can create a more talkative version of :

Now it will start spitting the error telling us the reason, just like expected:

This message will be sent either to the screen or the error log, telling us that there was an error with decoding JSON, caused by the wrong JSON syntax.

*Update: Since 7.3.0 it is possible to tell json_decode to throw an exception.

Converting errors to exceptions

Historically, there was only errors in PHP. Then in PHP 5 exceptions were added to the language and since then PHP is moving slowly to replace errors with ErrorExceptions. As this process is not finished yet, we have to deal with two possible kinds of errors - errors and ErrorExceptions. It is not so convenient. Besides, exceptions are more versatile than errors - they could be caught, and they contain a stack trace by default. So consider turning all errors into exceptions, as it will allow the uniform error handling. The code to do so is ridiculously simple:

all we have to do is just to call a set_error_handler() function and tell it to throw an exception.

Add these three lines to your PHP scritps and you'll be able to catch PHP errors! For example, the following code

will tell you not to divide by zero instead of throwing an error. Quite convenient. And again, it will make the error handling uniform.

Showing a nice page for a user

All right, it's OK with a programmer, they are notified of the every error occurred, either from a log file or just by watching the screen. But what about a site user? With proper error reporting set, they will just face a blank page, which is apparently not the way to go. We need to show them some explanations and ask to try later. There are several ways to do that. The simplest way is to configure your web-server to show such a page in case of error. For example, to configure Nginx to show a custom error page in case of 500 error, just create such a custom error page, and then add this line to the server configuration:

Voila! In case of error this page will be shown instead of a blank screen, making your users happy! Do not forget to create the actual page and put it in the site root.

However, it is reported that Apache's mod_php has issues with its directive and a 500 error generated by PHP. To make the solution robust and have more control on the error handling it's better to handle error on the PHP side, but still do it the centralized way.

For this, PHP offers two functions, set_error_handler() and set_exception_handler(). They both register a function that will be callsed in case an error or an uncaught exception appears.

Given we already used the error handler function to convert errors to exception, now we need only an exception handler function.

The universal handling function

But having such a function for just a user's convenience will make the programmer unhappy, as the latter wants to see the actual error message. So let's create a universal function that could satisfy both. In order to do so we need some parameter to tell a dev environment from a production one. There are many possible solutions, in my case I would just use the php.ini configuration parameter. As it must be set to 0 on the production server we could use it to tell that we are in the production environment. But of course you could use your own markers, for example using a is very common solution.

Note that this is a very basic function. Many additions could be made to it, in order to improve the output for both a site user and a programmer. Yet, this is already a robust solution that will make your site comply with the basic error reporting rules.

Handling fatal errors

One last thing to make our error handling completely uniform.

Fatal errors are not caught by the standard error handler. To handle them the same way as other errors, we will need another function, register_shutdown_function which will tell PHP to call a function every time the PHP execution is terminated, both of natural causes or in case of error. So we will need to tell the latter from the former, for which the error_get_last() will be used, also providing the error information:

Unfortunately, this function is called at such a stage when no intelligent handling is possible, for example, an exception thrown inside this function wont be caught using try-catch operator. All we can do is some basic error handling.

The complete error handling example code

Now let's try to gather together everything we learned, and create a basic error handling solution.

First, we need to configure basic error handling directives in the PHP/web-server configuration as discussed here. Then let's create a file called with the following code inside, and include it in your bootstrap file:

Here, we define a common error handling function which encapsulates all the error handling logic. Then, we set up the exception handler that calls our function when an uncaught exception appears.
Also, all PHP errors are converted into exceptions as it was discussed above, and thus end up processed by the same handling code.
Finally, the same handling function is also called for the fatal errors.

That fancy code to get the is due to the fact that the value could be not only 1 or 0 but also "yes", "no", "true", etc. And would handle them all correctly.

Of course, this basic solution could be greatly improved and extended. But the idea here is to provide a concise, easy to grasp educational example, that could be nevertheless used in the production code as well. Do not hesitate to extend this basic approach to satisfy your needs.

If you want some ideas on the advanced error handling, take a look at Laravel's error handling code




” characters in between the possible parameters. The “&” character is for “true for all”, while the “

Improve PHP Error Messages in IIS 7

  • Article
  • 5 minutes to read

by Tali Smith

PHP errors often do not provide sufficient detail to help diagnose errors that occur within the framework. These include basic errors such as 404 Not Found. Because of this, the default "detailed error" experience for PHP applications may be ineffective for troubleshooting basic errors.

Internet Information Services (IIS) improves PHP error handling by intercepting common error conditions and providing redirection for common HTTP status codes.

By default, IIS is configured to return detailed error messages to local clients and to return generic error messages to remote clients. This is done to allow effective troubleshooting locally, while protecting production applications from disclosing sensitive details to remote clients when errors occur.

IIS generates very detailed error messages for most errors. These contain, at minimum, information about the request and the error, including which module generated the error and during which part of the request processing. For errors caused by IIS and its built-in modules, the errors also contain likely resolutions. This dramatically simplifies the troubleshooting process for most errors.

This article, based on the hands-on labs in the PHP on Windows Training Kit, describes how IIS takes care of basic errors handling and how IIS diagnoses application-level errors by enabling PHP error messages.

Basic Error Handling

IIS improves PHP error handling by intercepting common error conditions and providing redirection for common HTTP status codes.

Note that IIS also support error messages generated by application frameworks, which often offer application-specific information to help diagnose application errors. For example, Microsoft® ASP.NET takes advantage of this to provide detailed exception stack traces and other information.

If you request the page from Windows® Internet Explorer®, you get a default "Not Found" error—a non-descriptive 404 error page.

Screenshot of a browser window with a non-descriptive 404 error message displayed.
Figure 1: A non-descriptive 404 error message

The default IIS "Not Found" error message provides useful information to help diagnose the error condition; it correctly identifies the error and suggests solutions for most common error conditions by providing information such as the source (module, notification) of the error and background information such as the URL, mapped physical path, and the authentication method being used. For example:

  • Response information: HTTP 404 Not Found.
  • Detailed error information: The module (IIS Web Core), the Notification (MapRequestHandler), the handler (StaticFileHandler), and the error code (0x80070002 – File Not Found).
  • Request information: The requested URL and the physical path .
  • The "Most likely causes" section correctly suggests the most likely error cause to be: "The directory or file specified does not exist on the Web server".
  • The "Things you can try" section suggests the corresponding solution: "Create the content on the Web server".

Screenshot of a browser window displaying a detailed 404 error message.
Figure 2: Detailed 404 error message

You can also get IIS detailed errors for some PHP errors by configuring IIS to perform some additional validation of PHP requests.

To configure IIS to provide additional validation of PHP requests, use the following steps:

  1. Switch to the IIS Manager. If it is closed, click Start,and then select Internet Information Services (IIS) Manager.

  2. In the tree view on the left, click the server node.

  3. Under IIS, double-click Handler Mappings to edit the PHP handler mapping.

  4. Right-click the PHP via FastCGI entry, and then click Edit.

  5. Click Request Restrictions.

  6. Select the Invoke handler only if request is mapped to check box.

  7. Leave the File option button selected.

  8. Click OK twice.

  9. Click Yes in the Edit Module Mapping dialog box.

  10. To test, trigger a "Not Found" condition again to verify that the PHP 404 error is now handled by IIS, providing more detail. Using Internet Explorer, request (this page does not exist).

  11. You receive an IIS detailed error indicating that the Notfound.php page was not found on the server.

    An IIS 401.3 Unauthorized detailed error also provides information; it indicates that the request does not have the permission to view the page due to access control list (ACL) configuration and provides an extensive explanation of how to resolve this issue.

    Screenshot of a browswer window with an unauthorized detailed error displayed.
    Figure 3: An Access Denied error

Enable PHP Error Messages to Diagnose Application-Level Errors

Configuring IIS to validate requests causes IIS to attempt to open the PHP script file corresponding to the request URL and generates detailed error messages for any conditions that preclude this. This typically includes:

  • File not found
  • Access denied due to incorrect permissions
  • Access denied due to insufficient authentication
  • For most other error conditions, especially those that occur at the application level, IIS detailed error messages do not contain sufficient information to help diagnose the error effectively.

The biggest examples of such errors are script parsing and script interpretation errors. While you can force IIS detailed error messages for these errors, this typically does not provide any value in diagnosing the root cause of the error. In these cases, you must rely on the information provided by PHP to diagnose these errors.

By default, PHP is not configured to display these errors to the response to prevent disclosure of sensitive information.

Notethat for local debugging, you can enable PHP error display to diagnose PHP errors while debugging. Consider disabling PHP error display for production applications.

If you request a page with a script error, you receive the IIS detailed error message. This happens because by default PHP does not generate a response with the error details, so IIS inserts its generic "500 Server Error" detailed error. While this error correctly suggests that PHP has returned a 500 error code, it does not provide application-specific information about what caused the error.

You can configure PHP to display errors in responses.

  1. Using Windows® Explorer, browse to .

  2. Open the Php.ini filein the PHP installation directory.

  3. Find and set the display_errors = On directive:

  4. Save and close the file.

  5. Reset IIS. Click Start,and then select Command Prompt, right click and select Runas administrator to open a command-line window.

  6. Type iisreset.exe

  7. Press Enter.

If you request a page with a script error now, you get a PHP parse error:

If you see only the default Internet Explorer HTTP 500 Internal Server Error page, you must disable friendly error messages. Within Internet Explorer Go to Tools, Internet Options, Advanced tab, and then clear the Show friendly HTTP error messages check box.

Note that PHP also provides options for customizing default error handling or completely overriding it.

Note: This article uses material from the PHP on Windows Training Kit, published on August 25, 2009.

See also

1 Comments

Leave a Comment