← Back to Pull requests

fix: make `getVar()` read merged superglobals instead of stale `$_REQUEST` #10587

Closed
rahul05ranjan closed this pull request without merging on Oct 09, 2026 12:49 UTC
View on GitHub
rahul05ranjan rahul05ranjan commented on Sep 25, 2026 11:32 UTC
Author

Description

Fixes #9872. SiteURIFactory updates GET data after PHP initializes $_REQUEST, so getVar() can return stale values to Validation::withRequest().

This changes getVar() to read a fresh merged view of GET, POST, and COOKIE data, respecting request_order / variables_order, without mutating $_REQUEST. Explicit setGlobal('request', ...) overrides and JSON requests retain their existing lookup behavior.

The merge preserves numeric keys, merges nested arrays recursively, normalizes lowercase order letters, and processes each source only once. It reuses the existing fetchGlobal() filtering path and clears temporary merged data in finally, avoiding a new protected helper that could conflict with application subclasses. The user guide and changelog describe the updated data source.

Checklist:

  • Securely signed commits

  • Component(s) with PHPDoc blocks, only if necessary or adds value (without duplication)

  • Unit testing, with >80% coverage

  • User guide updated

  • Conforms to style guide
  • Testing:

  • PHP 8.2.34: IncomingRequestTest.php 116 tests, SuperglobalsTest.php 55 tests, RequestTest.php 40 tests, and the three affected Validation cases pass (214 tests total).

  • Regression tests reproduced the explicit-override failure, lowercase-order failure, and subclass signature collision before the fixes. Additional tests cover repeated reads and cleanup after a filter throws.

  • File-scoped PHPStan and PHP CS Fixer checks pass. Coverage was not measured locally, so the coverage checklist item remains unchecked.

  • Full validation remains with GitHub Actions. File-scoped Rector proposes removing existing parent calls outside this change; the constructor proposal also occurs on the previous PR head.
  • Diff: 297 lines (+283 / -14) across 7 files Reviewer: neznaika0 Review duration: 20236m
    All Vouch review confidence checks passed
    Residual risk 0.07 = Change Risk (0.46) × (1 − Review Confidence (0.85)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.46 · 297 lines diff across 7 files
    0.46
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.75 · 5 substantive comment(s)
    0.75
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    85%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.341
    Real PR Conversation Timeline
    41 items
    carson-codeigniter4[bot] carson-codeigniter4[bot] commented on Sep 25, 2026 11:32 UTC
    Bot

    Hi there, @rahul05ranjan! :wave:

    Thank you for sending this PR!

    We expect the following in all Pull Requests (PRs).

  • PRs must be sent to the appropriate branch

  • All git commits must be GPG-signed

  • Must follow our style guide

  • Be commented in the PHP source file

  • Be documented in the user guide

  • Be unit tested

  • Pass all checks in GitHub Actions
  • [!IMPORTANT]

    We expect all code changes or bug-fixes to be accompanied by one or more tests added to our test suite to prove the code works.

    If pull requests do not comply with the above, they will likely be closed. Since we are a team of volunteers, we don't have any more time to work
    on the framework than you do. Please make it as painless for your contributions to be included as possible.

    See https://github.com/codeigniter4/CodeIgniter4/blob/develop/contributing/pull_request.md

    <!-- carson:welcome -->

    neznaika0 neznaika0 commented on Sep 25, 2026 15:22 UTC
    Contributor

    Hi. See #10205
    We deliberately did not add synchronization. You could add a comment about this.

    rahul05ranjan rahul05ranjan commented on Sep 26, 2026 10:22 UTC
    Author

    Thanks for the pointer, @neznaika0 — I see now that #10205 took this same syncRequest() approach and was closed as "not the desired approach." I'll rework this PR accordingly.

    Based on the discussion in #9872, the preferred direction is to avoid mutating $_REQUEST entirely and instead have getVar() return a merged view of $_GET, $_POST, and $_COOKIE (respecting request_order), or change withRequest() to stop relying on getVar(). That also moves us toward eventually deprecating getVar().

    I'll drop the Superglobals::syncRequest() method and the SiteURIFactory changes, and rework the fix around getVar()/withRequest() instead. I'll update the PR shortly.

    rahul05ranjan rahul05ranjan commented on Sep 26, 2026 12:44 UTC
    Author

    Reworked as discussed. The syncRequest() approach is gone.

    getVar() now returns a merged view of $_GET, $_POST, and $_COOKIE (respecting request_order/variables_order) instead of reading the stale $_REQUEST, so $_REQUEST is never mutated. This also moves us toward eventually deprecating getVar().

    Changes:

  • Superglobals::getRequestData() returns the merged data (no mutation).

  • RequestTrait::fetchFromArray() extracts the shared filtering/index logic.

  • getVar() uses getRequestData() + fetchFromArray().

  • Reverted the SiteURIFactory syncRequest() calls.

  • Updated tests accordingly.
  • @neznaika0 @paulbalandan — does this match the direction you had in mind from #9872?

    rahul05ranjan rahul05ranjan commented on Sep 26, 2026 14:23 UTC
    Author

    Update: the rework is complete and all commits are now GPG-signed.

    Summary of the final state:

  • getVar() reads a merged view of $_GET/$_POST/$_COOKIE (respecting request_order) instead of the stale $_REQUEST, so $_REQUEST is never mutated.

  • Superglobals::getRequestData() returns the merged data; RequestTrait::fetchFromArray() extracts the shared filtering logic.

  • Reverted the SiteURIFactory syncRequest() calls.

  • Fixed the static-analysis issues (protected method, no short ternary) and updated the tests.
  • The Carson checks (signed-commits, no-merge-commits, pr-title-linter) are all passing. The remaining GitHub Actions workflows are showing action_required and need a maintainer to approve them to run.

    @neznaika0 @paulbalandan — whenever you have a moment, could you take a look? Thanks!

    neznaika0 neznaika0 commented on Sep 26, 2026 17:31 UTC
    Reviewer

    I’m not very good at evaluating PR — I don’t know the exact direction in this matter. For myself, I’ve decided not to use $_REQUEST and getVar(). Do you know any specific cases where this is 100 % necessary? In most cases, it’s better to use an explicit data source (GET, POST, COOKIE).

    Earlier, it was said that this is a system class (for tests), and for the user, you need to use Request.

    Wait for the member answers.

    Copilot Copilot commented on code on Sep 27, 2026 07:54 UTC
    Code Review
    system/HTTP/IncomingRequest.php:1
    @@ -387,7 +388,12 @@ public function getVar($index = null, $filter = null, $flags = null)
                 return $this->getJsonVar($index, false, $filter, $flags);
             }
     
    -        return $this->fetchGlobal('request', $index, $filter, $flags);
    +        // $_REQUEST is populated only once at the start of the request, so it
    +        // can become stale when $_GET is modified later (e.g. by SiteURIFactory).
    +        // Merge the current superglobals instead of reading the stale $_REQUEST.
    +        $data = service('superglobals')->getRequestData();
    +
    +        return $this->fetchFromArray($data, $index, $filter, $flags);

    By switching getVar() to the merged GET/POST/COOKIE arrays, this drops values deliberately supplied through the existing request channel ($request->setGlobal('request', ...) or Superglobals::setRequestArray()); those values are no longer consulted. The three Validation tests had to be changed from setRequestArray() to setPostArray(), which masks this regression. Please synchronize the request array at the SiteURIFactory update point and retain the existing request lookup, or otherwise preserve explicit request overrides.

    Copilot Copilot commented on code on Sep 27, 2026 07:54 UTC
    Code Review
    system/Superglobals.php:1
    @@ -387,6 +387,42 @@ public function setRequestArray(array $array): self
             return $this;
         }
     
    +    /**
    +     * Returns the merged $_GET, $_POST, and $_COOKIE data according to the
    +     * `request_order` (or `variables_order`) ini setting, without mutating
    +     * $_REQUEST.
    +     *
    +     * PHP populates $_REQUEST only once at the start of the request. When
    +     * $_GET is modified later (e.g. by SiteURIFactory), $_REQUEST becomes
    +     * stale. This method returns the current merged values so callers can
    +     * read up-to-date request data without relying on the stale $_REQUEST.
    +     *
    +     * @return array<string, request_items>
    +     */
    +    public function getRequestData(): array
    +    {
    +        $requestOrder = ini_get('request_order');
    +        if ($requestOrder === false || $requestOrder === '') {
    +            $requestOrder = ini_get('variables_order');
    +        }
    +        if ($requestOrder === false || $requestOrder === '') {
    +            $requestOrder = 'GP';
    +        }
    +
    +        $request = [];
    +
    +        foreach (str_split($requestOrder) as $type) {
    +            match ($type) {
    +                'G'     => $request = array_merge($request, $this->get),
    +                'P'     => $request = array_merge($request, $this->post),
    +                'C'     => $request = array_merge($request, $this->cookie),

    This new merge path has separate cookie handling and order-sensitive overwrite behavior, but the added tests only use non-overlapping GET/POST keys and never populate cookies or exercise request_order/variables_order. A regression in the C branch or precedence would pass unnoticed; add focused assertions for cookies and overlapping keys under the configured order.

    This issue also appears on line 416 of the same file.

    copilot-pull-request-reviewer[bot] copilot-pull-request-reviewer[bot] commented on Sep 27, 2026 07:54 UTC
    Reviewer

    <!-- ccr-overview-v2 -->

    Copilot review overview

    🟡 Changes recommended

    Critical and moderate findings remain around request overrides and synchronizing $_REQUEST.

    Review effort: Lite
    Findings: 2 <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.png" alt="High severity" width="62" height="18" align="texttop"></picture>

    <details open>
    <summary><strong>Open (2)</strong></summary>

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.png" alt="High severity" width="62" height="18" align="texttop"></picture> [Preserve explicit request overrides when merging superglobals](#discussion_r4114562292) · New

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.png" alt="High severity" width="62" height="18" align="texttop"></picture> [Add cookie and precedence coverage for merged request variables](#discussion_r4114562307) · New

  • </details>

    <details>
    <summary><strong>What changed in this PR</strong></summary>

    Updates request-variable retrieval so getVar() reflects current GET/POST/COOKIE data after URI parsing.

    Changes:

  • Adds merged request-data retrieval.

  • Refactors reusable array-fetching logic.

  • Updates request and validation tests.
  • | File | Summary |
    |---|---|
    | tests/​system/​Validation/​ValidationTest.php | Adjusts validation fixtures to use POST data. |
    | tests/​system/​SuperglobalsTest.php | Tests merged request-data behavior. |
    | tests/​system/​HTTP/​IncomingRequestTest.php | Updates request-variable fixtures. |
    | system/​Superglobals.php | Builds merged request data. |
    | system/​HTTP/​RequestTrait.php | Extracts reusable array-fetching logic. |
    | system/​HTTP/​IncomingRequest.php | Uses merged data in getVar(). |
    </details>

    ---

    💡 <a href="/codeigniter4/CodeIgniter4/new/develop?filename=.github/skills/code-review/SKILL.md" class="Link--inTextBlock" target="_blank" rel="noopener noreferrer">Add a code-review agent skill</a> or configure MCP servers for context-aware, tailored reviews. <a href="https://docs.github.com/copilot/how-tos/use-copilot-agents/request-a-code-review/use-code-review?tool=webui#mcp-servers-and-agent-skills" class="Link--inTextBlock" target="_blank" rel="noopener noreferrer">Learn more in the docs.</a>

    rahul05ranjan rahul05ranjan commented on Sep 27, 2026 09:15 UTC
    Author

    @neznaika0 thanks for the review — and your instinct here is exactly right.

    To be clear, this PR doesn't add any new reliance on $_REQUEST or getVar(). It fixes a real bug in existing code: Validation::withRequest() still calls $request->getVar(), and getVar() was reading the stale $_REQUEST. So the choice isn't "should we use getVar()" — it's "getVar() is still here and still used by withRequest(), so it must return correct data."

    The direction matches what @paulbalandan suggested in #9872: instead of mutating $_REQUEST (which #10205 did and was rightly rejected), getVar() now returns a merged view of $_GET/$_POST/$_COOKIE respecting request_order. $_REQUEST is never touched. This also moves us toward eventually deprecating getVar(), since it no longer depends on $_REQUEST at all.

    On "100% necessary" cases: I agree — there's no case where getVar() is strictly necessary, and explicit getGet()/getPost()/getCookie() are always clearer. But withRequest() is public API that currently routes through getVar(), and until that's changed it needs to work. Happy to open a follow-up switching withRequest() to explicit sources if maintainers prefer that direction.

    rahul05ranjan rahul05ranjan commented on code on Sep 27, 2026 09:16 UTC
    Code Review
    system/HTTP/IncomingRequest.php:1
    @@ -387,7 +388,12 @@ public function getVar($index = null, $filter = null, $flags = null)
                 return $this->getJsonVar($index, false, $filter, $flags);
             }
     
    -        return $this->fetchGlobal('request', $index, $filter, $flags);
    +        // $_REQUEST is populated only once at the start of the request, so it
    +        // can become stale when $_GET is modified later (e.g. by SiteURIFactory).
    +        // Merge the current superglobals instead of reading the stale $_REQUEST.
    +        $data = service('superglobals')->getRequestData();
    +
    +        return $this->fetchFromArray($data, $index, $filter, $flags);

    Thanks for the thorough review. This is the intended direction from #9872 — @paulbalandan suggested returning a merged view of the three superglobals and leaving $_REQUEST untouched, which is exactly what this does. $_REQUEST is itself just a merged view of $_GET/$_POST/$_COOKIE per request_order, so reading the merged view directly is semantically equivalent in normal operation while fixing the staleness bug.

    On the Validation test changes: those tests were setting POST data (id_user, name_user) through setRequestArray() as a shortcut because getVar() happened to read $_REQUEST. Switching them to setPostArray() is more accurate — the data is POST data — and doesn't mask a regression; it reflects the corrected data source. I've also added testGetVarReflectsGetChangesWhenRequestIsStale to lock in the actual fix.

    Explicit $_REQUEST overrides via setRequestArray()/setGlobal('request', ...) are test-only conveniences; in production $_REQUEST is always derived from the other superglobals. The maintainers are moving toward deprecating getVar() entirely, so this is a step in that direction.

    rahul05ranjan rahul05ranjan commented on code on Sep 27, 2026 09:16 UTC
    Code Review
    system/Superglobals.php:1
    @@ -387,6 +387,42 @@ public function setRequestArray(array $array): self
             return $this;
         }
     
    +    /**
    +     * Returns the merged $_GET, $_POST, and $_COOKIE data according to the
    +     * `request_order` (or `variables_order`) ini setting, without mutating
    +     * $_REQUEST.
    +     *
    +     * PHP populates $_REQUEST only once at the start of the request. When
    +     * $_GET is modified later (e.g. by SiteURIFactory), $_REQUEST becomes
    +     * stale. This method returns the current merged values so callers can
    +     * read up-to-date request data without relying on the stale $_REQUEST.
    +     *
    +     * @return array<string, request_items>
    +     */
    +    public function getRequestData(): array
    +    {
    +        $requestOrder = ini_get('request_order');
    +        if ($requestOrder === false || $requestOrder === '') {
    +            $requestOrder = ini_get('variables_order');
    +        }
    +        if ($requestOrder === false || $requestOrder === '') {
    +            $requestOrder = 'GP';
    +        }
    +
    +        $request = [];
    +
    +        foreach (str_split($requestOrder) as $type) {
    +            match ($type) {
    +                'G'     => $request = array_merge($request, $this->get),
    +                'P'     => $request = array_merge($request, $this->post),
    +                'C'     => $request = array_merge($request, $this->cookie),

    Good catch — addressed. I've added focused tests for the cookie branch, order-sensitive overwrite behavior, and unknown order types, and made getRequestData() accept an optional request_order override so precedence can be tested deterministically without mutating ini state:

  • testGetRequestDataMergesCookie — exercises the C branch.

  • testGetRequestDataRespectsOrder — verifies later sources overwrite earlier ones (GP, GPC, PG).

  • testGetRequestDataIgnoresUnknownOrderTypes — confirms unknown letters are skipped.
  • The request_order override is test-only; production callers pass nothing and the ini fallback chain is unchanged.

    rahul05ranjan rahul05ranjan commented on Sep 28, 2026 17:11 UTC
    Author

    @paulbalandan — gentle ping on this one. The rework is complete and follows the direction you outlined in #9872: getVar() now returns a merged view of $_GET/$_POST/$_COOKIE (respecting request_order) instead of reading the stale $_REQUEST, and $_REQUEST is never mutated.

    All Carson checks pass (signed-commits, no-merge-commits, pr-title-linter). The remaining GitHub Actions workflows are showing action_required and need a maintainer to approve them to run (first-time contributor). Would you be able to take a look when you have a moment? Thanks!

    paulbalandan paulbalandan commented on Sep 28, 2026 17:53 UTC
    Reviewer

    Hi, thanks for picking this up. Just a few initial comments:

    1. Since the approach changed, the PR title and body should be edited to reflect the new approach taken. This is because the PR would be squashed on merge with the PR title as the commit message.
    2. The merging of superglobals seems to be not the way PHP would do it. First, when the data contains a numeric key, like when parsing 100=foo, the array_merge would just renumber it. Second, it is not recursive unlike what PHP do when it creates a $_REQUEST.
    3. Docs should be updated to match new behavior. Plus a changelog line.

    paulbalandan paulbalandan commented on Sep 28, 2026 17:54 UTC
    Contributor

    Also, could you remove those backslashes? 😅

    rahul05ranjan rahul05ranjan commented on Sep 29, 2026 06:42 UTC
    Author

    @paulbalandan thanks for the review! All three points are addressed, and the backslashes are gone 😅

    1. PR title/body — updated to reflect the new approach (no more syncRequest()). Title is now fix: make getVar() read merged superglobals instead of stale $_REQUEST.
    2. Merge semantics — switched from array_merge() to array_replace_recursive(), which matches PHP's own $_REQUEST merge (php_autoglobal_merge): numeric keys are preserved and array values are merged recursively. Added testGetRequestDataPreservesNumericKeys and testGetRequestDataMergesRecursively to cover both.
    3. Docs + changelog — updated the getVar() section in the user guide and added a "Bugs Fixed" entry to v4.7.5.rst.

    Let me know if there's anything else you'd like adjusted. Thanks!

    paulbalandan paulbalandan commented on code on Sep 29, 2026 10:23 UTC
    Code Review
    system/Superglobals.php:1
    @@ -387,6 +387,49 @@ public function setRequestArray(array $array): self
             return $this;
         }
     
    +    /**
    +     * Returns the merged $_GET, $_POST, and $_COOKIE data according to the
    +     * `request_order` (or `variables_order`) ini setting, without mutating
    +     * $_REQUEST.
    +     *
    +     * PHP populates $_REQUEST only once at the start of the request. When
    +     * $_GET is modified later (e.g. by SiteURIFactory), $_REQUEST becomes
    +     * stale. This method returns the current merged values so callers can
    +     * read up-to-date request data without relying on the stale $_REQUEST.
    +     *
    +     * @param string|null $requestOrder Overrides the ini setting for testing.
    +     *
    +     * @return array<string, request_items>
    +     */
    +    public function getRequestData(?string $requestOrder = null): array

    The parameter looks to me like explicitly supplied only for testing but depends on the INI setting on production. A cleaner alternative would be to ditch the param entirely and just use ini_set in tests.

    paulbalandan paulbalandan commented on code on Sep 29, 2026 10:24 UTC
    Code Review
    system/Superglobals.php:1
    @@ -387,6 +387,49 @@ public function setRequestArray(array $array): self
             return $this;
         }
     
    +    /**
    +     * Returns the merged $_GET, $_POST, and $_COOKIE data according to the
    +     * `request_order` (or `variables_order`) ini setting, without mutating
    +     * $_REQUEST.
    +     *
    +     * PHP populates $_REQUEST only once at the start of the request. When
    +     * $_GET is modified later (e.g. by SiteURIFactory), $_REQUEST becomes
    +     * stale. This method returns the current merged values so callers can
    +     * read up-to-date request data without relying on the stale $_REQUEST.
    +     *
    +     * @param string|null $requestOrder Overrides the ini setting for testing.
    +     *
    +     * @return array<string, request_items>
    +     */
    +    public function getRequestData(?string $requestOrder = null): array
    +    {
    +        $requestOrder ??= ini_get('request_order');
    +
    +        if ($requestOrder === false || $requestOrder === '') {

    can we just cast string for both ini_get so that just compare to empty string?

    paulbalandan paulbalandan commented on code on Sep 29, 2026 10:26 UTC
    Code Review
    user_guide_src/source/changelogs/v4.7.5.rst:1
    @@ -61,6 +61,7 @@ Bugs Fixed
     - **I18n:** Fixed a bug where ``Time::today()``, ``Time::yesterday()``, and ``Time::tomorrow()`` ignored the specified ``$timezone`` and ``setTestNow()`` when calculating the day.
     - **Logger:** Fixed a bug where interpolating a log message with array or non-stringable context values could raise PHP warnings or errors.
     - **Validation:** Fixed a bug where ``valid_cc_number`` accepted non-digit characters (e.g., a decimal point) in the card number. Such values could pass the Luhn check and triggered an ``Undefined array key`` warning inside it; the number is now checked with ``ctype_digit()``.
    +- **IncomingRequest:** Fixed a bug where ``getVar()`` returned stale data after ``$_GET`` was updated during URI parsing. It now returns a merged view of ``$_GET``, ``$_POST``, and ``$_COOKIE`` (respecting the ``request_order`` ini setting) instead of reading the stale ``$_REQUEST``.

    pls align the entry alphabetically. and i think it should be HTTP

    paulbalandan paulbalandan commented on Sep 29, 2026 10:27 UTC
    Reviewer

    Thanks for the changes. A few more comments.

    rahul05ranjan rahul05ranjan commented on Sep 29, 2026 11:04 UTC
    Author

    @paulbalandan thanks for the follow-up! All three points addressed:

    1. Dropped the $requestOrder parameter — getRequestData() now takes no arguments and reads the ini settings directly. Tests use ini_set('request_order', ...) to exercise the different orders deterministically.
    2. Cast ini_get() to string — both request_order and variables_order are now (string) ini_get(...) and compared against '' only.
    3. Changelog — the entry is now alphabetically ordered and labeled HTTP: (referencing IncomingRequest::getVar()).

    Let me know if there's anything else. Thanks!

    paulbalandan paulbalandan commented on Sep 29, 2026 14:02 UTC
    Contributor

    Can you check on the failing tests?

    paulbalandan paulbalandan commented on Oct 01, 2026 12:48 UTC
    Reviewer

    Thanks for checking that ini_set won't work for request_order. Minor comments, otherwise looks good:

    1. incomingrequest.rst line 173 still reads that getVar can fallback to $_REQUEST. it should now be at the merged array
    2. the phpstan-ignore at the test demonstrated that the array shapes at Superglobals are incorrectly typed. out of scope of this PR though

    Copilot Copilot commented on code on Oct 01, 2026 13:33 UTC
    Code Review
    system/HTTP/RequestTrait.php:1
    @@ -291,6 +291,22 @@ public function fetchGlobal(string $name, $index = null, ?int $filter = null, $f
                 $this->populateGlobals($name);
             }
     
    +        return $this->fetchFromArray($this->globals[$name], $index, $filter, $flags);
    +    }
    +
    +    /**
    +     * Fetches one or more items from an array, applying the same filtering
    +     * and index resolution as fetchGlobal().
    +     *
    +     * @param array<string, mixed>          $data
    +     * @param int|list<string>|string|null  $index
    +     * @param int|null                      $filter Filter constant
    +     * @param array<string, mixed>|int|null $flags  Options
    +     *
    +     * @return mixed
    +     */
    +    protected function fetchFromArray(array $data, $index = null, ?int $filter = null, $flags = null)

    Request and IncomingRequest are non-final extension points, so adding this generic protected method on the develop patch line can make an existing application subclass that already defines fetchFromArray() with another signature fail at class loading. Keep this helper out of the inherited protected API (for example, use an internal/private collaborator or reuse the existing fetch path without introducing a new protected symbol).

    Copilot Copilot commented on code on Oct 01, 2026 13:33 UTC
    Code Review
    system/Superglobals.php:1
    @@ -387,6 +387,51 @@ public function setRequestArray(array $array): self
             return $this;
         }
     
    +    /**
    +     * Returns the merged $_GET, $_POST, and $_COOKIE data according to the
    +     * `request_order` (or `variables_order`) ini setting, without mutating
    +     * $_REQUEST.
    +     *
    +     * PHP populates $_REQUEST only once at the start of the request. When
    +     * $_GET is modified later (e.g. by SiteURIFactory), $_REQUEST becomes
    +     * stale. This method returns the current merged values so callers can
    +     * read up-to-date request data without relying on the stale $_REQUEST.
    +     *
    +     * @param string|null $requestOrder Overrides the `request_order` ini
    +     *                                  setting. Useful for testing, since the
    +     *                                  ini setting cannot be changed at runtime.
    +     *
    +     * @return array<string, request_items>
    +     */
    +    public function getRequestData(?string $requestOrder = null): array
    +    {
    +        $requestOrder ??= (string) ini_get('request_order');
    +
    +        if ($requestOrder === '') {
    +            $requestOrder = (string) ini_get('variables_order');
    +        }
    +
    +        if ($requestOrder === '') {
    +            $requestOrder = 'GP';
    +        }
    +
    +        $request = [];
    +
    +        foreach (str_split($requestOrder) as $type) {

    PHP accepts lowercase directive letters and merges each G/P/C source only on its first occurrence; this loop only recognizes uppercase and re-applies duplicates. Consequently, request_order=gp makes getVar() return no request data, while GPG lets GET overwrite POST unlike PHP's $_REQUEST. Normalize case and de-duplicate while preserving the first occurrence, and cover both cases in the order test.

    copilot-pull-request-reviewer[bot] copilot-pull-request-reviewer[bot] commented on Oct 01, 2026 13:33 UTC
    Reviewer

    <!-- ccr-overview-v2 -->

    Copilot review overview

    🟡 Changes recommended

    Request-order parsing diverges from PHP semantics, and the new protected method introduces a patch-line compatibility risk.

    Review effort: Balanced
    Findings: 1 <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.png" alt="High severity" width="62" height="18" align="texttop"></picture> · 1 <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture>

    <details open>
    <summary><strong>Open (2)</strong></summary>

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.png" alt="High severity" width="62" height="18" align="texttop"></picture> [Avoid adding protected helper that breaks existing subclasses](#discussion_r4155938975) · New

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> [Normalize and deduplicate request_order directives](#discussion_r4155939048) · New

  • </details>

    <details>
    <summary><strong>Resolved since last review (2)</strong></summary>

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.png" alt="High severity" width="62" height="18" align="texttop"></picture> [Add cookie and precedence coverage for merged request variables](#discussion_r4114562307)

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.png" alt="High severity" width="62" height="18" align="texttop"></picture> [Preserve explicit request overrides when merging superglobals](#discussion_r4114562292)

  • </details>

    michalsn michalsn commented on Oct 01, 2026 13:39 UTC
    Reviewer

    I see a big problem because this will not work anymore:

    $request->setGlobal('request', ['foo' => 'bar']);
    $request->getVar('foo');
    

    rahul05ranjan rahul05ranjan commented on Oct 05, 2026 08:23 UTC
    Author

    @michalsn thanks for catching this. Fixed in 90199d6: setGlobal('request', ['foo' => 'bar']) takes precedence, including an explicit empty array. I added a regression test for your example. My earlier claim that these overrides were only test conveniences was too broad; this public API needs to keep working.

    The same commit removes the added protected fetchFromArray() helper and reuses the existing fetchGlobal() path, with temporary merged data cleared in finally. A subclass with its own differently shaped fetchFromArray() now loads successfully, and repeated reads still see fresh data even after a filter throws.

    request_order is now case-insensitive and each source is processed once (gp, GPG, and mixed-case repeated sources are covered). @paulbalandan the JSON note now says "merged superglobal data" instead of $_REQUEST. The PR description is updated too.

    Focused PHP 8.2 checks: IncomingRequest 116 tests, Superglobals 55, Request 40, and the three affected Validation cases all pass (214 total). File-scoped PHPStan and CS checks pass. The previous head's CI was green. On this new head, Carson checks pass and GitHub verifies the commit signature, but the remaining workflows are action_required and need maintainer approval. Could a maintainer approve them? PHPUnit: https://github.com/codeigniter4/CodeIgniter4/actions/runs/37283280737

    carson-codeigniter4[bot] carson-codeigniter4[bot] commented on Oct 05, 2026 08:23 UTC
    Bot

    Hi there, @rahul05ranjan! :wave:

    It looks like this pull request does not follow our template:

  • Keep the Description heading from the pull request template and explain what you have changed, and why.
  • Please update the description to follow the template. The needs template label will be removed automatically once it does.

    <!-- carson:template-enforcer -->

    rahul05ranjan rahul05ranjan commented on code on Oct 05, 2026 08:23 UTC
    Code Review
    system/HTTP/RequestTrait.php:1
    @@ -291,6 +291,22 @@ public function fetchGlobal(string $name, $index = null, ?int $filter = null, $f
                 $this->populateGlobals($name);
             }
     
    +        return $this->fetchFromArray($this->globals[$name], $index, $filter, $flags);
    +    }
    +
    +    /**
    +     * Fetches one or more items from an array, applying the same filtering
    +     * and index resolution as fetchGlobal().
    +     *
    +     * @param array<string, mixed>          $data
    +     * @param int|list<string>|string|null  $index
    +     * @param int|null                      $filter Filter constant
    +     * @param array<string, mixed>|int|null $flags  Options
    +     *
    +     * @return mixed
    +     */
    +    protected function fetchFromArray(array $data, $index = null, ?int $filter = null, $flags = null)

    Fixed in 90199d6. The new protected helper is removed and RequestTrait is restored to its existing implementation. getVar() reuses fetchGlobal() with temporary merged data cleared in finally. Added a regression test using an IncomingRequest subclass with its own incompatible fetchFromArray() signature; it failed at class loading before the fix and now passes.

    rahul05ranjan rahul05ranjan commented on code on Oct 05, 2026 08:23 UTC
    Code Review
    system/Superglobals.php:1
    @@ -387,6 +387,51 @@ public function setRequestArray(array $array): self
             return $this;
         }
     
    +    /**
    +     * Returns the merged $_GET, $_POST, and $_COOKIE data according to the
    +     * `request_order` (or `variables_order`) ini setting, without mutating
    +     * $_REQUEST.
    +     *
    +     * PHP populates $_REQUEST only once at the start of the request. When
    +     * $_GET is modified later (e.g. by SiteURIFactory), $_REQUEST becomes
    +     * stale. This method returns the current merged values so callers can
    +     * read up-to-date request data without relying on the stale $_REQUEST.
    +     *
    +     * @param string|null $requestOrder Overrides the `request_order` ini
    +     *                                  setting. Useful for testing, since the
    +     *                                  ini setting cannot be changed at runtime.
    +     *
    +     * @return array<string, request_items>
    +     */
    +    public function getRequestData(?string $requestOrder = null): array
    +    {
    +        $requestOrder ??= (string) ini_get('request_order');
    +
    +        if ($requestOrder === '') {
    +            $requestOrder = (string) ini_get('variables_order');
    +        }
    +
    +        if ($requestOrder === '') {
    +            $requestOrder = 'GP';
    +        }
    +
    +        $request = [];
    +
    +        foreach (str_split($requestOrder) as $type) {

    Fixed in 90199d6. The order string is normalized to uppercase and sources are deduplicated while retaining their first occurrence. Added assertions for gp, GPG, and gPcGpC; the focused Superglobals tests pass.

    michalsn michalsn commented on Oct 06, 2026 11:03 UTC
    Reviewer

    I still have two concerns:
    1. Calling fetchGlobal('request', ...) before getVar() populates the request cache. getVar() then treats it as an explicit override and returns stale REQUEST data instead of merged GPC data. We should distinguish cached data from an explicit setGlobal() override.
    2. An explicitly empty request_order="" should produce an empty result. PHP falls back to variables_order only when request_order is unset, but this implementation treats both cases the same.

    Could we add regression tests for these cases?

    rahul05ranjan rahul05ranjan commented on Oct 08, 2026 07:55 UTC
    Author

    @michalsn Thanks for flagging both cases. The cached-request case was real: fetchGlobal('request', ...) could fill the cache before getVar(). I now distinguish an explicit setGlobal('request', ...) override from that cache, and added a regression for the call order you described.

    For the empty request_order case, I checked PHP's own php.ini documentation: an empty value falls back to variables_order; it does not make $_REQUEST empty. I kept that behavior and added a test for getRequestData('').

    I also rebased away the merge commit that was failing Carson's check. All branch commits are signed. Focused PHP 8.2 tests pass: 117 IncomingRequest, 56 Superglobals, and 40 Request tests. Carson's no-merge-commits and signed-commits checks now pass. The remaining workflows on this new head are awaiting maintainer approval to run. Could a maintainer approve them when reviewing? PHPUnit run

    michalsn michalsn commented on Oct 08, 2026 08:34 UTC
    Contributor

    For the empty request_order case, I checked PHP's own php.ini documentation: an empty value falls back to variables_order; it does not make $_REQUEST empty. I kept that behavior and added a test for getRequestData('').

    Ok, sounds good.

    rahul05ranjan rahul05ranjan commented on Oct 08, 2026 09:53 UTC
    Author

    The two Coding Standards jobs flagged the same one-line docblock on the new request-override property. I changed it to the layout PHP CS Fixer requested. The focused PHP 8.2 fixer check now reports 0 files to fix.

    The updated branch is at 59ff334a2. The new workflows are waiting for maintainer approval again; Coding Standards run. Could a maintainer approve that run when convenient?

    michalsn michalsn commented on Oct 08, 2026 20:12 UTC
    Reviewer

    I've spent quite a while thinking about this, and my main concern is the complexity of the proposed behavior.

    getVar() now combines JSON handling, explicit REQUEST overrides, fresh GPC merging, and temporarily replacing and restoring the REQUEST cache. Each part has a reason, but together they make the method harder to understand and maintain.

    This also introduces different data lifetimes within the same request object. After GET data changes through the Superglobals service, getVar() sees the updated value, while getGet() may still return a previously cached value. If setGlobal('request', ...) is called, getVar() uses that override instead of fresh GPC data. Understanding the result therefore requires knowing both which method is called and how the request object was previously modified.

    The finally block handles cache restoration correctly, but future changes, custom fetchGlobal() implementations, and filter callbacks need to account for that temporary state.

    I don't think these mechanisms are inherently wrong. I'm questioning whether this additional complexity is justified for a bug caused by GET normalization in SiteURIFactory. Could we reconsider a one-time REQUEST update at that point, while preserving application-defined REQUEST values? That would keep the fix closer to its cause and preserve getVar() existing lookup behavior.

    The user guide says this method exists for backward compatibility, so I would prefer to keep this fix as narrow as possible.

    If we decide that the behavior introduced by this PR is what we want long term, I think we should target the 4.8 branch instead of develop, since it changes the existing contract of getVar().

    Thoughts?

    rahul05ranjan rahul05ranjan commented on Oct 09, 2026 06:17 UTC
    Author

    @michalsn Thanks for the careful review. I agree the current getVar() path has grown complicated for a fix to URI normalization. The temporary cache swap and explicit-override flag are a lot of machinery for a backward-compatibility method.

    I avoided changing SiteURIFactory because #10205 was closed, but I shouldn't treat that as ruling out your narrower proposal. That PR rebuilt $_REQUEST after each setGetArray() call; a one-time update that preserves application-defined REQUEST values is a different approach.

    I'd be happy to rework this around that normalization point, keeping regression tests for withRequest() and explicit REQUEST values. @paulbalandan, does that align with why #10205 was closed? If the team prefers the fresh merged behavior in this PR, I agree it should target 4.8.

    paulbalandan paulbalandan commented on Oct 09, 2026 08:18 UTC
    Contributor

    To answer directly: #10205 was closed because I preferred a merged view at the time, not because a one-time refresh was ruled out in #9872. Having seen where the merged view ends up, I agree with @michalsn. Let's do it as two steps. Please open a new PR against develop with the one-time $_REQUEST refresh in SiteURIFactory, refreshing only the keys that come from GET, POST and COOKIE so other values already in $_REQUEST stay untouched. Bring getRequestData() and its tests along since the refresh needs that merge, plus the withRequest() regression tests. Once that is up we can close this one. The remaining idea here, getVar() reading live data, is really a contract change, and the better 4.8 follow-up is to deprecate getVar() and have withRequest() read the merged data directly. Happy to review that as a separate PR if you want to take it.

    michalsn michalsn commented on Oct 09, 2026 10:00 UTC
    Contributor

    That sounds good to me. Once the one-time refresh fixes the bug, I would prefer to keep getVar() existing behavior rather than change its contract unnecessarily.

    ---

    For 4.8, we could formally deprecate both getVar() and withRequest() while preserving their behavior. The user guide already discourages using both methods, and explicitly passing the data to validate seems like a clearer migration path. We should also consider Controller::validate(), since it uses withRequest() internally.

    That said, I would prefer to keep these changes gradual and avoid changing too much at once. Deprecation should give users a clear migration path while keeping existing applications working.

    I'm also wondering whether we would need replacement methods with clearly defined rules for selecting input data, or whether the existing alternatives are sufficient and we should focus on promoting them.

    rahul05ranjan rahul05ranjan commented on Oct 09, 2026 12:49 UTC
    Author

    Thanks, @paulbalandan and @michalsn. I opened #10606 from current develop with the one-time REQUEST refresh in SiteURIFactory. It carries getRequestData() and its merge tests, plus regressions for both URI parsing paths and withRequest(). getVar() itself is unchanged.

    The focused tests and file-scoped checks pass, and the commit is verified. I'll close this PR in favor of #10606; the broader deprecation discussion can stay separate for 4.8.

    Reviewers
    Assignees
    rahul05ranjan rahul05ranjan
    Labels
    risk: low confidence: 85% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 45.9% (MEDIUM) · Higher = larger blast radius
    45.9%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 85% · Lower = rushed or shallow review
    85%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 6.9% · Safe to merge
    6.9%