I have a file system structure with symlinks, something like this:
folder123
index.php
config.php -> symlink to shared/config.php
shared
config.php
I run index.php on command line, index.php includes config.php, which is symlink to a file in some other folder.
How can I know index.php file path from the config.php script? The required result is "folder123" (well the full path of it), not "shared". So, I cannot use __FILE__.
This works on scripts, ran by browser (at least in my case, it is the same as folder123 - the base dir):
$_SERVER['DOCUMENT_ROOT']
I need something for the command-line too.
It looks like
$_SERVER['PWD']
is something what I need, but it's not documented, so I don't find it a reliable way. Also, you need to combile it with SCRIPT_FILENAME to get the required results - PWD shows directory, from which the script was run, not it's full path.
getcwd looks promising, but it can be changed by chdir - I'll use that if I don't find some better alternative.
There are two variables you can use while writing command line applications with PHP: $argc and $argv. The first is the number of arguments plus one (the name of the script running). The second is an array containing the arguments, starting with the script name as number zero ($argv[0]).
The CLI SAPI provides an interactive shell using the -a option if PHP is compiled with the --with-readline option. As of PHP 7.1. 0 the interactive shell is also available on Windows, if the readline extension is enabled. Using the interactive shell you are able to type PHP code and have it executed directly.
I'm not sure if there is a way to determine what file included a file, but you can get the name of the running program (index.php
in this case) with $argv[0]
, or possibly $_SERVER['argv'][0]
if the former is not available.
//config.php
//running path
$path = dirname(realpath($argv[0]));
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