doubt with include php

Asked

Viewed 75 times

1

Well I have a function where I need to load a include file into the function. Kind like this:

function Query($conexao, $query) {

   // Includes
   include "../Dados.php";

}

the problem is that in some files in which I call the function it does not locate the data file. This is because some files are inside some folders. Is there any way to make include fetch the data file at the root of the site? Or regardless of where I call the function it goes at the root and searches the file.

  • If you replicate this function on several pages you will need to point the way, if your function is in a single script and you simply call it you can use the predefined constants as DIR which will point to the directory from its script containing the function. http://php.net/manual/en/language.constants.predefined.php

  • The 'DIR' has been replaced by 'FILE' in PHP 5.6 if I am not mistaken. So the function is in a single scrip, so I avoid duplicating code. I call the function file on the page I want with a 'include', and then call the function.

  • Note that I did not cite the function dir() of bad directories yes to default count __DIR__ functional in php 7.1.*

  • Right. Ta mais __DIR__will return me the path where the 'incluide' is and I always need to return to the root folder

  • Why not use a constant with the absolute path of the file?

1 answer

2


You can use __DIR__ of the counting predefined

**example*:

function Query($conexao, $query) {

   // Includes
   include __DIR__ . "../Dados.php";

}

__DIR__ will point from the directory where the function script is.

editing:

The following function is based on the root and not relative to the directory as in the above example:

function Query($conexao, $query) {
    // includes
    include  str_replace("\\", "/", dirname($_SERVER["DOCUMENT_ROOT"])."/path/or/subpath/to/Dados.php");
}

The above function can be used to direct the path to the file Dados.php from the root.

A local example in Windows would be something like this:

echo str_replace("\\", "/", dirname($_SERVER["DOCUMENT_ROOT"])."/path/or/subpath/to/Dados.php");

// output: C:/Server/www/path/or/subpath/to/Dados.php
  • Well it tries to find the file with a wrong link /Library/WebServer/Documents/Sistema/Funcoes../../Dados.php

  • I think I figured I’ll give one up on the answer

  • ok I’m waiting

Browser other questions tagged

You are not signed in. Login or sign up in order to post.