note 123943 added to function.constant

From: Date: Fri, 14 Jun 2019 21:24:35 +0000
Subject: note 123943 added to function.constant
Groups: php.notes 
Request: Send a blank email to php-notes+get-211256@lists.php.net to get a copy of this message
The use of constant() (or some other method) to ensure the your_constant was defined is particularly important when it is to be defined as either true or false. For example, taken from this Stackoverflow Question https://stackoverflow.com/questions/5427886/php-undefined-constant-testing/56604602#56604602) If BOO did NOT get defined as a constant, for some reason, <?php if(BOO) do_something(); ?> would evaluate to TRUE and run anyway. A rather unexpected result. The reason is that PHP ASSUMES you "forgot" quotation marks around BOO when it did not see it in its list of defined constants. So it evaluates: if ('BOO')... Since every string, other than the empty string, is "truthy", the expression evaluates to true and the do_something() is run, unexpectedly. If you instead use: <?php if (constant(BOO)) do_something() ?> then if BOO has not been defined, constant(BOO) evaluates to null, which is falsey, and if (null)... becomes false, so do_something() is skipped, as expected. The PHP behavior regarding undefined constants is particularly glaring when having a particular constant defined is the exception, "falsey" is the default, and having a "truthy" value exposes a security issue. For example, <?php if (IS_SPECIAL_CASE) show_php_info() ?> . There are other ways around this PHP behavior, such as <?php if (BOO === true) do_something(); ?> or <?php if (defined('BOO') && BOO) do_something() ?>. Note that only the version using defined() works without also throwing a PHP Warning "error message." Here is a php repl.it demonstration: https://repl.it/@sherylhohman/php-undefined-constants-beware-of-truthy-conversion?language=php_cli&folderId= (disclosure: I also submitted an answer to the SO question linked to above) ---- Server IP: 208.43.231.9 Probable Submitter: 82.199.157.34 (proxied: 47.155.18.201) ---- Manual Page -- http://php.net/manual/en/function.constant.php Edit -- https://master.php.net/note/edit/123943 Del: integrated -- https://master.php.net/note/delete/123943/integrated Del: useless -- https://master.php.net/note/delete/123943/useless Del: bad code -- https://master.php.net/note/delete/123943/bad+code Del: spam -- https://master.php.net/note/delete/123943/spam Del: non-english -- https://master.php.net/note/delete/123943/non-english Del: in docs -- https://master.php.net/note/delete/123943/in+docs Del: other reasons-- https://master.php.net/note/delete/123943 Reject -- https://master.php.net/note/reject/123943 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#211256) next »