0

When adding the line:

#!/usr/bin/env drush

to the top of a PHP script to automatically run using drush, the variable __DIR__ and __FILE__ stop returning my script file name and directory and return drush paths instead.

Is there another variable that should be used in case of drush scripts to get the script path and dir?

Note: When I remove that line and use drush scr <myscript> instead, __DIR__ and __FILE__ return the correct paths.

[EDIT]

To test the suggestions below in the answer by Hasan Bayat:

I ran the following script:

<?php
print('__DIR__ value is: '.__DIR__."\n");
print('__FILE__ value is: '.__FILE__."\n");
print('SCRIPT_FILENAME is: '.$_SERVER['SCRIPT_FILENAME']."\n");
print('PATH_TRANSLATED is: '.$_SERVER['PATH_TRANSLATED']."\n");
print('from backtrace: '.debug_backtrace()[count(debug_backtrace()) - 1]['file']."\n");
print('included_files: '.get_included_files()[0]."\n");

Using the command line:

drush scr script.php

And the results are as following

__DIR__ value is: /path/to/my/script
__FILE__ value is: /path/to/my/script/script.php
SCRIPT_FILENAME is: /path/to/current/dir/index.php
PATH_TRANSLATED is: /usr/local/bin/drush
from backtrace: /usr/local/bin/drush
included_files: /usr/local/bin/drush

I then changed the script to add the line #!/usr/bin/env drush at the top. And reran the script this time with the command:

./script.php

Now the results are as following:

__DIR__ value is: phar:///usr/local/bin/drush/commands/core
__FILE__ value is: phar:///usr/local/bin/drush/commands/core/core.drush.inc(1194) : eval()'d code
SCRIPT_FILENAME is: /path/to/current/dir/index.php
PATH_TRANSLATED is: /usr/local/bin/drush
from backtrace: /usr/local/bin/drush
included_files: /usr/local/bin/drush

So apparently none of the suggested solutions works in case the drush first line is added to the script.

Bishoy
  • 705
  • 9
  • 24

1 Answers1

0

There are several ways but here is two:

  1. Using $_SERVER Global Variable: Check your $_SERVER["SCRIPT_FILENAME"] has exists and points to the current file, then if it not works use $_SERVER["PATH_TRANSLATED"] it might works.
  2. If the $_SERVER variable not works use the below code:
$stack = debug_backtrace();
$firstFrame = $stack[count($stack) - 1];
$initialFile = $firstFrame['file'];

if none of them works use getcwd(); to get current working directory and follow it by your file name.

EDIT: The third way is to using get_included_files(), if you don't have any included files previously your current file should be:

$included_files = get_included_files();
echo $included_files[0]; // Outputs current script path
Hasan Bayat
  • 926
  • 1
  • 13
  • 24