Use the required / included file as base directory in PHP

六眼飞鱼酱① 提交于 2019-12-12 03:55:13

问题


I am currently using an index.php to include another file , it structure like:

root / index.php
     / new/ index.php

And I use

<?php
require_once("new/index.php");
?>

the problem is , all paths in it are wrong. As all paths are based on new/index.php , when i include it, all paths changes to based on index.php. Are there any way to let the outsider visit index.php but at the same time my actual code is stored in new/ folder? Thanks


回答1:


Are you talking about something like

<?php echo '<img src="my_image.jpg">; ?>

If so, use a slash to get to the url root and then use the full path from there like

<?php echo '<img src="/images/my_image.jpg">; ?>

Otherwise your urls can be messed up easily.




回答2:


Change current directory using chdir function.




回答3:


include with an absolute path

require_once(dirname(__FILE__) . "/filename.php");




回答4:


I'm not quite sure what you're asking, but if you want to include a file relative to your root, this is my solution:

require_once($_SERVER['DOCUMENT_ROOT'] . '/new/index.php');


来源:https://stackoverflow.com/questions/19161253/use-the-required-included-file-as-base-directory-in-php

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