Make path accessible at various level of folder on PHP

拈花ヽ惹草 提交于 2019-12-25 05:19:50

问题


Assume that I have a folder with some folders and pages on it:

  • FolderA
    • PageA1.php
  • FolderB
    • FolderB1
      • PageB11.php
    • FolderB2
      • PageB21.php
    • PageB1.php
  • FolderC
    • PageC1.php

On PageB11, I have:

require_once 'FolderB2/PageB21.php';

While calling PageB11 on PageB1:

require_once 'FolderB1/PageB11.php';

It's work fine. But now the problem is, while on PageB11 also have a function that call the page itself (PageB11), then the error showed:

Warning: require_once(FolderB2/PageB21.php): failed to open stream: No such file or directory in Path\FolderB\FolderB1\PageB11.php on line X

When I changed the require_once line on PageB11 become: require_once '../FolderB2/PageB21.php';, it's work!

What I wanna do is, how to make all of it accessible at various level of folder? Is is possible to do that? Thanks..


回答1:


As stated, the best way of handling such situations, is to refer to each file by its absolute path. This is the path from the root of the filesystem, unlike a relative path which is given relative by the current file.

In PHP you have a magical constant __DIR__, which gives the absolute path of the current file. Prepend every include/require with that, and you'll never see that problem again.

require_once __DIR__ . '/../FolderB2/PageB21.php';

You can also make use of realpath().




回答2:


You can add the absolute path to the files

require_once('/home/my_host_account/www/FolderB2/PageB21.php');

Please verify if this is working.




回答3:


You can also create soft-links in each directory referring to your original. But this is a workaround that should be used only if all other methods fail.



来源:https://stackoverflow.com/questions/11840317/make-path-accessible-at-various-level-of-folder-on-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!