Obtener ruta absoluta del script actual


He buscado alto y bajo y obtener una gran cantidad de diferentes soluciones y variables que contienen información para obtener la ruta absoluta. Pero parecen funcionar bajo algunas condiciones y no bajo otras. ¿Hay una forma de bala de plata para obtener la ruta absoluta del script ejecutado en PHP? Para mí, el script se ejecutará desde la línea de comandos, pero, una solución debería funcionar igual de bien si se ejecuta dentro de Apache, etc.

Aclaración: El script inicialmente ejecutado, no necesariamente el archivo donde se codifica la solución.

Author: kbulgrien, 2011-01-10

16 answers

La solución correcta es utilizar el get_included_files función:

list($scriptPath) = get_included_files();

Esto le dará la ruta absoluta del script inicial incluso si:

  • Esta función se coloca dentro de un archivo incluido
  • El directorio de trabajo actual es diferente del directorio del script inicial
  • El script se ejecuta con la CLI, como una ruta relativa

Aquí hay dos scripts de prueba; el script principal y un archivo incluido:

# C:\Users\Redacted\Desktop\main.php
include __DIR__ . DIRECTORY_SEPARATOR . 'include.php';
echoScriptPath();

# C:\Users\Redacted\Desktop\include.php
function echoScriptPath() {
    list($scriptPath) = get_included_files();
    echo 'The script being executed is ' . $scriptPath;
}

Y el resultado; observe el directorio actual:

C:\>php C:\Users\Redacted\Desktop\main.php
The script being executed is C:\Users\Redacted\Desktop\main.php
 10
Author: Salman A,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-01 11:39:59

__FILE__ constante le dará ruta absoluta al archivo actual.

Actualización :

La pregunta se cambió para preguntar cómo recuperar el script ejecutado inicialmente en lugar del script en ejecución. El único (??) confiable manera de hacer eso es utilizar el debug_backtrace función.

$stack = debug_backtrace();
$firstFrame = $stack[count($stack) - 1];
$initialFile = $firstFrame['file'];
 256
Author: zerkms,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-15 15:36:59
echo realpath(dirname(__FILE__));

Si coloca esto en un archivo incluido, imprime la ruta de acceso a este include. Para obtener la ruta del script padre, reemplace __FILE__ por $_SERVER['PHP_SELF']. Pero tenga en cuenta que PHP_SELF es un riesgo de seguridad!

 229
Author: rik,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-01-10 09:14:05

Ejemplos para: https://(www.)example.com/subFolder/yourfile.php?var=blabla#555

Códigos típicos de PHP:

//parse_url
$x = parse_url($url);
$x['scheme']                https
$x['host']                        example.com
$x['path']                                   /subFolder/yourfile.php
$x['query']                                                          var=blabla
$x['fragment']                                                                  555 // hashtag outputed only in case, when hashtag-containing string was manually passed to function, otherwise PHP is unable to recognise hashtags in $_SERVER

//pathinfo (If you will ever use this function, I only recommend to pass `parse_url`s output as argument)
A = pathinfo($url);
B = pathinfo(parse_url($url)['path']);
A['dirname']                https://example.com/subFolder
B['dirname']                                   /subFolder
A['basename']                                             yourfile.php?var=blabla#555
B['basename']                                             yourfile.php
A['extension']                                                     php?var=blabla#555
B['extension']                                                     php
A['filename']                                             yourfile
B['filename']                                             yourfile


//=================================================== 
//========== self-defined SERVER variables ========== 
//=================================================== 
$_SERVER["DOCUMENT_ROOT"]   /home/user/public_html
$_SERVER["SERVER_ADDR"]     143.34.112.23
$_SERVER["SERVER_PORT"]     80(or 443 etc..)
$_SERVER["REQUEST_SCHEME"]  https                            //like: $_SERVER["SERVER_PROTOCOL"] 
$_SERVER['HTTP_HOST']             example.com                //like: $_SERVER["SERVER_NAME"]
$_SERVER["REQUEST_URI"]                           /subFolder/yourfile.php?var=blabla
$_SERVER["QUERY_STRING"]                                                  var=blabla
__FILE__                    /home/user/public_html/subFolder/yourfile.php
__DIR__                     /home/user/public_html/subFolder      //like: dirname(__FILE__)
$_SERVER["REQUEST_URI"]                           /subFolder/yourfile.php?var=blabla
parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH)  /subFolder/yourfile.php 
$_SERVER["PHP_SELF"]                              /subFolder/yourfile.php

// ==================================================================
//if "YOURFILE.php" is included in "PARENTFILE.php" , and you visit  "PARENTFILE.PHP?abc":
$_SERVER["SCRIPT_FILENAME"] /home/user/public_html/parentfile.php
$_SERVER["PHP_SELF"]                              /parentfile.php
$_SERVER["REQUEST_URI"]                           /parentfile.php?abc
__FILE__                    /home/user/public_html/subFolder/yourfile.php

// ===================================================
// ================= handy variables =================
// ===================================================
//If site uses HTTPS:
$HTTP_or_HTTPS = ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS']!=='off') || $_SERVER['SERVER_PORT']==443) ? 'https://':'http://' );            //in some cases, you need to add this condition too: if ('https'==$_SERVER['HTTP_X_FORWARDED_PROTO'])  ...

//To trim values to filename, i.e. 
basename($url)              yourfile.php

//excellent solution to find origin
$debug_files = debug_backtrace();       $initial_called_file = count($debug_files) ? $debug_files[count($debug_files) - 1]['file'] : __FILE__;

¡Aviso!:

  • hashtag (#...) Las partes de URL no pueden ser detectadas desde PHP (lado del servidor). Para ello, utilice JavaScript.
  • DIRECTORY_SEPARATOR devuelve \ para el alojamiento de tipo Windows, en lugar de /.



Para WordPress

//(let's say, if wordpress is installed in subdirectory:  http://example.com/wpdir/)
home_url()                       http://example.com/wpdir/        //if is_ssl() is true, then it will be "https"
get_stylesheet_directory_uri()   http://example.com/wpdir/wp-content/themes/THEME_NAME  [same: get_bloginfo('template_url') ]
get_stylesheet_directory()       /home/user/public_html/wpdir/wp-content/themes/THEME_NAME
plugin_dir_url(__FILE__)         http://example.com/wpdir/wp-content/themes/PLUGIN_NAME
plugin_dir_path(__FILE__)        /home/user/public_html/wpdir/wp-content/plugins/PLUGIN_NAME/  
 226
Author: T.Todua,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-15 15:46:56
__DIR__

De el manual:

El directorio del archivo. Si se usa dentro de un include, se devuelve el directorio del archivo incluido. Esto equivale a dirname(__FILE__). Este nombre de directorio no tiene una barra diagonal final a menos que sea el directorio raíz.
__FILE__ siempre contiene una ruta absoluta con enlaces simbólicos resueltos, mientras que en versiones anteriores (que 4.0.2) contenía una ruta relativa en algunas circunstancias.

Nota: __DIR__ fue añadido en PHP 5.3.0.

 33
Author: Gottlieb Notschnabel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-17 01:24:56

Si desea obtener el directorio de trabajo actual use getcwd()

Http://php.net/manual/en/function.getcwd.php

__FILE__ devolverá la ruta con nombre de archivo, por ejemplo, en XAMPP C:\xampp\htdocs\index.php en lugar de C:\xampp\htdocs\

 18
Author: pkarecki,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-10-06 03:20:26
dirname(__FILE__) 

Dará la ruta absoluta del archivo actual desde el que está exigiendo la ruta, la ruta de su directorio de servidor.

Archivos de ejemplo:

Www/http/html/index.php; si coloca este código dentro de su índice.php volverá:

<?php echo dirname(__FILE__); // this will return: www/http/html/

Www/http/html/class/myclass.php; si coloca este código dentro de su myclass.php volverá:

<?php echo dirname(__FILE__); // this will return: www/http/html/class/

 10
Author: Sultanos,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-10-01 10:47:54

Solo use a continuación:

echo __DIR__;
 8
Author: Matricore,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-11-05 12:40:54

Si estás buscando la ruta absoluta relativa a la raíz del servidor, he encontrado que esto funciona bien:

$_SERVER['DOCUMENT_ROOT'] . dirname($_SERVER['SCRIPT_NAME'])
 7
Author: SiteKickr,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-08-20 00:18:31
`realpath(dirname(__FILE__))` 

Te da el directorio actual del script(el script dentro del cual colocaste este código) sin barra diagonal final. esto es importante si desea incluir otros archivos con el resultado

 6
Author: minhajul,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-02-25 14:44:33

En caso de usar framework, la mayoría de ellos no funciona, así que he encontrado la solución para eso. Código:

echo dirname(__FILE__).'\\'.basename(__FILE__);

Debe dar la ruta absoluta, incluyendo el nombre del archivo.

 6
Author: user7364363,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-02 08:06:47

Aquí hay una función PHP útil que escribí para esto precisamente. Como aclara la pregunta original, devuelve el camino desde el cual el inicial script fue ejecutado-no el archivo en el que estamos actualmente.

/**
 * Get the file path/dir from which a script/function was initially executed
 * 
 * @param bool $include_filename include/exclude filename in the return string
 * @return string
 */ 
function get_function_origin_path($include_filename = true) {
    $bt = debug_backtrace();
    array_shift($bt);
    if ( array_key_exists(0, $bt) && array_key_exists('file', $bt[0]) ) {
        $file_path = $bt[0]['file'];
        if ( $include_filename === false ) {
            $file_path = str_replace(basename($file_path), '', $file_path);
        }
    } else {
        $file_path = null;
    }
    return $file_path;
}
 4
Author: blizzrdof77,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-17 17:42:45

Prueba esto en tu script

echo getcwd() . "\n";
 2
Author: Shuhad zaman,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-24 10:25:42
realpath($_SERVER['SCRIPT_FILENAME'])

Para el script ejecutado bajo servidor web $_SERVER['SCRIPT_FILENAME'] contendrá la ruta completa al script inicialmente llamado, por lo que probablemente su índice.php. realpath() no se requiere en este caso.

Para el script run from console $_SERVER['SCRIPT_FILENAME'] contendrá la ruta relativa al script al que se llamó inicialmente desde el directorio de trabajo actual. Por lo tanto, a menos que haya cambiado el directorio de trabajo dentro de su script, se resolverá a la ruta absoluta.

 2
Author: Victor,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-09 15:47:50

La forma más fácil de recuperar la ruta absoluta del script ejecutado inicialmente desde ese script "principal" y cualquier script incluido con include, require, require_once es almacenándolo en una constante al principio del script principal:

define( 'SCRIPT_ROOT', __FILE__ );

__FILE__ devuelve la ruta del script actual. Usado dentro de un script incluido devuelve la ruta del archivo incluido , no el script que se ejecuta inicialmente como pide el OP:

Aclaración: El script ejecutado inicial, no el archivo estamos actualmente en

La solución de almacenar el __FILE__ en una constante es más fácil y más rápido que recuperar la ruta usando debug_backtrace()


La solución anterior es adecuada cuando hay un único script "principal" que includees cada otro script necesario, como en la mayoría de las aplicaciones web.

Si ese no es el caso y puede haber varios "scripts intitales", entonces para evitar redefiniciones y tener la ruta correcta almacenada dentro de la constante, cada script puede comenzar con:

if( ! defined( 'SCRIPT_ROOT' ) ) {
    define( 'SCRIPT_ROOT`, __FILE__ );
}
 1
Author: Paolo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-12 12:10:02

Esto es lo que uso y funciona en entornos Linux. No creo que esto funcione en una máquina Windows...

//define canonicalized absolute pathname for the script
if(substr($_SERVER['SCRIPT_NAME'],0,1) == DIRECTORY_SEPARATOR) {
    //does the script name start with the directory separator?
    //if so, the path is defined from root; may have symbolic references so still use realpath()
    $script = realpath($_SERVER['SCRIPT_NAME']);
} else {
    //otherwise prefix script name with the current working directory
    //and use realpath() to resolve symbolic references
    $script = realpath(getcwd() . DIRECTORY_SEPARATOR . $_SERVER['SCRIPT_NAME']);
}
 1
Author: andrewniesen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-02 02:33:19