Modifying raw $_POST data early in the lifecycle

Yes, there are points during the WordPress request life-cycle that provide hooks for you to make modification to the request and other parameters available, more on that in just a moment.

Consideration…

You can modify superglobals, as you are aware, but in doing so you may be introducing unexpected behaviour into your application especially if you are performing sanitization/validation on a key-value pair in one area of your application but which is then accessed in another area of your application, using different superglobals, be it under your control or the control of another plugin (or theme).

For example you may do:

// assume value of: $_POST['something'] → cats
$_POST['something'] = str_replace('cats', 'dogs', $_POST['something']);

And someone else does:

// value is now: $_POST['something'] → dogs
echo $_REQUEST['something']; // → cats

If someone else (or you) unintentionally uses $_REQUEST instead of $_POST, you can expect different results if you have not altered both superglobals.


Recommendation…

I’d recommend you change your approach to modifying data by determining:

  • what your actual use case is
  • who needs to use the data (you only and or other plugins/themes)
  • determine a logical entry point for where that data is made accessible to others

Here is a (contrived) example:

function someone_else_interfere_with_things( $data ) {
    return 'megaladons';
}

add_filter( 'interfere_with_things', 'someone_else_interfere_with_things', 10 );

function interfere_with_things() {
    // ... do sanity checks here

    $data = isset( $_POST['something'] ) ? $_POST['something'] : 'default';
    $data = apply_filters( 'interfere_with_things', str_replace( 'cats', 'dogs', $data ) );

    echo $data; // megaladons!!!
}

add_action( 'init', 'interfere_with_things', 1 );

Other plugins/themes or elsewhere in your own code, you then rely upon the custom filter interfere_with_things where there is a common understanding that at this point other code can expect to modify values in a prepared state that is consistent.

If someone else then goes off and pulls things out of superglobals, that’s on them at that point.


Alternative hooks to init

If you are still set on modifying globals earlier in a request life cycle then you may want to consider other hooks such as:

  • plugins_loaded
  • after_setup_theme
  • request
  • parse_request
  • among others…

All of which fire earlier than init.

tech