PHP - directory path

Asked

Viewed 723 times

0

I’m making a website that has a column called -News-, this column I call through the include. (you can imagine that it is an external file - news.php), until then.

It turns out that on my site there are folders on other levels, for example:

  • index php.
  • news php.
  • content/acao/index.php
  • content/material/index.php
  • content/util/index.php

There are about 10 folders with the same structure.

On the home page (index.php), I’m including the news php. as follows:

$path = "news.php" ; 
include $path;

So far normal.

Turns out when I call the same file we index that has sublevels, my URL misses the reference.

$path = "../../news.php" ; 
include $path;

The field news appears on my pages, but when I click on a link to URL wrong. Following example below:

content/news/2018/acao/news/2018/index.php

I’d like to know if there’s anything PHP, back to the parent level (let’s say so).

I tried to use $path = $_SERVER['DOCUMENT_ROOT'];, but it didn’t work. dirname($path) also did not work.

Of course PHP is correct in its reading, but if you can help me to solve this problem, I would be grateful.

  • news.php is in the root folder of your project, and the $path that is giving error when giving include is within content/acao/index.php?

  • that’s right ! $path is in the share index...

  • Utilize set_include_path('/path/to') in their index php. or use the full path include "/path/to/news.php"; or use rewrite (as a kind of friendly URL).

  • cool... I’ll try what you said ... (y)

1 answer

2

You can do it this way:

$raiz = $_SERVER['DOCUMENT_ROOT'] . DIRECTORY_SEPARATOR;
include $raiz . "news.php";

So you always take the site host and don’t need to worry on which page is called the include.

If you’re gonna use the include for other files that are inside some folder do this way:

$raiz = $_SERVER['DOCUMENT_ROOT'] . DIRECTORY_SEPARATOR;
include $raiz . "content/util/index.php";

So you need to think the way from the root.

I did the following function to make things easier:

function caminho($path){
    $path = $_SERVER['DOCUMENT_ROOT'] . DIRECTORY_SEPARATOR . $path;
    $barras = array('\\', '/');
    return str_replace($barras,DIRECTORY_SEPARATOR,$path);
}
include caminho("news.php");
  • I tried the two alternatives that you forwarded to me, but it didn’t work. The page does not fail, but the news.php file is not loaded. Is there something I have to install or configure?

  • I edited the answer, try this way.

  • ..look, I honestly don’t know what’s going on. I did exactly what you advised me to do. Page error does not happen, but news.php does not appear .. using the function you did. Do I need to upload the site in the domain in order to see the changes? (It is necessary to ask this kind of question) =\

Browser other questions tagged

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