This website uses cookies

Our website, platform and/or any sub domains use cookies to understand how you use our services, and to improve both your experience and our marketing relevance.

Peak Performance.

Limitless Scalability.

  • 0

    Days

  • 0

    Hours

  • 0

    Mins

  • 0

    Sec

Off For 4 months
+40 free Migrations

Secure Any CMS With Ease with Our Malware Protection Add-On! LEARN MORE→

How to Troubleshoot Website PHP Error Logs With Cloudways

Updated on November 5, 2024

10 Min Read

Websites run into issues all the time, such as slowing down. But sometimes, they stop working due to multiple concurrent errors like HTTP 500.

PHP applications require constant management, and error logging plays a vital role in debugging and maintenance.

In this blog, we will learn 8 different ways to enable PHP error logging. Cloudways offers the most convenient method, but you can use any method you find convenient.

We will also learn why enabling PHP error logs is important, where is php logging errors,  the most common types of PHP errors, and how to fix them as well.

Why Is Enabling PHP Error Logging Important for Debugging and Maintenance?

Error logs inform you what sort of errors are occurring, so you can debug applications correctly. Here are a few reasons why error logging is necessary.

  • Debugging: When you don’t know how an issue came up, what instructions led to the error, and error logs point you to the right place. Debugging helps you identify problems in different ways or extract useful information from data.
  • Performance Monitoring: You can monitor the performance of your application and identify bottlenecks by looking at your error logs.
  • Security: Log entries that occur when attackers attempt to extract information from your code might help you identify vulnerabilities so you can patch them up. While you’re here, you might find our guide on enabling WordPress error logs helpful.

Most Common PHP Error Log Types

There are a lot of different types of PHP errors. Too many to list here to be honest with you. Having the knowledge about different error types can help you understand the root cause to fix it.

Here you can find 10 of the most common PHP errors including PHP notice, syntax and warnings that developers often need to deal with during coding.

1. PHP Parse Error (Syntax Error)

Parse errors usually occur when the PHP interpreter encounters a syntax mistake in the code, such as missing punctuation or unclosed quotes can lead to parse error.

Common Causes:

  • Missing semicolons at the end of statements.
  • Unmatched parentheses or brackets.
  • Misspellings.

Example:

Here’s an example of a parse error message:

PHP Parse error: syntax error, unexpected ‘5’ (L_NAME), expecting ‘)’ in /home/u802426761/domains/username/public_html/wp-config.php on line 32

The error indicates that PHP is unable to find the closing parenthesis on line 32 of the wp-config.php file. To fix this, you’ll need to correct the syntax error on that line.

2. E_WARNING: Invalid Argument Supplied for Foreach()

This warning occurs when a foreach loop is attempted on a variable that is not an array or an object.

Common Causes:

  • Using foreach on a null or non-array variable.

Example:

Warning: Invalid argument supplied for foreach() in /home/master/applications/databasename/public_html/index.php on line 10

The warning indicates that the variable used in the foreach loop in the index.php file on line 10 is not an array or object. To fix this, ensure the variable is correctly defined as an array or object before the foreach loop.

Incorrect code:

$items = null; // $items is not an array, it's null

foreach ($items as $item) {
    echo $item;
}

Correct Code:

$items = []; // Initialize as an empty array

// Check if $items is an array before looping
if (is_array($items)) {
    foreach ($items as $item) {
        echo $item;
    }
}

Solve PHP Errors Easily with Cloudways Hosting!

Tired of dealing with complex PHP errors and server issues?

 

With Cloudways, you have the flexibility to experiment, optimize, and perfect every aspect of your PHP applications. Try Cloudways with a 3-day free trial and deploy your PHP projects effortlessly.

3. E_NOTICE: Undefined Index

This notice is triggered when trying to access an array element that does not exist.

Common Causes:

  • Accessing an array key that has not been set.

Example:

Notice: Undefined index: user_name in /home/u802426761/domains/username/public_html/profile.php on line 15

The error indicates that the key “user_name” is not defined in the array on line 15 of the profile.php file. To fix this, use the isset() function to check if the key is set before accessing it. This ensures the array key exists, preventing the error.

Incorrect Code:

$user = []; // $user is an empty array

echo $user['user_name']; // Trying to access 'user_name' which is not defined

Correct Code:

$user = []; // $user is still an empty array

// Check if 'user_name' is set before accessing it
if (isset($user['user_name'])) {
    echo $user['user_name'];
} else {
    echo 'Username not set';
}

// Alternatively, using null coalescing operator
echo $user['user_name'] ?? 'Username not set';

4. E_NOTICE: Undefined Variable

This notice occurs when a variable is used without being initialized or assigned a value.

Common Causes:

  • Forgetting to initialize a variable before using it.

Example:

Notice: Undefined variable: user_age in /home/master/applications/databasename/public_html/profile.php on line 22

The PHP warning indicates that the variable “user_age” is being used without being initialized or assigned a value in the profile.php file on line 22. To fix this, you need to ensure the variable is assigned a value before it’s used.

Incorrect code:

echo $user_age; // $user_age is not defined anywhere before this line

Correct Code:

$user_age = 25; // Initialize the variable

echo $user_age; // Now $user_age is defined, so no notice will be triggered

5. E_DEPRECATED: Function/Class/Method

Deprecated errors (warning) will show up when calling functions, classes or methods that are marked as deprecated.

Common Causes:

  • Using functions or classes that have been deprecated in new or latest PHP versions.

Example:

Deprecated: Function mysql_connect() is deprecated in /home/master/applications/databasename/public_html/db.php on line 10

In this example the PHP warning is about the deprecated function “mysql_connect()”. It simply means the PHP version we are using is no longer supporting the mysql_connect() function. We will need to use any alternative or refer to the PHP documentation for more information for such deprecated functions.

Incorrect code:

$connection = mysql_connect("localhost", "username", "password");

Correct Code:

$connection = mysqli_connect("localhost", "username", "password");

6. E_STRICT: Non-Static Method

The E_STRICT error occurs when a non-static method is called statically.

Common Causes:

  • Using or calling a non-static method using the name of class instead of an object instance.

Example:

Non-static method MyClass::myMethod() should not be called statically in /home/master/applications/databasename/public_html/script.php on line 15

In this example, PHP is throwing an E_strict error because a non-static method is being called statically. This happens when a method is called using the class name instead of an instance of the class. To fix this, ensure that the method is called with an object instance, or if it should be static, declare it as a static method.

Incorrect code:

class MyClass {
    public function myMethod() {
        return "Hello, World!";
    }
}

// Incorrect: Calling non-static method statically
echo MyClass::myMethod();

Correct Code:

class MyClass {
    public static function myMethod() {
        return "Hello, World!";
    }
}

// Correct: Now the method is static, so it can be called statically
echo MyClass::myMethod();

7. E_RECOVERABLE_ERROR: Catchable Fatal Error

  • Catchable fatal errors usually get caught and handled using an error handler function.

Common Causes:

  • When the type mismatches in function arguments.

Example:

Deprecated: Function mysql_connect() is deprecated in /home/master/applications/databasename/public_html/db.php on line 10

In this example, the PHP warning indicates that the mysql_connect() function is deprecated. This means the PHP version being used no longer supports this function. To resolve this issue, you should use an alternative, such as mysqli_connect() or PDO, and refer to the PHP documentation for guidance on updating deprecated functions.

Incorrect code:

$connection = mysql_connect("localhost", "username", "password");

Correct Code:

$connection = mysqli_connect("localhost", "username", "password");

8. E_USER_ERROR: User-Generated Error

User-generated errors are custom errors developers define using the trigger_error() function. This allows developers to generate their own error messages and handle specific conditions within the code.

Common Causes:

  • Intentionally causing an error based on specified conditions.

Example:

Fatal error: User-generated error in /home/master/applications/databasename/public_html/process.php on line 20

This user-generated warning is typically created by developers within their code to detect failed logic, invalid inputs, or specific conditions. It triggers when these conditions are met, aiding developers in debugging and resolving the issue efficiently.

Incorrect code:

$age = 15;

if ($age < 18) {
    trigger_error("User must be 18 years or older.", E_USER_ERROR);
}

Correct Code:

$age = 15;

if ($age < 18) {
    trigger_error("User must be 18 years or older. Current age: $age", E_USER_ERROR);
}

// The script will stop here if the error is triggered
echo "This line will not execute if the error is triggered.";

9. E_COMPILE_ERROR

This error occurs when the PHP engine detects a compile-time issue, typically caused by incorrect syntax or other structural problems in the code. These errors prevent the script from running until they are fixed.

Common Causes:

  • Missing files or classes that are required during compilation.

Example:

Fatal error: Cannot redeclare MyClass() in /home/u802426761/domains/username/public_html/config.php on line 45

This error indicates that the class MyClass() has been declared more than once in the config.php file at line 45. PHP does not permit redeclaring a class, so to fix this, ensure the class is only declared once or use include_once or require_once to avoid loading the file multiple times.

Incorrect code:

// First declaration of the class
class MyClass {
    // Class contents
}

// Second declaration of the same class, which is not allowed
class MyClass {
    // Class contents
}

Correct Code:

class MyClass {
    // Class contents
}

// If needed again, reference the existing class without redeclaring it
$instance = new MyClass();

10. E_CORE_ERROR

A core error occurs during the startup of the PHP engine, preventing the script from executing.

Common Causes:

  • Issues with the PHP installation or configuration.

Example:

Core error: PHP startup: Unable to load dynamic library ‘/usr/lib/php/extensions/no-debug-non-zts-20170718/missing_extension.so’ – /usr/lib/php/extensions/no-debug-non-zts-20170718/missing_extension.so: cannot open shared object file: No such file or directory in Unknown on line 0

This PHP error occurs due to a misconfiguration in the PHP core file, where the dynamic library missing_extension.so is not found. To resolve this issue, you may need to install the missing library or reinstall PHP to ensure all necessary extensions are properly configured.

How to Enable PHP Error Logging [8 Methods]

Enabling PHP error logging can be done through various methods. Below are eight effective techniques for enabling PHP error logging.

Method 1: Monitor Error Log Using Cloudways Platform [Easiest Method]

Since enabling PHP error logging requires modification in the php.ini file, you can simply activate the error logging from the Cloudways platform itself with simple clicks. You can easily customize error_reporting and logging settings from your Cloudways Platform.

  • Log in to your Cloudways dashboard and click the “Servers” tab.

  • Once it’s enabled, your PHP error logs will be recorded in your applications’ “Logs” folder. You can also check the errors under each application monitoring tab.
  • You can easily filter the php errors and warnings from the logs filter.

Method 2: Enable PHP Error Logging

You can enable PHP error logging by modifying the php.ini file or using your code’s error_reporting() and ini_set() functions. Here’s an example:

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

Method 3: Enable Error Log Using cPanel

If your hosting provider uses cPanel, you can enable PHP error logging through the cPanel interface:

  • Log in to your cPanel dashboard and navigate to the “Software” section.
  • Click on the “Select PHP Version” option.
  • Scroll down to the “PHP INI Editor” section and click “Open in New Window.”
  • Locate the “error_log” directive and set its value to the desired log file path.

Method 4: Enable Error Log Using the .htaccess File

You can also enable PHP error logging by modifying the .htaccess file in your website’s root directory. Add the following lines:

php_flag display_startup_errors on
php_flag display_errors on
php_flag html_errors on
php_value error_reporting 32767

Method 5: Enable Error Log Using php.ini File

If you have access to the php.ini file, you can enable PHP error logging by modifying the following directives:

display_errors = On
error_reporting = E_ALL
log_errors = On
error_log = /path/to/error_log

Method 6: Enable PHP Error Logging to a File Using the error_log() Function

You can use the error_log() function in your PHP code to log custom messages to the error log:

error_log('This is a custom error message');

Method 7: Enable Automatic Collection of PHP Errors with Retrace APM

To enable the automatic collection of PHP errors with Retrace APM, first sign up for a Retrace account and install the Retrace agent on your server, ensuring that APM monitoring is enabled during installation.

Once set up, Retrace will automatically collect errors, warnings, and notices from your PHP application without requiring additional code changes.

You can view the collected errors in your Retrace account’s “Errors” section, which provides detailed information, including error messages, stack traces, and affected files.

Additionally, Retrace integrates with popular issue-tracking tools and collects performance metrics, streamlining your error monitoring and troubleshooting process for improved application health and efficiency.

Method 8: Enable PHP Error Logging Through the Web Server Configuration

Depending on your web server configuration, you may be able to enable PHP error logging through server settings. For example, you can add these directives to the httpd.conf file in Apache:

PHP_value error_log /path/to/error_log

Easy, Auto-Scalable Managed WordPress with Cloudways Autonomous

Fully managed WordPress hosting that auto scales to meet the needs of your growing business.

Conclusion

PHP error logging should be a necessary part of your maintenance procedure for every web application on your server.

While knowing the typical types of PHP errors will help you in your maintenance efforts, being familiar with the ways to enable error logging or how to log errors in php and how to interpret error messages will help you resolve any issues you encounter promptly before they greatly affect your users.

Cloudways offers a straightforward yet powerful approach to tracking PHP error logs on their servers. This allows you to effectively monitor and resolve errors directly from the platform’s dashboard, eliminating the need to rely on third-party monitoring tools or manually search through server files.

Frequently Asked Questions

Q1. What is PHP error logging?

PHP error log helps to identify PHP errors, warnings, and notices created during the execution of recorded PHP scripts. With this, the developer can identify and debug issues in their code because specific details regarding the nature of those errors will be displayed in the logs.

Q2. How do I access PHP error logs on Cloudways?

To view error logs in PHP from Cloudways, log into your Cloudways dashboard, click on the tab called Servers, select your application from the list, and then go to the Application Management of concerned app. Under the monitoring tab, you will get a section called Logs. From there, filter the Error Logs by searching PHP, & it will show all relevant PHP error logs.

Q3. What are the most common PHP errors I should look out for?

The most common PHP errors are parse errors, foreach invalid arguments’ warnings, undefined variables or array indices notices, deprecated usage of functions, and catchable fatal errors. Knowing about them can help you troubleshoot your problems.

Q4. How can I enable error logging in PHP?

You can enable error logging in PHP through php.ini from within your code by using the error_reporting() and ini_set() functions, or you can do it through the Cloudways platform. You may also turn on error logging from .htaccess files or from cPanel settings, depending on your particular hosting environment.

Q5. Is it safe to display PHP errors on a live website?

No, it is not safe to display PHP errors on a live site because doing so can reveal quite a lot of information about your application and server environment. Keep error display off in production and have error logging enabled to send the error to a log file instead. This will let you examine errors without compromising security.

Share your opinion in the comment section. COMMENT NOW

Share This Article

Salwa Mujtaba

Salwa Mujtaba is a Technical Content Writer at Cloudways. With a strong background in Computer Science and prior experience as a team lead in Cloudways Operations, she brings a deep understanding of the Cloudways Platform to her writing. Salwa creates content that simplifies complex concepts, making them accessible and engaging for readers. When she's not writing, you can find her enjoying good music, reading a book, or spending quality time with her family.

×

Webinar: How to Get 100% Scores on Core Web Vitals

Join Joe Williams & Aleksandar Savkovic on 29th of March, 2021.

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Want to Experience the Cloudways Platform in Its Full Glory?

Take a FREE guided tour of Cloudways and see for yourself how easily you can manage your server & apps on the leading cloud-hosting platform.

Start my tour

Peak Performance.

Limitless Scalability.

  • 0

    Days

  • 0

    Hours

  • 0

    Mins

  • 0

    Sec

Off For 4 months
+40 free Migrations

Claim Now