From the command line, I can get the home directory like this:
~/
How can I get the home directory inside my PHP CLI script?
#!/usr/bin/php <?php echo realpath(~/); ?>
Starting with Windows Vista, the Windows home directory is \user\username. In prior Windows versions, it was \Documents and Settings\username. In the Mac, the home directory is /users/username, and in most Linux/Unix systems, it is /home/username.
The __DIR__ can be used to obtain the current code working directory. It has been introduced in PHP beginning from version 5.3. It is similar to using dirname(__FILE__). Usually, it is used to include other files that is present in an included file.
If you are using PHP 7.0 and above then the best way to navigate from your current directory or file path is to use dirname(). This function will return the parent directory of whatever path we pass to it.
You can fetch the value of $HOME from the environment:
<?php $home = getenv("HOME"); ?>
Use $_SERVER['HOME']
Edit:
To make it complete, see what print_r($_SERVER)
gave me, executed from the command line:
Array ( [TERM_PROGRAM] => Apple_Terminal [TERM] => xterm-color [SHELL] => /bin/bash [TMPDIR] => /var/folders/Lb/LbowO2ALEX4JTK2MXxLGd++++TI/-Tmp-/ [TERM_PROGRAM_VERSION] => 272 [USER] => felix [COMMAND_MODE] => unix2003 [__CF_USER_TEXT_ENCODING] => 0x1F5:0:0 [PATH] =>/Library/Frameworks/Python.framework/Versions/Current/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/texbin:/usr/X11/bin [PWD] => /Users/felix/Desktop [LANG] => de_DE.UTF-8 [SHLVL] => 1 [HOME] => /Users/felix [LOGNAME] => felix [DISPLAY] => /tmp/launch-XIM6c8/:0 [_] => ./test_php2 [OLDPWD] => /Users/felix [PHP_SELF] => ./test_php2 [SCRIPT_NAME] => ./test_php2 [SCRIPT_FILENAME] => ./test_php2 [PATH_TRANSLATED] => ./test_php2 [DOCUMENT_ROOT] => [REQUEST_TIME] => 1260658268 [argv] => Array ( [0] => ./test_php2 ) [argc] => 1 )
I hope I don't expose relevant security information ;)
Note that $_SERVER['HOME']
is not available on Windows. Instead, the variable is split into $_SERVER['HOMEDRIVE']
and $_SERVER['HOMEPATH']
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With