How to check if a defined constant exists in PHP? - php

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.

Related

PHP Arrow operator - how do I assign a variable

I'm trying to pass a variable into an operator instead of having it be fixed
$client ->setDeveloperKey('a very long hexadecimal string');
This is how the script is written to work and it works - some value is a very long hex code...
The script I'm writing takes the developer key from an input i.e. $value='some value' is already defined BEFORE the statement.
Instead of being fixed, I'd like to assign $value into the setDeveloperKey operator - its coming in as a function i.e.
callGoogle ($query,$devkey)
where callGoogle is the function. However when I try
$client ->setDeveloperKey($devkey);
the script doesn't work...in other words its the wrong syntax to assign my developer key (string) to the operator.
Nor does
$client ->setDeveloperKey = $devkey;
What is the correct PHP syntax to assign the $value variable to the $client - > setDeveloperKey operator?
First check the type of your $value and also check if that class method accept that value type. From what I can see its a Google_Client API and that method accepts Strings
If this works:
$obj->method('test');
Then this works too:
$value = 'test';
$obj->method($value);
You must be messing somewhere else.
Well what type of object is $client? You have to define your own class, and create a function called setDeveloperKey, or this is a pre existing class / function, the syntax would be $client->setDeveloperKey('foo');
The original class should look something like this:
class Client {
protected $DeveloperKey;
public function setDeveloperKey($Key) {
$this->DeveloperKey = $Key;
}
}

When and how to use Constants in PHP?

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

A PHP variable with parentheses?

I don't understand this code:
$outputFunction($dst, $resized, $quality);
It's not a function e.g myfunction()
It's not a variable e.g $variable = $variable2
What is it?
The code works in the script i have downloaded, i just can't figure out how that piece of code can work...maybe i'm just tired or something..
Thanks.
$outputFunction holds the name of the function. Thus, if $outputFunction holds the value "calculate", then calculate($dst, $resized, $quality) is invoked.
To add to sbrattla's answer, you can also define anonymous functions in PHP 5.3 (I think), so
$var = function($a) { /* do something */ return $b; }
echo $var(123);
These are variable functions.
$outputFunction is evaluated to obtain the name of the function to which the operands will be applied.
There's an entire page dedicated to this topic in the PHP manual.
in php you can do something like
$outputFunction = 'myFunction';
$outputFunction(args);
and it works calling the function normally
variable functions
The string should initialized some lines before. You can consider this as a pointer of funcrion which allows to change the executed method.
Php will recognize your syntax and will launch the function named in your string (computed one if you want)

constant already defined in php

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.

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
}

Categories