Make WordPress Core


Ignore:
Timestamp:
05/02/2023 03:43:03 PM (14 months ago)
Author:
SergeyBiryukov
Message:

Code Modernization: Replace usage of strpos() with str_starts_with().

str_starts_with() was introduced in PHP 8.0 to perform a case-sensitive check indicating if the string to search in (haystack) begins with the given substring (needle).

WordPress core includes a polyfill for str_starts_with() on PHP < 8.0 as of WordPress 5.9.

This commit replaces 0 === strpos( ... ) with str_starts_with() in core files, making the code more readable and consistent, as well as improving performance.

While strpos() is slightly faster than the polyfill on PHP < 8.0, str_starts_with() is noticeably faster on PHP 8.0+, as it is optimized to avoid unnecessarily searching along the whole haystack if it does not find the needle.

Follow-up to [52039], [52040], [52326].

Props spacedmonkey, costdev, sabernhardt, mukesh27, desrosj, jorbin, TobiasBg, ayeshrajans, lgadzhev, SergeyBiryukov.
Fixes #58012.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/wp-includes/pluggable.php

    r55685 r55703  
    11881188        // If https is required and request is http, redirect.
    11891189        if ( $secure && ! is_ssl() && false !== strpos( $_SERVER['REQUEST_URI'], 'wp-admin' ) ) {
    1190             if ( 0 === strpos( $_SERVER['REQUEST_URI'], 'http' ) ) {
     1190            if ( str_starts_with( $_SERVER['REQUEST_URI'], 'http' ) ) {
    11911191                wp_redirect( set_url_scheme( $_SERVER['REQUEST_URI'], 'https' ) );
    11921192                exit;
     
    12191219            // If the user wants ssl but the session is not ssl, redirect.
    12201220            if ( ! $secure && get_user_option( 'use_ssl', $user_id ) && false !== strpos( $_SERVER['REQUEST_URI'], 'wp-admin' ) ) {
    1221                 if ( 0 === strpos( $_SERVER['REQUEST_URI'], 'http' ) ) {
     1221                if ( str_starts_with( $_SERVER['REQUEST_URI'], 'http' ) ) {
    12221222                    wp_redirect( set_url_scheme( $_SERVER['REQUEST_URI'], 'https' ) );
    12231223                    exit;
     
    12821282        do_action( 'check_admin_referer', $action, $result );
    12831283
    1284         if ( ! $result && ! ( -1 === $action && strpos( $referer, $adminurl ) === 0 ) ) {
     1284        if ( ! $result && ! ( -1 === $action && str_starts_with( $referer, $adminurl ) ) ) {
    12851285            wp_nonce_ays( $action );
    12861286            die();
Note: See TracChangeset for help on using the changeset viewer.