tags:

views:

158

answers:

5

I am crash-learning PHP for a project, and I have a ton of stupid questions to make. The first is the following. I have a structure like this:

  • index.php
  • header.php
  • images/
  • data
    • data.php

Now, the problem is that I want to include the header.php file in the data.php file. That is no problem.

The problem I have is that header.php has a link to the images folder in a relative way. So, the images won't load.

To make matters worse, this structure is under a specific alias, so I just can't append a / to the beginning of the link to the image.

What I need, I guess, is a way to get the path to the application in the script. That way I can reference to the images without worrying where the include is made.

How do you get this path in PHP?

A: 

Take a look at $_SERVER['PATH_TRANSLATED']

Glenn
+2  A: 

Try including the file like such:

<?php
    include($_SERVER['DOCUMENT_ROOT'].'/data/data.php/');
?>

The DOCUMENT_ROOT will return the path of the root folder, located on the web server of your website.

Andreas Grech
A: 

Use set_include_path(get_include_path().PATH_SEPARATOR.$new_path) where $new_path should get you all the way from your absolute root folder to the result of getcwd().

Make sure to add this include path to the main file so the code is not repeated for every file in data/. This will also make sure you aren't bothered with the same issue again.

chelmertz
+2  A: 

Many people use something like this. The dirname(__FILE__) will return the directory of the current script. Then you concatenate that to relative path to the script you are including.

require(realpath(dirname(__FILE__).'/lib/Database.php'));
Zoredache
i have seen this somewhere before.... o yea it was my answer!
A: 

All the good PHP answers being already taken, I'd suggest you look at it the other way: is there something preventing you from linking the image as src="/images/yourimage.gif"? This way the image will load no matter where you call it from.

djn
That is exactly my problem! I can't do /images/yourimage.gif because I don't know in which folder will the application reside. It could be /app1/images/yourimage.gif or /app2/images/yourimage.gif
Mario Ortegón