Functions stop working when file included with root path (leading slash)

前端 未结 3 1147
野趣味
野趣味 2020-12-18 14:34

My PHP files in my root directory INCLUDE header.php. Header.php INCLUDEs functions.php. I\'m adding new pages in a subdirectory, so I added leading slashes to all my links

3条回答
  •  隐瞒了意图╮
    2020-12-18 15:02

    Just so you're aware, if you're going to have the php pages you're requesting also request other pages themselves, it may be beneficial to use require_once instead of include. That will make it so none of the pages that are included repeat themselves and you don't have to worry about accidentally including something more than once.

    That being said... when you request a page in the root directory, it will request header.php in the root directory which will in turn request functions.php in the root directory. However, if you request from the subdirectory, ../header.php will reference header.php in the root directory, but that whole file will get included, and then its the php page in the subdirectory that ends up trying to include /functions.php. It would need to request ../functions.php, but that would cause everything in the root directory to stop working.

    I'd suggest setting a variable in header.php along the lines of $root = $_SERVER['DOCUMENT_ROOT']; Then, all includes in header.php should be like include($root."/functions.php");

    $_SERVER['DOCUMENT_ROOT'] will get you objective url to the root, which will enable you to make sure you're referencing the correct place no matter where you're requesting header.php from.

提交回复
热议问题