Should I complete this directive or not? php echo dirname (__ FILE__); ?


This I found as an example on the internet to know the path where I am in Linux (where you have the file to get the absolute path):

echo dirname(__FILE__);

Now my question is: what do I have to complete what is in parentheses? Or do I put it the way it is?

asked by Lita San 02.05.2016 в 22:23

2 answers


I do not understand what you mean by completing but if you call it like this it works, since the function dirname() returns the path of a parent directory, if you pass it as parameter __FILE__ it will return the path of the php file where the function is being called. If for example your file is in /var/www/html/sistema/archivo.php

echo dirname(__FILE__);

It will show as result / var / www / html / sistema /.

answered by 02.05.2016 в 22:35

If you mean that echo needs parentheses as if it were a function: no, it does not need them because it is not a function, but a language construction (such as require , include , case , etc):

/* Esto es innecesario */
echo (dirname(__FILE__));

The code you have used sends the route directly to the browser, does not store it for later use. If you want to store it for later use, what is missing is assigning it to a variable, and not putting parentheses or anything similar.

Doing what I show you next, you can open files using that base path stored in the variable:

/* Almacenamos la ruta del script en la variable $ruta */
$ruta = dirname(__FILE__);
/* Hacemos uso de la variable $ruta para acceder a un archivo que
  hay en el mismo directorio que el script */
$datos = file_get_contents($ruta . '/archivo.txt');

NOTE: As of PHP 5.3 you have available the constant predefined __DIR__ . At the date of your question the oldest version with support was the PHP 5.5 version, so you should use that macro instead of dirname(__FILE__) .

/* Ya no es necesario almacenar la ruta base en ninguna variable */
$datos = file_get_contents(__DIR__ . '/archivo.txt');
answered by 07.08.2018 в 10:53