Let's connect

Why WordPress 5.5.3 with PHP 8 gives 404 on every page of the site?

WordPress in the latest version 5.5.3 gives a 404 error when trying to enable the newly released PHP 8. Why?

Officially, WordPress will only be compatible with PHP 8 starting with version 5.6, which is scheduled for December 8, 2020. The RC version of the WordPress 5.6 core works correctly with PHP 8, the issue has been fixed. However, it is interesting to understand what is the source of the problem.

First, let’s try to answer the question, what is the value of the expression

'' < 0 //(empty string less than zero)?

The first answer that comes to mind is false. An empty string is reduced to zero, the comparison is 0 < 0, the result is false.

This has always been the case in PHP, and before PHP 8, the result of the expression is false. But not in PHP 8. Here the result of the expression is true, and it is officially announced. Comparison with a numeric string uses a number comparison. But the empty string is not numeric and PHP 8 uses string comparison: ' ' < '0' and the result is true.

What does this have to do with WordPress?

The core has a method that is called on every request: \WP_Query::parse_query. It contains lines

if ( !is_scalar( $qv['p'] ) || $qv['p'] < 0 ) {
    $qv['p']     = 0;
    $qv['error'] = '404';

In most cases, $qv['p'] contains an empty string, which triggers the if and sets a 404 error.

In WordPress 5.6, the comparison string looks like this:

if ( !is_scalar( $qv['p'] ) || (int)$qv['p'] < 0 ) { ...

Which fixes the problem in PHP 8 and works correctly in all PHP versions.
You shouldn’t use implicit casting, especially when developing code that should work under PHP 8.

The original article can be read here

Post a Comment