Home > Mobile >  Get the value of a constant in a file
Get the value of a constant in a file

Time:04-05

$file = $_SERVER["DOCUMENT_ROOT"]."/log.txt";

$current = file_get_contents($file);

There is a constant TEST in the file, how do I get its value?

define("TEST", "Hello you.", true);

CodePudding user response:

If your PHP file contains a constant declared above the code you posted then just use the constant with it's name:

define("TEST", "Hello you.", true);

$file = $_SERVER['DOCUMENT_ROOT'].'/log.txt';

$file_content = file_get_contents($file);

// To access a constant just type it's name:
echo TEST;

If your TEST constant is declared in log.txt then it's different.

log.txt:

ASDLFJS SDFWQERSDF sadf sdfwer
asdflkwer
define("TEST", 'This is the content');
another log line

You'll need to write a regular expression to get the define() declaration, as it may contain a string, a number or whatever. I would use this regex: /define\((["'])TEST\1[^\n\r]*\)\s*;/

Test and explanation of the regex: https://regex101.com/r/RoC7dP/2

Once the define() declaration is extracted, you could execute it with eval() in order to have the constant available. Doing a require() or include() doesn't seem to be the solution as your file is called log.txt, letting me think that it's not a PHP file.

Back to the PHP code:

$file = $_SERVER['DOCUMENT_ROOT'].'/log.txt';

$file_content = file_get_contents($file);

$regex = '/define\((["\'])TEST\1[^\n\r]*\)\s*;/';

if (preg_match($regex, $file_content, $matches)) {
    // This could cause an error.
    // The 3rd argument of define() isn't always accepted.
    eval($matches[0]);
    echo TEST;
} else {
    die('Could not find the TEST declaration!');
}

Example of execution here (without a file but just a string because we cannot do it on online compilers): https://sandbox.onlinephpfunctions.com/c/e768f

CodePudding user response:

Use the include or require functions

The file has the .txt extension, but that doesn't matter if it is still PHP code. Some frameworks use .inc and other extensions. The file must have <?php at the beginning or <? if short php tags are allowed.

You can load files as PHP code with the include or require functions:

  • include()
    Include file (interpret as PHP code) into the current script
  • include_once()
    Interprets the file, but that exact file will only be included once if you include that file again. Including the file again will not throw an error.
  • require()
    Require will throw an error if the file does not exist
  • require_once()
    Recommended for this: Throws an error if the file does not exist, will not load that file again if required again. Requiring that file again will not throw an error.

You probably want to keep that define around for as long as the script runs, so require_once() is most likely the correct choice for you.

You use the constant as you would by just typing its name: TEST.
So for example var_dump(TEST);.

  •  Tags:  
  • php
  • Related