PHP RFC: Core Functions Throwing Exceptions in PHP 7


Concern has been raised over the way failure is indicated by several functions in the core that are often used for security purposes. These functions may fail open, allowing execution to continue, potentially compromising the security of an application. Failure of these functions is only indicating failure through a return value that may be inappropriate cast and used or requiring further function calls to check for failure. It is far to easy for an uninformed programmer to be unaware of the potential for failure and the consequences of neglecting to check for failure, so it is imperative that these functions fail closed, so execution cannot continue if the error is ignored.

The following functions are addressed by this RFC:

  • random_int()
  • random_bytes()
  • preg_match()
  • preg_match_all()
  • preg_replace()
  • preg_filter()
  • preg_split()
  • preg_replace_callback()
  • preg_replace_callback_array()


To fail closed while allowing the error to be handled, it is this RFCs proposal that the functions above throw exceptions upon failure. The specific types of exceptions and conditions from which they are thrown are outlined below.


  • Throws Exception if generating sufficiently random data fails.
  • Throws Error if $min > $max.


  • Throws Exception if generating sufficiently random data fails.
  • Throws Error if $length ⇐ 0.


  • All functions throw Exception if the PCRE engine fails.

Backward Incompatible Changes

random_int() and random_bytes() are new functions to PHP 7, so changes to these functions do not have any backwards compatibility issues.

Failure of the PCRE engine is uncommon and only occurs when prce.jit is enabled with certain input strings and patterns. Support for PRCE's JIT compilation was not added until PHP 7.

Proposed PHP Version

PHP 7.0

Future Scope

This RFC does not address how exceptions should be thrown from other core functions. This question will be addressed in a separate RFC. Focus was given to the particular functions in this RFC due to their importance to security applications.

Proposed Voting Choices

  • Throw exceptions
  • Keep current behavior

Patches and Tests

Below are implementations of random_int() and random_bytes() which throw exceptions, though not exactly what is outlined above. The pulls will be updated to throw the exceptions described above before merging.


rfc/core-function-exceptions.txt · Last modified: 2017/09/22 13:28 (external edit)