-1

The following examples don't work in php -

$data = file_get_contents('~/Documents/someFile.txt');

//no such file or directory

$data = file_get_contents('$HOME/Documents/someFile.txt');

// no such file or directory

What's the reason why this doesn't work?

jstyles85
  • 61
  • 4

3 Answers3

1

The expansion of ~ and $HOME is done by your shell, not by PHP. Depending on your config, you can probably use:

$data = file_get_contents($_SERVER['HOME'] . '/Documents/someFile.txt');
Alex Howansky
  • 50,515
  • 8
  • 78
  • 98
1

Use getenv('HOME') or $_SERVER['HOME']. You cannot use $HOME in single quotes because its literal will be used, and ~ isn't known by php.

Alex Barker
  • 4,316
  • 4
  • 28
  • 47
  • Thanks. that works. I was purposefully trying to use it in single quote as its not a PHP variable. I thought it would work as string in command line. Clearly, I need more research into using php in the cli. – jstyles85 Oct 31 '17 at 19:42
0
$data = file_get_contents('$HOME/Documents/someFile.txt');

has two problems:

  1. You never set the variable $HOME. HOME is an environment variable, but they don't automatically become PHP variables like they do in the shell.

  2. Variables aren't expanded inside single quotes, see What is the difference between single-quoted and double-quoted strings in PHP? (not coincidentally, this is the same as the shell).

You can do:

$HOME = getenv('HOME');
$data = file_get_contents("$HOME/Documents/someFile.txt");
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Yes, i'm aware of the differences between single/double quotes in both php and bash. I didn't however realize I had to pass the $HOME environment variable to PHP. My thought was to simply pass the path to file_get_contents as string as I would normally navigate in cli. – jstyles85 Oct 31 '17 at 21:19
  • But in the CLI `$HOME` is a variable that has to be replaced with its value. – Barmar Oct 31 '17 at 21:20