PHP Function Assert - How to Use it Properly
Assertions are a great tool for testing your code, checking that an expression fulfills some criteria, and in case it doesn’t, the program stops instantly. They are also very useful when sanitizing and validating input parameters.
The php function assert is a built-in function that helps with debugging by checking if an expression is correct and displaying a message if it’s not. When not used properly, however, it can lead to security vulnerabilities. For example, if an attacker can control the value of the expression that the assertion is checking, they could use it to bypass detection by modern web scanners that look for more common functions such as eval.
In order to prevent such attacks, it’s important to sanitize and validate any input parameters that are passed to the assert() function. It’s also recommended to disable the assert() function in production environments, by setting zend.assertions = 0 (or using the configuration directive ASSERT_CALLBACK).
The ASSERT_CALLBACK option allows you to specify a callback function that will be called if an assert() function fails, which can be useful for testing automated scripts and logging errors. It accepts three arguments: the file where the assert() failed, the line of the failed line, and the expression that was tested. It’s also possible to include a fourth argument, a description of the failure (as a string). In addition, there is a static function called LogThrowable($throwable, bool $expected) that can be used to log an exception.