Arthor
Arthor

Reputation: 674

Reference to file regardless of the folder structure and depth

My research has lead me to believe that it might be called, absolute URL / relative URL. But please, I am not sure. So this is not reason to give me a minus as I have just reached 50 and I am on a STEEP learning curve.

In my index.php

I have a reference to a csv array. /array/test.csv

Then, I have a folder called MENU. In this folder I have a PHP called menu.php which also needs to make reference to the test.csv. However I Cannot put /array/test.csv, instead I have to put ../array/test.csv.

So depending where you are in a folder structure, you might have to use / or ../ or ../../,

Can someone point out the correct way to do this as I know that I will have problem if I do not learn the correct way.

Upvotes: 6

Views: 4680

Answers (3)

tbraun89
tbraun89

Reputation: 2234

If you don't use the DOCUMENT_ROOT it depends on your folder structure. ".." means that you go one folder back.

If you have this structure:

root_dir
|
folderA
|  |
|  - A.php
|
folderB
   |
   - B.php

If you are in file B.php and want to include A.php you have to use this path:

inlcude "../folderA/A.php";

so you go one folder back, then you are in the root_dir from where you can access A.php via folderA/A.php.

Upvotes: 1

Jakub
Jakub

Reputation: 20475

Arthor, there is no correct way, you are correct it is relative vs absolute reference to a file/url/resource.

There is no wrong way. However each approach has its upsides, and downsides:

Key difference points:

  • relative: portability (you can move your app by copy & paste somewhere else, as you call URLS ../array/file.ext you will always refer to them correctly.
  • relative: moving a file that makes reference to a resource relatively means you have to update its reference, if file was in /file/folder/stuff/file.ext and you move it, you need to update the reference to your /array/file.ext then.
  • absolute: less portable, unless you use it in a URL sense (include javascript / images, etc)
  • absolute: moving files that reference other files, means you don't have to change their code.
  • and many more...

Personally I prefer absolute, but really it depends on your reasoning, neither of which is wrong.

Oh and to clarify (if you didn't know) ../ simply means "go down one directory, and then look from there, it is used in a relative link, where you outline where the file is relative to your script that is calling it.

Upvotes: 1

thenetimp
thenetimp

Reputation: 9820

I would call the full path of the file.

$_SERVER['DOCUMENT_ROOT'] . "/array/test.csv"

The beginning says where the htdocs folder for your web server is. Then we add the rest of the path from there.

So to store the path in a variable you may do.

$csvFile = $_SERVER['DOCUMENT_ROOT'] . "/array/test.csv"

Upvotes: 5

Related Questions