Skip to content

Page profiler endpoint fatals on PHP 8 when the request has no b (background selectors) field #1204

Closed

Description

@kushh23

Description

POST /wp-json/optml/v1/optimizations (the public page profiler endpoint) reads b with get_param( 'b' ) and calls count() on it without checking its type. b is not declared in the route args, so when it is missing (or null, or a string) PHP 8 throws TypeError: count(): Argument #1 ($value) must be of type Countable|array, null given at inc/rest.php:974. WordPress then answers HTTP 500 "There has been a critical error on this website." and a PHP fatal is written to the error log.

This happens after the HMAC and Origin checks, so it needs a valid page token. That token is printed in the page source for every logged-out visitor on a page that is not profiled yet, so any HTTP client (not only the bundled script) can trigger the fatal and the log line. The bundled script always sends b, so normal visits are not affected.

The nested values have the same problem: count( $above_fold_bg_selectors ) (:987) and count( $bg_urls ) (:993) fatal on null. The bundled script sets each entry to null first and only replaces it when it finds URLs (assets/js/modules/main.js:231-237), so a null there is likely rare but possible.

Expected: a missing or malformed b is treated as "no background selectors" (or rejected with the normal code: error response), never a fatal.

Step-by-step reproduction instructions

  1. On a test site running PHP 8.x with Optimole 4.2.17 active (the route is registered even when the plugin is not connected), run:
    wp eval '
    $u  = "repro-profile-id"; $t = time(); $pu = home_url( "/" );
    $r  = new WP_REST_Request( "POST", "/optml/v1/optimizations" );
    $r->set_header( "content-type", "application/json" );
    $r->set_header( "origin", "https://" . wp_parse_url( home_url(), PHP_URL_HOST ) );
    $r->set_body( wp_json_encode( [ "d" => 1, "a" => [ 1 ], "u" => $u, "t" => $t, "pu" => $pu, "h" => wp_hash( $u . $t . $pu, "nonce" ) ] ) );
    var_dump( rest_do_request( $r )->get_data() );
    '
    
  2. Result (from reading the code and the PHP check in step 5; I did not run it on a live site): PHP Fatal error: Uncaught TypeError: count(): Argument #1 ($value) must be of type Countable|array, null given in .../inc/rest.php:974.
  3. Add "b" => new stdClass() to the body and run it again: it should get past :974 with no fatal and return "Optimization data stored successfully" (it stores a small profile transient for repro-profile-id).
  4. Over HTTP as a logged-out client: open a not-yet-profiled page, copy pageProfileId, _t, hmac and pageProfileUrl from the optimoleDataOptimizer script in the page source, and POST them as u, t, h, pu (plus d, a) to /wp-json/optml/v1/optimizations with Content-Type: application/json and Origin: https://<site host>, leaving out b. The response is HTTP 500 with "code":"internal_server_error" and the fatal above is logged.
  5. Pure PHP check of the same lines (PHP 8.4.19), body decoded with json_decode( $body, true ) as WP_REST_Request does:
    b absent           => TypeError: count(): Argument #1 ($value) must be of type Countable|array, null given
    b is {}            => Optimization data stored successfully
    b null             => TypeError: count(): Argument #1 ($value) must be of type Countable|array, null given
    b string           => TypeError: count(): Argument #1 ($value) must be of type Countable|array, string given
    b inner url null   => TypeError: count(): Argument #1 ($value) must be of type Countable|array, null given   (the :993 count)
    

Screenshots, screen recording, code snippet or Help Scout ticket

b is read after the signature and origin checks and counted without a type check:
https://github.com/Codeinwp/optimole-wp/blob/v4.2.17/inc/rest.php#L958-L976

if ( wp_hash( $url . $time . $current_url, 'nonce' ) !== $hmac ) { ... }
$bg_selectors = $request->get_param( 'b' );
...
if ( count( $bg_selectors ) > 100 ) {

Nested counts: https://github.com/Codeinwp/optimole-wp/blob/v4.2.17/inc/rest.php#L983-L994

The route only declares d, a and u, with permission_callback => '__return_true':
https://github.com/Codeinwp/optimole-wp/blob/v4.2.17/inc/rest.php#L142-L160

The token is printed for logged-out visitors on unprofiled pages:
https://github.com/Codeinwp/optimole-wp/blob/v4.2.17/inc/manager.php#L515-L523 and https://github.com/Codeinwp/optimole-wp/blob/v4.2.17/inc/admin.php#L1070-L1083

The bundled script's null placeholder for nested entries:
https://github.com/Codeinwp/optimole-wp/blob/v4.2.17/assets/js/modules/main.js#L226-L237

Core does not catch it: call_user_func( $handler['callback'], $request ) in WP_REST_Server::respond_to_request() (wp-includes/rest-api/class-wp-rest-server.php:1293 in WordPress 7.1.3, :1181 in 6.2). The fatal error handler then answers with status 500 (wp-includes/class-wp-fatal-error-handler.php:212 in 7.1.3). REST is not a protected endpoint, so no recovery mode email is sent (wp-includes/class-wp-recovery-mode.php:176-178).

A likely fix is to declare b in the route args (type => object, default => []) or to guard with is_array() before each count() and foreach, at :974, :987 and :993.

Environment info

  • Optimole 4.2.17 (inc/rest.php is the same on master and development at 63f3f7c)
  • Any WordPress version the plugin supports (5.5 and later; core lines cited from 7.1.3 and 6.2)
  • PHP 8.0 and later. On PHP 7.4 count( null ) only logs a warning and the request goes on.

Is the issue you are reporting a regression

No. The same code has been there since the endpoint was added in 4.0.0.

Found while writing the WordPress compatibility checks for Optimole.

Activity

  1. added
    bugThis label could be used to identify issues that are caused by a defect in the product.
    on Oct 28, 2026
  2. added theissue type on Oct 28, 2026
  3. girishpanchal30 commented on Oct 29, 2026

    @girishpanchal30
    Contributor

    I have fixed it with PR #1214

  4. rodica-andronache commented on Oct 29, 2026

    @rodica-andronache
  5. pirate-bot commented on Oct 29, 2026

    @pirate-bot
    Collaborator

    QA agent — 🟡 Needs human QA · Malformed profiler requests are handled safely; the normal background round trip still needs verification.

    The base build crashed on missing and malformed profiler data. The candidate saved missing and nested-null data correctly, rejected malformed shapes, and produced no PHP errors in the HTTP checks. A normal page visit also saved its image, LCP and dimensions, but the bundled client sent an empty background map on both builds. That leaves the full normal-background round trip incomplete, rather than demonstrating a validation defect in this change.

    Worth a human look

    1. Investigate why a loaded above-fold hero produces an empty background map on both builds, then verify that a normal visit stores its background URLs.
    Checks (3 passed · 1 not tested)
    • ✅ A valid signed anonymous HTTP request with b omitted stores a profile with no background selectors and returns a normal success response, never HTTP 500 or a PHP fatal.
    • ✅ A signed profile containing nested null background URL lists is accepted and stores those entries as empty arrays while preserving valid sibling URLs; optional null LCP URL lists do not fatal.
    • ✅ Malformed object shapes in b, l or m and non-string nested URL items are rejected with HTTP 400 rest_invalid_param without storing a profile or causing a PHP fatal.
    • ⏸️ A normal logged-out visit to an unprofiled image page submits the bundled profiler payload successfully and stores its above-fold images, background URLs and LCP data without a PHP fatal.

    Full report, evidence and session trail

  6. kushh23 commented on Oct 29, 2026

    @kushh23
    ContributorAuthor

    🧪 QA steps and test links

    Optimole's page profiler (it records which images are above the fold on each page) accepts data from visitors' browsers. When a request reaches it without the background-image part, or with that part empty, the site answers with "There has been a critical error on this website." and a PHP fatal error is logged. Normal page visits always send that part, so visitors don't hit it; only a hand-made request does.

    Link Build Bot check
    Reproduce the bug Optimole 4.2.17 (released) ✅ Reproduced: both links on the Dashboard notice give "There has been a critical error on this website.", and QA Logs shows Uncaught TypeError: count(): Argument #1 ($value) must be of type Countable|array, null given
    Verify the fix PR #1214 build 2299a55 ✅ Fixed: "Send without background data" shows HTTP 200 "Optimization data stored successfully", "Send with empty background data" shows HTTP 400 rest_invalid_param, no critical error

    In the links:

    • Steps 1 and 2 are already done (as a small must-use plugin instead of a Code Snippet), and the links open on the Dashboard.
    • Optimole is not connected; the profiler accepts requests either way.
    • Tools → QA Logs shows debug.log.

    Reproduce on Optimole 4.2.17 (PHP 8 or later):

    1. Install Code Snippets and add a snippet titled "Optimole profiler check", with the code below, set to run in the admin area only, and activate it.
    2. Go to Dashboard. A notice reads "Optimole profiler check" with two links.
    3. Click Send without background data.
    4. Back on Dashboard, click Send with empty background data.
    • Bug: each click gives "There has been a critical error on this website.", and the debug log has PHP Fatal error: Uncaught TypeError: count() in Optimole.
    • Fixed: the Dashboard loads. Step 3 shows Result: HTTP 200 with "Optimization data stored successfully"; step 4 shows Result: HTTP 400 with rest_invalid_param.
    Snippet code
    add_action( 'admin_notices', function () {
    	if ( 'dashboard' !== get_current_screen()->id ) {
    		return;
    	}
    	$base = admin_url( 'index.php?optml_qa_check=' );
    	echo '<div class="notice notice-info"><p>Optimole profiler check: <a href="' . esc_url( $base . 'missing' ) . '">Send without background data</a> | <a href="' . esc_url( $base . 'null' ) . '">Send with empty background data</a></p>';
    	$case = isset( $_GET['optml_qa_check'] ) ? sanitize_key( $_GET['optml_qa_check'] ) : '';
    	if ( $case ) {
    		$u    = 'qa-profile-check';
    		$t    = time();
    		$pu   = home_url( '/' );
    		$body = [ 'd' => 1, 'a' => [], 'u' => $u, 't' => $t, 'pu' => $pu, 'h' => wp_hash( $u . $t . $pu, 'nonce' ) ];
    		if ( 'null' === $case ) {
    			$body['b'] = null;
    		}
    		$r = new WP_REST_Request( 'POST', '/optml/v1/optimizations' );
    		$r->set_header( 'content-type', 'application/json' );
    		$r->set_header( 'origin', wp_parse_url( home_url(), PHP_URL_SCHEME ) . '://' . wp_parse_url( home_url(), PHP_URL_HOST ) );
    		$r->set_body( wp_json_encode( $body ) );
    		$res = rest_do_request( $r );
    		echo '<p><strong>Result: HTTP ' . (int) $res->get_status() . '</strong> ' . esc_html( wp_json_encode( $res->get_data() ) ) . '</p>';
    	}
    	echo '</div>';
    } );
    Edge cases
    • Normal front-end visit as a logged-out visitor to a page with a cover or background image, with Optimole connected and lazy loading on: the page loads, and the browser console shows no failed optimizations request (400 or 500).
    • Same visit on a page with an above-the-fold element that has no background image: no error, the profile is still saved.
    • PHP 7.4 on the release: no critical error (only a warning in the log); with the fix, same results as step 3 and 4.

    Fix: #1214 (open)

  7. pirate-bot commented on Nov 2, 2026

    @pirate-bot
    Collaborator

    🎉 This issue has been resolved in version 4.2.18 🎉

    The release is available on GitHub release

    Your semantic-release bot 📦🚀

  8. added
    releasedIndicate that an issue has been resolved and released in a particular version of the product.
    on Nov 2, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

bugThis label could be used to identify issues that are caused by a defect in the product.releasedIndicate that an issue has been resolved and released in a particular version of the product.

Type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions