0

Every example I find for file_get_contents and FILE_USE_INCLUDE_PATH show the file name as a text string inside quotes. I see that the dot concatenation is used (I'm presuming to concatenate the PATH and the actual file name) and when I follow that method, my code works. However, I need to create a variable for the file name and when I do PHP stops.

I have set_include_path( PATH ); and I see the desired folder WITHOUT a forward slash (/).

I have tried both with and without a forward slash in front of the file name when I assign it to the variable ($var_ame = "file.dat";) and ($var_ame = "/file.dat";) with no difference.

This works: $expected_var = file_get_contents('./file.dat', FILE_USE_INCLUDE_PATH);

This DOES NOT: $expected_var = file_get_contents($var_name, FILE_USE_INCLUDE_PATH);

I have tried a dot in front of the variable knowing that I need to concatenate somehow but that stops PHP as well.

What am I missing here?

ND_Coder
  • 127
  • 7
  • 1
    When you say "PHP stops", do you mean [Nothing is seen. The page is empty and white.](https://stackoverflow.com/questions/12769982/reference-what-does-this-error-mean-in-php/12772851#12772851)? – IMSoP Jul 16 '22 at 23:10
  • Yes. That is it exactly. I use Console to debug Javascript/HTML but I have yet to learn how to debug PHP scripts. Next on the learning list ... – ND_Coder Jul 17 '22 at 15:30

1 Answers1

1

The dot in file_get_contents('./file.dat', FILE_USE_INCLUDE_PATH); is not a string concatenation operator, it's an actual dot inside the string. If you want that same string in a variable, you want to include that dot: $filename = './file.dat';

Meanwhile, the fact that the dot is there means that FILE_USE_INCLUDE_PATH is irrelevant, because . is the special name for "the current directory", so './file.date' means "a file called 'file.dat' in the current directory", and won't search any other directory.

What "the current directory" means in a running PHP script is not always obvious, so as a general good practice, I would suggest not relying on it, or on the configured path, and always using an absolute path. The magic constant __DIR__ expands to whatever directory the current PHP file is placed in, which can be useful for constructing such a path.

IMSoP
  • 89,526
  • 13
  • 117
  • 169
  • That was it! Thank you for taking the time to provide such a detailed response. I played with each of the variations you described to study the difference and I see what you mean. And, thank you, also, for the advice on what to "rely" on and what could be problematic. Awesome! Much appreciated. – ND_Coder Jul 17 '22 at 15:33