Server home directory php

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

From the command line, I can get the home directory like this:

How can I get the home directory inside my PHP CLI script?

Php Solutions

Solution 1 — Php

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 😉

Читайте также:  Types of css layouts
Windows Compatibility

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

Solution 2 — Php

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

Solution 3 — Php

PHP allows you to get the home dir of any of the OS users. There are 2 ways.

First of all you gotta figure out the OS User ID and store it somewhere ( database or a config file for instance).

// Obviously this gotta be ran by the user which the home dir // folder is needed. $uid = posix_getuid(); 

This code bit can be ran by any OS user, even the usual webserver www-data user, as long as you pass the correct target user ID previously collected.

$shell_user = posix_getpwuid($uid); print_r($shell_user); // will show an array and key 'dir' is the home dir // not owner of running script process but script file owner $home_dir = posix_getpwuid(getmyuid())['dir']; var_dump($home_dir); 

Same logic from posix_getpwuid(). Here you gotta pass the target OS username instead of their uid.

$shell_user = posix_getpwnam('johndoe'); print_r($shell_user); // will show an array and key 'dir' is the home dir // not owner of running script process but script file owner $home_dir = posix_getpwnam(get_current_user())['dir']; var_dump($home_dir); 

Solution 4 — Php

This function is taken from the Drush project.

/** * Return the user's home directory. */ function drush_server_home( ) < // Cannot use $_SERVER superglobal since that's empty during UnitUnishTestCase // getenv('HOME') isn't set on Windows and generates a Notice. $home = getenv('HOME'); if (!empty($home)) < // home should never end with a trailing slash. $home = rtrim($home, '/'); > elseif (!empty($_SERVER['HOMEDRIVE']) && !empty($_SERVER['HOMEPATH'])) < // home on windows $home = $_SERVER['HOMEDRIVE'] . $_SERVER['HOMEPATH']; // If HOMEPATH is a root directory the path can end with a slash. Make sure // that doesn't happen. $home = rtrim($home, '\\/'); > return empty($home) ? NULL : $home; > 

Solution 5 — Php

If for any reason getenv(‘HOME’) isn’t working, or the server OS is Windows, you can use exec(«echo ~») or exec(«echo %userprofile%») to get the user directory. Of course the exec function has to be available (some hosting companies disable that kind of functions for security reasons, but that is more unlikely to happen).

Here is a [tag:php] function that will try $_SERVER , getenv and finally check if the exec function exists and use the appropriate system command to get the user directory:

function homeDir( ) < if(isset($_SERVER['HOME'])) < $result = $_SERVER['HOME']; > else < $result = getenv("HOME"); > if(empty($result) && function_exists('exec')) < if(strncasecmp(PHP_OS, 'WIN', 3) === 0) < $result = exec("echo %userprofile%"); > else < $result = exec("echo ~"); > > return $result; > 

Solution 6 — Php

Depends on where you are and what you’re trying to do.

$_SERVER is completely unreliable for a non-server script, BUT $_ENV[‘HOME’] might be better for a standard shell script. You can always print_r( $GLOBALS ) and see what your environment gives you to play with. phpinfo() also spits out plaintxt when called from a CLI script, and just good ole php -i executed from a shell will do the same.

Solution 7 — Php

This works for me both LINUX and WINDOWS:

function get_home_path( ) < $p1 = $_SERVER['HOME'] ?? null; // linux path $p2 = $_SERVER['HOMEDRIVE'] ?? null; // win disk $p3 = $_SERVER['HOMEPATH'] ?? null; // win path return $p1.$p2.$p3; > 

Solution 8 — Php

This is the method i used in a recent project:

I saved it into my object by doing this:

$this->write_Path = exec('echo $HOME'); 

But you could really save it any way you want and use it anyway you see fit.

Solution 9 — Php

You can rely on «home» directory when working with web server. Working CLI it will give the user path (in windows) if you want your script to work in web and cli environments I’ve found better to go up any levels with dirname until your root(home) directory.

echo dirname(__DIR__).PHP_EOL; // one level up echo dirname(dirname(__DIR__)); //two levels up echo dirname(__DIR__,2).PHP_EOL; //two levels only php >7.0 

Solution 10 — Php

I know that this is an old question, but if you are looking for an alternative and easy to replicate method across your application, you may consider using a library installed via composer. I’ve written a library that combine some of the answer here and make it a library and I’ll shamelessly promote it here : juliardi/homedir.

You can install it via composer :

$ composer require juliardi/homedir 

And then use it in your application :

 require_once('vendor/autoload.php'); $userHomeDir = get_home_directory(); 

Hope this answer help you.

Solution 11 — Php

$_SERVER[‘HOME’] and getenv(‘home’) did not work for me.

However, on PHP 5.5+, this worked to give the home directory that the file is located in:

Solution 12 — Php

Try $_SERVER[‘DOCUMENT_ROOT’] as your home directory.

Solution 13 — Php

Источник

Php how to get the server directory php

Eg: In your you need to use functions in , so you use : : That way when common.php is in , the call of in will correctly includes in instead of trying to look in current directory where is run. Finally, we can use the magic constants in the function to get the name of the current directory.

PHP Get name of current directory

You can use basename() to get the trailing part of the path 🙂

In your case, I’d say you are most likely looking to use getcwd() , dirname(__FILE__) is more useful when you have a file that needs to include another library and is included in another library.

main.php libs/common.php libs/images/editor.php 

In your common.php you need to use functions in editor.php , so you use

require_once dirname(__FILE__) . '/images/editor.php'; 
require_once libs/common.php 

That way when common.php is require’d in main.php , the call of require_once in common.php will correctly includes editor.php in images/editor.php instead of trying to look in current directory where main.php is run.

To get only the name of the directory where script executed:

//Path to script: /data/html/cars/index.php echo basename(dirname(__FILE__)); //"cars" 

You can use dirname(__FILE__) to get the path to the directory of the current file.

// use dirname to get the directory of the current file $path = dirname(__FILE__); // $path here is now /path_to/your_dir // split directory into array of pieces $pieces = explode(DIRECTORY_SEPARATOR, $path); // $pieces = ['path_to', 'your_dir'] // get the last piece echo $pieces[count($pieces) - 1]; // result is: your_dir 

PHP display current server path, To get your current working directory: getcwd() (documentation) · To get the document root directory: $_SERVER[‘DOCUMENT_ROOT’] (documentation)

Determining & using your server relative path for includes

Using a PHP directory variable to display the server path to the current website so it can be
Duration: 3:18

Get folder up one level

. but in a web server environment you will probably find that you are already working from current file’s working directory, so you can probably just use:

. to reference the directory above. You can replace __DIR__ with dirname(__FILE__) before PHP 5.3.0.

You should also be aware what __DIR__ and __FILE__ refers to:

The full path and filename of the file. If used inside an include, the name of the included file is returned.

So it may not always point to where you want it to.

echo realpath(__DIR__ . DIRECTORY_SEPARATOR . '..'); 

But note the __DIR__ constant was added in PHP 5.3.0.

How to get root directory folder name in php instead of path, try this, $projectFolderName = explode(‘/’, $_SERVER[‘PHP_SELF’])[1];. the $_SERVER[‘PHP_SELF’] returns path to current file relative to

Get Current Directory Name and Path in PHP

This article will introduce a few methods to get the current working directory name in PHP.

Use the getcwd() Function to Get the Current Directory Name in PHP

The getcwd() function gives the current working directory. The returned value is a string on success.

The function does not take any parameters. The function returns false in case of failure.

Let’s consider the following directory structure.

├── var │ └── www │ └── html | └──project | └──index.php 

The PHP file lies inside the project directory. The getcwd() function will return the name of the current working directory, which is project .

We can use the echo function to display the content of the function. We can see in the output section that the getcwd() function returns the current working directory with its path.

Use the dirname() Function to Get the Current Directory Name in PHP

We can also use the dirname() function to get the current directory name in PHP. The function returns the path of the parent directory.

It accepts two parameters where the first one is the path and the second one is levels. Levels indicate the number of directories to move up.

Finally, we can use the __FILE__ magic constants in the dirname() function to get the name of the current directory. The __FILE__ constant returns the full path of the current file along with the file name.

We can demonstrate these constants and the function in the above directory structure. For example, we get the following result when we echo the __FILE__ constant from the index.php file.

/var/www/html/project/index.php 

For example, write the dirname() function in the index.php file with the __FILE__ constant as the parameter.

In this way, we can get the current working directory name in PHP.

Use the basename() Function to Get the Current Directory Name in PHP

We can use the basename() function to get the current working directory name without the path in PHP. We can apply this function with the result of the above two functions.

The basename() function returns the name of the base file or folder from the given path. For example, if the path provided is /var/www/html/project , the output will be project .

For example, use the functions dirname(__FILE__) and getcwd() as the parameters for the basename() function. In this way, we can get the current working directory name in PHP.

echo basename(dirname(__FILE__))."
"; echo basename(getcwd())."\n";

PHP File

PHP built in server, any way to configure it to show files of directory?, php -S localhost:8080 -t . script.php Script.php:

Get the server path /home directory from php wamp windows

Use it this way, First define a path SITE_PATH as you know which file to call which is here folder3/folder4/file2.php . if you are using MVC kind of framework then define SITE_PATH as very top most of file, so that in future if you change the base location of you project then you can change it in one variable then it will good to go.

Get folder up one level, to reference the directory above. You can replace __DIR__ with dirname(__FILE__) before PHP 5.3.0. You should also be aware what __

Источник

Оцените статью