PHP: undefined constant while defining it - php

I'm getting the following error in PHP:
Notice: Use of undefined constant CONSTANT
on the exact line where I define it:
define(CONSTANT, true);
What am I doing wrong? I defined it, so why does it say "Undefined constant"?

You need to quote the string which becomes a constant
define('CONSTANT', true);

The best way to understand what are you doing wrong is to read PHP manual.
Here is definition of define function.
bool define ( string $name , mixed $value [, bool $case_insensitive = false ] )
So the first argument must be a string.

If you write it like that you are using the value of an already defined constant as a constant name.
What you want to do is to pass the name as a string:
define('CONSTANT', true);

Although not really, strictly relevant to your case, it is most desirable to first check that a CONSTANT has not been previously defined before (re)defining it.... It is also important to keep in mind that defining CONSTANTS using define requires that the CONSTANT to be defined is a STRING ie. enclosed within Quotes like so:
<?php
// CHECK THAT THE CONSTANTS HASN'T ALREADY BEEN DEFINED BEFORE DEFINING IT...
// AND BE SURE THE NAME OF THE CONSTANT IS WRAPPED WITHIN QUOTES...
defined('A_CONSTANT') or define('A_CONSTANT', 'AN ALPHA-NUMERIC VALUE', true);
// BUT USING THE CONSTANT, YOU NEED NOT ENCLOSE IT WITHIN QUOTES.
echo A_CONSTANT; //<== YIELDS:: "AN ALPHA-NUMERIC VALUE"

See below currect way to define constant
define('Variable','Value',case-sensitive);
Here Variable ==> Define your Constant Variable Name
Here Value ==> Define Constant value
Here case-sensitive Defult value 'false', Also you can set value 'true' and 'false'

Related

How does PHP deal with undefined constant?

I'm using PHP 7.0.2
Consider below text from the PHP Manual :
Why is $foo[bar] wrong?
Always use quotes around a string literal array index. For example,
$foo['bar'] is correct, while $foo[bar] is not. But why? It is common
to encounter this kind of syntax in old scripts:
<?php
$foo[bar] = 'enemy';
echo $foo[bar];
// etc
?>
This is wrong, but it works. The reason is that this code has an
undefined constant (bar) rather than a string ('bar' - notice the
quotes). It works because PHP automatically converts a bare string (an
unquoted string which does not correspond to any known symbol) into a
string which contains the bare string. For instance, if there is no
defined constant named bar, then PHP will substitute in the string
'bar' and use that.
From the above text I'm not clear that when PHP encountered bar() which does not correspond to any known symbol i.e. undefined constant what PHP actually does with it?
How can PHP convert a bare string bar into a string which contains the bare string i.e. 'bar'?
Is PHP defining a constant titled bar and assigning a string value 'bar' to it?
Like bar = 'bar';
If yes, can I make use of the constant bar somewhere in the further code?
Because in PHP only a variable and a constant can contain value/hold the value and not type like string contain/hold any value.
From the above text I'm not clear that when PHP encountered bar() which does not correspond to any known symbol i.e. undefined constant what PHP actually does with it?
The warning associated with this behavior says it all, really:
Warning: Use of undefined constant bar - assumed 'bar' (this will throw an Error in a future version of PHP)
The bare word is treated as a string, not as a constant -- it's treated exactly as if you'd written 'bar'. The expression defined('bar') will still be false, other instances of bar in your code will also throw warnings, and code which depends on this behavior will stop working entirely in future versions of PHP.

Why does calling a function within define() break my site?

The following breaks my site quite badly:
define('FOO', get_foo());
However, the following works fine:
define('FOO', 'BAR');
You can't use function in define, this is not good. Define is used to make constants. Constants must not be changed, must have the same value during all the time. Functions, like get_foo(), can return different values. Php thinks that you want to put changable value to the constant. Try to put the result if this function to the variable:
$foo = get_foo();
Because define() expects a value for the constant and not the returned value of a function:
The value of the constant; only scalar and null values are allowed.
Scalar values are integer, float, string or boolean values. It is
possible to define resource constants, however it is not recommended
and may cause unpredictable behavior.

php constant case-insensitive issue

I'm overriding a constant with case in-sensitive parameter. But php doesn't give me "constant already defined" error. I've enabled E_ALL,E_STRICT errors.
Example:1
define('ONE',1000);
define('one',2000,true);
echo ONE; // prints 1000
echo one; // prints 2000
In the second line, i'm making 'one' as another constant with case in-sensitive, which means redefining 'ONE'. But PHP gives no error/warning.
Example:2
define('ONE',1000,true);
define('one',2000);
echo ONE; // prints 1000 with constant already defined notice
echo one; // prints 1000
Here i can get error notice.
What's the difference between these two code blocks.?
From the documentation:
Note: Case-insensitive constants are stored as lower-case.
Thus, when trying to define the lower-cased version of the constant in your second example, the constant is already defined due to the prior case-insensensitive definition of a constant with the same name.
define('ONE', 1000, true); // defines strtolower("ONE") = "one"
define('one', 2000); // error redefining "one"
In the first scenario, there is no such collision:
define('ONE', 1000); // defines "ONE"
define('one', 2000, true); // defines strtolower("one") = "one"
The third Parameter in the define function is the case_insensitive option.
http://php.net/manual/de/function.define.php
In the first Example the constant ONE ist defined. And the constant one with case_insensitive true. Means you got a variable you can reach via ONE and a variable you can reach via oNe,One,oNE etc.
In the secound Example you first define a constant ONE with case_insensitive true and then the constant one. But this time all possible names (OnE,oNe,one) are already given, so the interpreter gives you a error notice

PHP undefined constant testing

In PHP if I define a constant like this:
define('FOO', true);
if(FOO) do_something();
The method do_something gets executed as expected.
But if I don't define the BOO constant below:
if(BOO) do_something();
Then do_something also gets executed. What's going on here?
// BOO has not been defined
if(BOO) do_something();
BOO will be coerced into the string BOO, which is not empty, so it is truthy.
This is why some people who don't know better access an array member with $something[a].
You should code with error_reporting(E_ALL) which will then give you...
Notice: Use of undefined constant HELLO - assumed 'HELLO' in /t.php on line 5
You can see if it is defined with defined(). A lot of people use the following line so a PHP file accessed outside of its environment won't run...
<?php defined('APP') OR die('No direct access');
This exploits short circuit evaluation - if the left hand side is true, then it doesn't need to run the right hand side.
If you enable error logging, you'll see an error like the following:
PHP Notice: Use of undefined constant BOO - assumed 'BOO' in file at line N
What's happening is that PHP is just arbitrarily assuming that you meant to use 'BOO' and just forgot the quotes. And since strings other than '' and '0' are considered "true", the condition passes.
If it's not the existance of the constant you want to test, but if you want to test the value of the constant you defined, this might be a better way: if(BOO === true) or if(BOO === false)
if($FOO) do_something();
Just using FOO takes it as a value rather than the variable you defined. Better to use PHP's defined.
PHP is dynamically typed. You can achieve what you're trying to do with a function such as this:
function consttrue($const) {
return !defined($const) ? false : constant($const);
}
PHP will automatically make the guess that you meant the string format, which a string will return true.
However you should use the defined method:
bool defined ( string $name )
So it would be:
if(defined('BOO')) {\\code }
Another option is to use php's constant() function, as in:
if (constant('BOO')) doSomething();
Remember to enclose the constant's name in quotes.
Here is a PHP replit demonstrating the examples below.
Ap per the php docs, if the constant is defined, its value is returned; otherwise, null is returned.
Since null is falsey, this will behave as expected.
This can be used in cases where you need to know if something is explicitly defined as true (or at lease a truthy value) vs either not defined, or defined with a falsey value. This works particularly well when having a variable defined is the exception, or having it undefined could be a security risk.
if (constant('IS_DEV')) {
// *Remember to enclose the constant's name in quotes.*
// do stuff that should only happen in a dev environment
// By Default, if it didn't get defined it is, as though, 'false'
}
Using constant() when checking against variables is a good practice to mitigate against security risks in certain situations. For example, printing out php info only if a certain constant is (defined and) TRUE.
As your question shows, PHP's string conversion would expose details if somehow the constant did not get defined.
Alternately, you could:
if (defined('IS_DEV') && (IS_DEV)) {
// *Remember to enclose the constant's name in quotes for the FIRST operator.*
// do stuff that should only happen in a dev environment
}
Another method that would work is to use === or !==, which tests exact equality (including type), without performing typecast a conversion.
if (IS_DEV === true)) {
// do stuff that should only happen in a dev environment
}

PHP: getting a "use of undefined constant COOKIE_LOGIN" how do I fix this?

I haven't made any changes to the code affecting the COOKIE's and now I get the following:
Use of undefined constant COOKIE_LOGIN - assumed 'COOKIE_LOGIN'
//Destroy Cookie
if (isset($_COOKIE[COOKIE_LOGIN]) && !empty($_COOKIE[COOKIE_LOGIN]))
setcookie(COOKIE_LOGIN,$objUserSerialized,time() - 86400 );
I'm not sure what I need to do to actually change this since I do not know what chnaged to begin with and so cannot track the problem.
Thanks.
You need to surround the array key by quotes:
if (isset($_COOKIE['COOKIE_LOGIN']) && !empty($_COOKIE['COOKIE_LOGIN']))
setcookie('COOKIE_LOGIN',$objUserSerialized,time() - 86400 );
PHP converts unknown literals to strings and throws a warning. Your php.ini probably had the error reporting level to not display warnings but someone may have updated it or something. In either case, it is bad practice to take advantange of PHP's behavior in this case.
For more information, check out the php documentation:
Always use quotes around a string literal array index. For example, $foo['bar'] is correct, while $foo[bar] is not.
This is wrong, but it works. The reason is that this code has an undefined constant (bar) rather than a string ('bar' - notice the quotes). PHP may in future define constants which, unfortunately for such code, have the same name. It works because PHP automatically converts a bare string (an unquoted string which does not correspond to any known symbol) into a string which contains the bare string. For instance, if there is no defined constant named bar, then PHP will substitute in the string 'bar' and use that.
You can't say $_COOKIE[COOKIE_LOGIN] without error unless COOKIE_LOGIN is an actual constant that you have defined, e.g.:
define("COOKIE_LOGIN", 5);
Some people have habits where they will write code like:
$ary[example] = 5;
echo $ary[example];
Assuming that "example" (as a string) will be the array key. PHP has in the past excused this behavior, if you disable error reporting. It's wrong, though. You should be using $_COOKIE["COOKIE_LOGIN"] unless you have explicitly defined COOKIE_LOGIN as a constant.

Categories