PHP 500 Internal Server Error: How to Find the Cause in the Apache, Nginx or PHP Log
Quick answer: A 500 error only says that something failed on the server; the real cause is in the log. Check the Apache error log (/var/log/apache2/ or /var/log/httpd/), the Nginx log (/var/log/nginx/) or the PHP-FPM log, and confirm which file PHP writes to with phpinfo() or ini_get('error_log'). The most common causes are syntax errors, a missing included file, a database failure, wrong permissions, an invalid .htaccess and the memory limit.
The PHP 500 error is one of the most stressful problems for anyone who runs websites, systems or APIs. It often shows up as a blank page, a generic internal error message or an empty response, and it never tells you the real cause on its own.
The error means something went wrong on the server, but it can come from many places: a PHP syntax error, a database connection failure, wrong file permissions, a problem in .htaccess, the memory limit, a missing extension, a fatal error or an uncaught exception.
In this article you will learn how to find the cause of a PHP 500 error using the Apache, Nginx and PHP logs, plus techniques like error_log, try/catch, temporarily showing errors and good practices for production.
What does a 500 error mean in PHP?
A 500 Internal Server Error means the server hit an internal failure while processing the request. In PHP applications, it can happen before any HTML or JSON is sent to the browser.
Unlike 404 Not Found, which means the page doesn't exist, a 500 error points to a failure in the application or in the server configuration.
Common causes:
- A PHP syntax error;
- A PHP file with the wrong permissions;
- An error in
.htaccess; - A failed MySQL connection;
- An uncaught exception;
- The memory limit being exceeded;
- The maximum execution time being reached;
- A missing PHP function or extension;
- A wrong file path in
requireorinclude; - An error while sending headers or the JSON response.
Why doesn't the 500 error show any details?
On a server correctly set up for production, PHP error details are hidden from visitors. That matters for security: internal messages can reveal file paths, table names, connection details or pieces of code.
So when something fails, the browser may show only:
500 Internal Server Error
The real message is almost always in a log file.
Step one: check the error log
The log is where the server records failures, warnings and internal problems. To fix a 500 error, you need the exact message written there.
Depending on your setup, the error may be in:
- The Apache log;
- The Nginx log;
- The PHP-FPM log;
- The log file set in
php.ini; - Your application's own log;
- Your hosting control panel, such as cPanel, Plesk or DirectAdmin.
Where are the Apache logs?
On Debian and Ubuntu servers, the Apache error log is usually at:
/var/log/apache2/error.log
On Red Hat, CentOS, Rocky, AlmaLinux and Amazon Linux it is usually:
/var/log/httpd/error_log
To follow the log in real time from the terminal:
tail -f /var/log/apache2/error.log
With the command running, reload the page that returns the 500 error. The log should show the real message.
Where are the Nginx logs?
On servers running Nginx, the error log is usually at:
/var/log/nginx/error.log
To follow it in real time:
tail -f /var/log/nginx/error.log
If you use Nginx with PHP-FPM, also check the PHP-FPM log.
Where are the PHP-FPM logs?
The path depends on the PHP version and the distribution. Common examples:
/var/log/php8.2-fpm.log
/var/log/php8.3-fpm.log
/var/log/php8.4-fpm.log
On Red Hat based systems there is usually a folder instead:
/var/log/php-fpm/error.log
/var/log/php-fpm/www-error.log
If the 500 error happens on Nginx + PHP-FPM, this log is essential.
How to find the log file PHP is using
You can check PHP's configuration with a temporary phpinfo file:
<?php
phpinfo();
Save it as info.php, open it in the browser and look for:
error_logdisplay_errorslog_errorsLoaded Configuration File
info.php as soon as you are done. It exposes sensitive information about your server. From the command line, php -i | grep error_log gives the same answer without a public file (but it shows the CLI settings, which may differ from the web server's).
Turning on error logging in PHP
In php.ini, the most important settings are:
log_errors = On
error_log = /var/log/php_errors.log
display_errors = Off
display_startup_errors = Off
error_reporting = E_ALL
In production, keep display_errors Off and send the details to the log. The log file must be writable by the web server user.
After changing php.ini, restart Apache or PHP-FPM. With Apache:
sudo systemctl restart apache2
With PHP-FPM:
sudo systemctl restart php8.3-fpm
How to show errors temporarily during development
In a development environment, you can display errors on screen to speed up debugging:
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
Put this at the top of the file only for local tests or a controlled environment. Note that it can't show parse errors in the same file, because PHP fails before running it; for those, use the log or php -l file.php.
display_errors on in production. Error messages can reveal internal details of your system.
Using error_log to record details
The error_log function writes messages to the server log. It helps you see how far the code gets and which values are coming in.
<?php
error_log('Starting API request');
$id = $_GET['id'] ?? null;
error_log('Received ID: ' . $id);
You can also log errors caught in try/catch blocks:
<?php
try {
// Code that may fail
} catch (Throwable $e) {
error_log('Caught error: ' . $e->getMessage());
}
500 error caused by a syntax error
A syntax error can stop PHP from running the file at all. Common examples:
- A missing semicolon;
- Braces closed in the wrong place;
- Mismatched quotes;
- Using a feature your PHP version doesn't support;
- Pasted code with invisible characters.
Example with an error:
<?php
echo "Hello world"
The correct version:
<?php
echo "Hello world";
The log usually shows Parse error or syntax error. You can check a file before uploading it with php -l file.php.
500 error caused by require or include
If your application tries to load a file that doesn't exist with require, PHP throws a fatal error.
<?php
require __DIR__ . '/config/database.php';
If the path is wrong, the log shows something like:
Failed opening required 'config/database.php'
Check that:
- The file exists;
- The name is correct;
- Upper and lower case match (Linux is case-sensitive, Windows is not);
- The relative path is right (prefer
__DIR__); - The file is readable.
500 error caused by the database connection
A failed MySQL connection is another common cause of 500 errors.
<?php
try {
$pdo = new PDO(
'mysql:host=localhost;dbname=your_db;charset=utf8mb4',
'user',
'password',
[
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
]
);
} catch (PDOException $e) {
error_log('Database connection error: ' . $e->getMessage());
http_response_code(500);
echo json_encode([
'success' => false,
'message' => 'Internal server error.'
]);
exit;
}
In production, log the real message but return a generic one to the user.
500 error caused by file permissions
Files and folders with the wrong permissions can cause 500 errors, especially for uploads, cache, logs or anything the application writes to disk.
- PHP can't write to the upload folder;
- A PHP file isn't readable;
- A folder has the wrong owner;
- Permissions are so open that the host blocks them (some shared hosts refuse to run files set to 777);
- An
.htaccessfile has an invalid rule.
Common permissions on Linux:
Files: 644
Folders: 755
Folders that need to be written to may need a specific owner or group, depending on the web server user (www-data, apache or nginx).
500 error caused by .htaccess
On Apache, an .htaccess file with an invalid rule causes a 500 error on every page in that folder.
A common rule:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php [QSA,L]
Common .htaccess problems:
mod_rewriteis disabled;- A directive your host doesn't allow;
- A syntax error in a rule;
- A redirect loop;
- A setting that doesn't match the server.
To test, rename .htaccess temporarily and see if the error goes away. To rebuild it with known-good rules, use the .htaccess generator.
500 error in a PHP API returning HTML instead of JSON
An API frontend expects JSON. If PHP fails before building the response, the server may return HTML or an empty body.
To avoid that, use one function for every JSON response:
<?php
function jsonResponse(int $statusCode, array $data): void
{
http_response_code($statusCode);
header('Content-Type: application/json; charset=utf-8');
echo json_encode($data, JSON_UNESCAPED_UNICODE);
exit;
}
Then use it in your error handling:
<?php
jsonResponse(500, [
'success' => false,
'message' => 'Internal server error.'
]);
Handling exceptions with try/catch
try/catch lets you catch failures and keep the application from crashing without control.
<?php
try {
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = :id");
$stmt->execute([
':id' => $id
]);
$user = $stmt->fetch();
jsonResponse(200, [
'success' => true,
'data' => $user
]);
} catch (PDOException $e) {
error_log('PDO error: ' . $e->getMessage());
jsonResponse(500, [
'success' => false,
'message' => 'Internal error while reading the data.'
]);
} catch (Throwable $e) {
error_log('Unexpected error: ' . $e->getMessage());
jsonResponse(500, [
'success' => false,
'message' => 'Internal server error.'
]);
}
Catching uncaught exceptions
You can set a global handler for exceptions nobody caught:
<?php
set_exception_handler(function (Throwable $e) {
error_log('Uncaught exception: ' . $e->getMessage() . ' in ' . $e->getFile() . ':' . $e->getLine());
http_response_code(500);
header('Content-Type: application/json; charset=utf-8');
echo json_encode([
'success' => false,
'message' => 'Internal server error.'
], JSON_UNESCAPED_UNICODE);
exit;
});
This handler keeps exceptions from escaping without a controlled response.
Turning PHP errors into exceptions with set_error_handler
Warnings and notices are not exceptions, so try/catch doesn't see them. A common pattern is to convert them into ErrorException, so they reach your catch blocks and the global handler above:
<?php
set_error_handler(function (int $severity, string $message, string $file, int $line): bool {
if (!(error_reporting() & $severity)) {
return false; // this error level is not being reported
}
throw new ErrorException($message, 0, $severity, $file, $line);
});
Even with handlers in place, the server log is still your main source of truth: fatal errors such as memory exhaustion are not passed to set_error_handler.
500 error from the memory limit
When PHP goes over its memory limit, it stops with a fatal error. The log shows something like:
Allowed memory size of 134217728 bytes exhausted
It usually happens with:
- Queries that return too many rows;
- Large uploads;
- Image processing;
- Runaway loops;
- Large reports;
- Excel or PDF exports.
Rather than just raising memory_limit, fix the cause: paginate, filter, process in chunks and write more efficient queries.
500 error from the maximum execution time
If a request takes too long, PHP stops it. The log shows:
Maximum execution time of 30 seconds exceeded
Common causes:
- A slow SQL query;
- A heavy loop;
- An external API that takes too long to answer;
- Processing many files at once;
- A very large report.
Review the logic, paginate, add database indexes and move heavy work out of a single request (to a queue or a cron job).
500 error after upgrading PHP
After a PHP upgrade, old code can stop working. Check for:
- Removed or deprecated functions;
- Extensions that are not enabled in the new version;
- An incompatible Composer version or packages;
- Configuration differences between versions;
- Stricter type checks.
The log usually names the function, class or extension that is failing.
Creating your own application log
Besides the server log, you can keep a file of important application events:
<?php
function appLog(string $message): void
{
$file = __DIR__ . '/logs/app.log';
if (!is_dir(dirname($file))) {
mkdir(dirname($file), 0755, true);
}
$line = '[' . date('Y-m-d H:i:s') . '] ' . $message . PHP_EOL;
file_put_contents($file, $line, FILE_APPEND | LOCK_EX);
}
appLog('Starting users endpoint');
Keep this folder outside the public web root, or block it from being served, so nobody can download your logs.
Complete PHP API example with 500 error handling
<?php
header('Content-Type: application/json; charset=utf-8');
ini_set('display_errors', 0);
ini_set('log_errors', 1);
error_reporting(E_ALL);
function jsonResponse(int $statusCode, array $data): void
{
http_response_code($statusCode);
echo json_encode($data, JSON_UNESCAPED_UNICODE);
exit;
}
set_exception_handler(function (Throwable $e) {
error_log('Uncaught exception: ' . $e->getMessage());
jsonResponse(500, [
'success' => false,
'message' => 'Internal server error.'
]);
});
try {
$pdo = new PDO(
'mysql:host=localhost;dbname=your_db;charset=utf8mb4',
'user',
'password',
[
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
]
);
$id = isset($_GET['id']) ? (int) $_GET['id'] : 0;
if ($id <= 0) {
jsonResponse(422, [
'success' => false,
'message' => 'Invalid ID.'
]);
}
$stmt = $pdo->prepare("SELECT id, name, email FROM users WHERE id = :id");
$stmt->bindValue(':id', $id, PDO::PARAM_INT);
$stmt->execute();
$user = $stmt->fetch();
if (!$user) {
jsonResponse(404, [
'success' => false,
'message' => 'User not found.'
]);
}
jsonResponse(200, [
'success' => true,
'data' => $user
]);
} catch (PDOException $e) {
error_log('PDO error: ' . $e->getMessage());
jsonResponse(500, [
'success' => false,
'message' => 'Internal database error.'
]);
} catch (Throwable $e) {
error_log('General error: ' . $e->getMessage());
jsonResponse(500, [
'success' => false,
'message' => 'Internal server error.'
]);
}
The query uses a prepared statement, which also protects it from SQL injection. See how to prevent SQL injection in PHP with PDO.
Checklist to fix a PHP 500 error
- Check the Apache, Nginx or PHP-FPM log;
- Make sure the PHP file has no syntax errors (
php -l); - Check the
requireandincludepaths; - Check file and folder permissions;
- Review the
.htaccessrules; - Check the database connection;
- See whether a PHP extension is missing;
- Check the memory and execution time limits;
- Log errors with
error_log; - Use
try/catcharound critical operations; - Never show internal messages in production;
- Return consistent JSON responses in APIs.
Common mistakes when fixing a 500 error
1. Trying to fix it without reading the log
The log shows the real cause. Without it, you are only testing guesses.
2. Turning on display_errors in production
Showing errors to visitors can reveal sensitive information.
3. Ignoring .htaccess
A single invalid rule can take down the whole site on Apache.
4. Not handling database errors
Connection failures and bad queries should be caught with try/catch.
5. Treating production and development the same way
In development you can show details. In production, log them and return a generic message.
Conclusion
A PHP 500 error means an internal failure on the server, but the real cause is almost always written in a log. Check the Apache, Nginx, PHP-FPM or PHP log before changing code blindly.
Once you have the real message, the fix is usually quick, whether it is a syntax error, the database connection, file permissions, a configuration problem, the memory limit or an uncaught exception.
In PHP APIs, also return consistent JSON responses, log details with error_log and never expose internal messages to users. Your application becomes safer and much easier to maintain. To build an API on these foundations, see how to create a REST API in plain PHP.
Frequently asked questions about the PHP 500 error
What is a 500 error in PHP?
It is an internal server error: PHP or the server configuration failed while processing the request.
How do I find the cause of a 500 error?
Check the Apache, Nginx, PHP-FPM or PHP log. The log usually shows the real error message.
Can .htaccess cause a 500 error?
Yes. On Apache servers, an invalid rule in .htaccess causes a 500 error.
Can I turn on display_errors to fix it?
In development, yes. In production, keep errors hidden and write the details to the log.
Can a database error cause a 500 error?
Yes. A failed MySQL connection, an invalid query or an uncaught exception can all cause it.
How do I avoid a blank page in PHP?
Turn on logging, handle exceptions with try/catch, set global handlers and return consistent error responses.