tags:

views:

184

answers:

5

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(~/);
?>
+1  A: 

Use $_SERVER['DOCUMENT_ROOT'].

Steven
This is empty if you run the script from the command line, I just tried it.
Felix Kling
As did I... the $_SERVER array is different from the command line than it normally is
jnunn
A: 

Use $_SERVER['PWD'];

jnunn
This gives the directory from where the script is executed (note: not located).
Felix Kling
A: 
dirname(__DIR__);
streetparade
+3  A: 

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

Felix Kling
+1 it's amazing how many people gave the same plainly wrong answer to this simple question.
Lo'oris
A: 

Is using a shell an option?

echo shell_exec('pwd');
erenon