I have a function that I am trying to run but it shows the message as
CONSTANT already defined.
I tried to put a condition saying "if defined" about the function but still nothing. Is there any method to ignore this and see the output?
Replace this:
define('constant', 'value');
with this:
if (!defined('constant')) define('constant', 'value');
define()
Example:
/* Note the use of quotes, this is important. This example is checking
* if the string 'TEST' is the name of a constant named TEST */
if (defined('TEST')) {
echo TEST;
}
Is this how you check for constants:
if (defined('TEST')) {
echo TEST;
}
Maybe you're not doing the check properly OR the constant you are checking for isn't the cause of the error, some rogue include file might have a different constant and produces an overlap / re-definition.
Related
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'
So I'm using a PHP framework called fuelphp, and I have this page that is an HTML file, so I can't use PHP in it. I have another file that has a top bar in it, which my HTML file will call through ajax.
How do I check if a constant exists in PHP?
I want to check for the the fuelphp framework file locations.
These are the constants I need to check for (actually, I only have to check one of them):
define('DOCROOT', __DIR__.DIRECTORY_SEPARATOR);
define('APPPATH', realpath(__DIR__.'/fuel/app/').DIRECTORY_SEPARATOR);
define('PKGPATH', realpath(__DIR__.'/fuel/packages/').DIRECTORY_SEPARATOR);
define('COREPATH', realpath(__DIR__.'/fuel/core/').DIRECTORY_SEPARATOR);
require APPPATH.'bootstrap.php';
edit:
I realized that these aren't variables they are constants...
First, these are not variables, but constants.
And you can check their existence by using the defined() function :
bool defined ( string $name )
Checks whether the given constant exists and is defined.
Use defined() function, for example:
if (defined('VAR_NAME')) {
// Something
}
Check using defined('CONSTANT') function.
An example from the manual:
<?php
/* Note the use of quotes, this is important. This example is checking
* if the string 'TEST' is the name of a constant named TEST */
if (defined('TEST')) {
echo TEST;
}
?>
here's a cooler & more concise way to do it:
defined('CONSTANT') or define('CONSTANT', 'SomeDefaultValue');
credit: daniel at neville dot tk
https://www.php.net/manual/en/function.defined.php#84439
I take it you mean CONSTANTS not variables! the function is defined();
see here: defined
With defined you'll have to do something like that:
if (defined("CONST_NAME"))
$value = CONST_NAME;
This will work, but you'll could get an annoying error message in your code editor (in my case Visual Studio Code with PHP Inteliphense extension) for the second line, since it wont find CONST_NAME.
Another alternative would be to use the constant function. It takes an string as the constant name and returns null if the constant is not defined:
$value = constant("CONST_NAME");
if ($value != null)
{
// Use the value ...
}
Since you passed the const name as a string, it wont generate an error on the code editor.
I'm currently programming a website (in PHP4). I plan to save values, which do not change during runtime, in constants. Those are for example the version number of login-data for the database.
Question 1: are there any (security relevant) problems that can arise from saving data in constants?
At the moment I do the following to define and call the constant:
define("VERSION", "1.0");
echo "Current version: ".VERSION."."; // Result: "Current version: 1.0."
There is one thing that annoys me: In case a constant is not defined, the "wrong" variable name is returned instead of e.g. NULL.
define("VERSION", "1.0");
echo "Current version: ".VERSIONXXX."."; // Result: "Current version: VERSIONXXX."
One solution I found to get an error message and the return value "NULL" when I accidently entered a wrong constant name is using the function constant():
define("VERSION", "1.0");
echo "Current version: ".constant("VERSIONXXX")."."; // Result: "Current version: ."
Question 2: Can I prevent in a different way, that PHP returns the name of the non-existing variable?
Question 3: Should the value of a constant in PHP always be returned using the function constant()?
If you attempt to use a constant that does not exist, PHP automagically assumes it is a string instead, which is why you see VERSIONXXX.
IIRC it throws a warning if you're error reporting is at the appropriate level. The best solution here is to ensure your code utilizes the proper constant names.
If you know the name of the constant, it's easiest/best to use it directly. echo MY_CONSTANT
If you don't know the name of the constant (e.g. it's name is in a variable), use constant():
$name = 'MY_CONSTANT';
echo constant($name);
In reverse Order:
Question 3: No
Question 2: Not really, but you can make adjustments.
because of (Question 1:) error_reporting. You PHP webserver is configured hide some errors. If you add
error_reporting(E_ALL);
to your scripts head, you will get a
Use of undefined constant MY_CONST - assumed 'MY_CONST'
Error. Unfortunately it's a problem coming out of PHP's long history, that constants can be interpreted as strings.
If you can not be shure a constant was set in the first place you can use defined
if(defined('MY_CONSTANT') {
//do something
}
But my personal opinion there shouldn't be many cases to need this, since the word constant alone implies a garanteed presence. The only exception I can think of is the typical header test.
if(!defined('MY_APP_IS_PRESENT')) {
die('You can not call this file on its own, please use index.php.');
}
And one last tipp: Go and make yourself a errorhandler function, maybe even with firephp?
Well, you could always use defined function to make sure the constant exists. Combined with a ternary statement, you could simply echo an empty string, something like:
echo defined( VERSION ) ? VERSION : "";
Not the best answer, but workable?
PHP manual for defined() is at http://php.net/manual/en/function.defined.php
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
}
func(CONST_A) should return 'CONST_A', func($name) should return $name
How to implement this func in PHP?
This doesn't seem possible easily.
You can use reflection to determine the parameters of the function, but that returns the variable names that the function expects, and if you're already inside the function, you kind of already know those.
debug_backtrace is the usual way of peeking at what called you, but it returns the values of the passed arguments, not the variable names or constants that the caller used when making the call.
However, what it does give you is the file name and line number of the caller, so you could open up the file and seek to that line and parse it out, but that would be very silly and you should not do this. I am not going to give you example code for this, as it is so utterly silly that you should not consider doing it ever.
The get_defined_vars thing is a hack and is not guaranteed to work either, and definitely won't work for constants, as get_defined_constants does that.
Try this:
<?php
function getVarConst($var)
{
if (isset($GLOBALS[$var]) // check if there is a variable by the name of $var
{
return $GLOBALS[$var]; // return the variable, as it exists
}
else if (defined($var)) // the variable didn't exist, check if there's a constant called $var
{
return constant($var); // return the constant, as it exists
}
else
{
return false; // return false, as neither a constant nor a variable by the name of $var exists
}
}
?>
This isn't possible.
You literally want the following right?
define('CONST_A', 'THIS COULD BE ANYTHING');
$name = 'who cares';
func(CONST_A); //returns 'CONST_A'
func($name); //returns '$name'
The function can't know that.
I suppose that reading the source code like Charles describes could get you this, but why?