Link to file regardless of folder structure and depth

First of all, I'm not quite sure how to explain this, so please pay attention to me.

My research led me to believe that it could be an absolute URL / relative URL . But please, I'm not sure. So this is not a reason to give me a minus, since I just reached 50, and I am on the STEEP learning curve.

In my index.php

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

Then I have a folder named MENU . In this folder, I have PHP called menu.php, which should also reference test.csv. However, I can not put /array/test.csv , instead I need to put ../array/test.csv .

So, depending on where you are in the folder structure, you may need to use / or ../ or ../../ ,

Can someone point out the right way to do this, as I know that I will have a problem if I don't find out the right way.

+4
source share
3 answers

I would name the full path to the file.

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

The beginning indicates where the htdocs folder for your web server is located. Then add the rest of the path.

So, to save the path in a variable that you can do.

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

Arthor, there is no right way, you are right, this is relative vs absolute link to the file / url / resource.

There is no wrong way. However, each approach has its advantages and disadvantages:

Key difference points:

  • relative: portability (you can move your application by copying and pasting to another place, since you call URLS ../array/file.ext , you will always access them correctly.
  • relative: moving the file that refers to the resource relatively means that you need to update its link, if the file was in /file/folder/stuff/file.ext and you move it, you need to update the link to your /array/file.ext then.
  • absolute: less portable unless you use it in the sense of a URL (including javascript / images, etc.)
  • absolute: moving files that link to other files means that you don’t need to change their code.
  • and much more...

Personally, I prefer the absolute, but in fact it depends on your reasoning, neither one nor the other.

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

+1
source

If you are not using DOCUMENT_ROOT , it depends on the structure of your folder. ".." means you are returning one folder back.

If you have this structure:

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

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

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

so that you move one folder back, you are in root_dir , from where you can access A.php through folderA/A.php .

+1
source

Source: https://habr.com/ru/post/1394615/


All Articles