Preloader

PHP Error Handling

PHP Tutorials
codevigyaan php

PHP Error Handling This capabilities allows you to find problems in your application, correct and control them. Ignoring errors may result to your website crusher. Displaying raw errors may reveal internal data.

Therefore, you need to accept robust errors and proceed securely.

Types of Errors in PHP

PHP identifies errors of various levels of severity for different problems. Some errors are mild and do not prevent the script from running. Serious errors in halt the script.

Knowing these errors, helps you to debug faster

1. Parse Error (Syntax Error)

A parse error occurs when PHP encounters a syntax error in your program. This usually indicates a missed requirement. Typical reasons are:.

  • Missing semicolon
  • Missing bracket
  • Wrong keyword spelling

Example:

if ($age > 18 {
echo "Adult";
}

In this example, a closing bracket is missing. So, PHP cannot even start the script.

Important point: Parse errors stop the script completely.

2. Fatal Error

A fatal error occurs when PHP attempts to access a non-existent entity.

Common causes:

  • Calling an undefined function
  • Creating an object from a missing class
  • Memory limit exceeded

Example:

undefinedFunction();

The function is not defined, then PHP will return a fatal error and will terminate the script.

Key point: The script stops immediately when a fatal error occurs.

3. Warning

A warning indicates a serious problem. The script does continue to run.

Common causes:

  • Adding a missing file
  • Using incorrect function arguments
  • Unable to connect to database.

Example:

include("missing_file.php");
echo "Hello";

PHP gives a warning because the file does not exist. And it successfully prints “Hello” after the warning.

Important difference: Warnings do not stop execution.

4. Notice

A warning indicates a small problem. Most of the time it occurs when you try to use a variable that hasn‘t been defined yet.

Example:

echo $username;

If $username is not set PHP will show a notice, but the script will run anyways.

Notices allow you to write cleaner code. They highlight small errors.

5. Deprecated Error

A deprecated error is when you use an outdated function that PHP may take out or remove of its language in the future.

Example:

mysql_connect("localhost", "root", "");

This function is deprecated. PHP is warning you that you should use a more up to date approach such as MYSQLi or PDO.

This type of error does not stop execution. However, you should fix it to keep your code modern.

Exception Handling in PHP

Exception handling/ error handling allows you to deal with nasty issues in a very clean manner. You can take control of an error instead of bombing out your script.

PHP uses three main keywords:

  • try
  • catch
  • throw

How It Works

First, to do this, you put risky code inside the try block.
If something goes wrong, you use throw to create an exception.
And then, the catch block handles this problem.

Example

try {
$age = 15; if ($age < 18) {
throw new Exception("You must be 18 or older.");
} echo "Access granted.";
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}

In this example, the code tests for the age. It‘s less than 18, it throws an exception, and then handles it.

Because of this structure, your script does not crash suddenly.

Why Use Exception Handling

Exception handling/ error handling helps you:

  • Keep your code clean
  • Fix critical bugs
  • Separate error logic from main logic
  • Prevent applications from crashing

Consequently, your application will be more reliable.

Custom Error Handler in PHP

Standard error messages are what PHP displays by default. They can be changed by writing your own error handler.

Here you can are given more control on the appearance of errors.

You can use the set_error_handler() function.

Example

function myErrorHandler($errno, $errstr) {
echo "Custom Error: [$errno] $errstr";
}set_error_handler("myErrorHandler");echo $undefinedVariable;

This is where, instead of calling PHP‘s default error message, you call your own custom error message.

This may be beneficial when you require consistent formatting for errors.

Logging Errors in PHP

Showing errors on a live website is not safe. Attackers can use error message to discover system information.

So, in that case, you should save errors.

Enable Error Logging

ini_set("log_errors", 1);
ini_set("error_log", "error.log");

As of now PHP is writing error into a file named error.log file.

Alternatively, you can use the error_log() function directly.

error_log("Database connection failed.");

This writes the message to your log file.

Why Logging Is Important

Logging helps you:

  • Track issues
  • Debug issues later
  • Protect confidential data.
  • Keep production sites safe

In development, errors will be displayed to you.
In production, you should log them.

Final Summary

PHP offers various features for dealing with errors.

  • Parse and fatal errors stop execution.
  • Warnings and notices do allow the script to continue.
  • Exceptions allow you to control error handling.
  • Custom handlers allow for flexibility.
  • Logging helps you to keep your application more secure.

When you use these tools correctly, your PHP applications become stable, secure, and professional.

Check out our resources!

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *