Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the home directory from a PHP CLI script?

Tags:

php

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(~/); ?> 
like image 781
Andrew Avatar asked Dec 12 '09 22:12

Andrew


People also ask

Where can I find home directory?

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.

What is __ DIR __ in PHP?

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.

How do you go up a directory in PHP?

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.


2 Answers

You can fetch the value of $HOME from the environment:

<?php     $home = getenv("HOME"); ?> 
like image 40
EJ Campbell Avatar answered Sep 19 '22 06:09

EJ Campbell


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 ;)

Windows Compatibility

Note that $_SERVER['HOME'] is not available on Windows. Instead, the variable is split into $_SERVER['HOMEDRIVE'] and $_SERVER['HOMEPATH'].

like image 53
Felix Kling Avatar answered Sep 21 '22 06:09

Felix Kling