Relative paths in PHP not working on server [closed]

走远了吗. 提交于 2019-12-24 00:59:59

问题


Background info: I've been developing a self hosted Facebook app on my own server (localhost) and have everything all working. Recently, I uploaded my files to my shared hosting online server (hostgator) and an odd bug popped up.

My require_once() functions seem to ignore relative paths on the hostgator server. For example, in index.php, I have require_once('fb/login.php'). This throws an error, stating that the file at example.com/login.php cannot be found. Why does require() ignore the fb part of my path? Remember, this works perfectly fine on my private localhost server. I did some Googling and solved half the problem by going into php.ini and turning on include_path=".:". This got rid of the first error, but now login.php also has require_once('fb/sdk/Facebook.php') and cannot locate that file. I understand that it gets messy with nested requires, but this does work on my localhost server. Both servers are PHP5, and I have made sure that the php.ini files are similar. By default, the localhost php.ini has include_path commented. I have even gone as far to replace the online php.ini file with my localhost one. Still, nothing. I have tried using absolute paths, and they do work, but I have many includes and requires throughout my code and do not want to hand code every single path. Any insight? This is a really infuriating problem and I hope there is an easy solution.

Thank you!


Well I did a ton of research and ended up using $_SERVER['DOCUMENT_ROOT'].'fb/login.php' as my path for all of my requires and includes. Fixed all of my problems, thank god


回答1:


I stopped using relative paths a long time ago to avoid the kind of troubles you are going through now. Consider doing like all PHP frameworks do - they define a variable that indicates where exactly is the root of the server, then you can use that to build absolute paths to your files.

You can do that by adding this to you root index.php file:

define('DOCROOT', realpath(dirname(__FILE__)).'/');

Then it's just a matter of going through all your require statements and adding DOCROOT first:

require_once('fb/login.php');

becomes:

require_once(DOCROOT . 'fb/login.php');

You can even do a global search and replace by replacing require_once(' with require_once(DOCROOT . '




回答2:


I can't say that I know how to solve it, but here is what I did several times with directories issues:

First thing is to call getcwd() in the file you use require_once to see if you really where you think you are.

Second, try ./fb/ instead of fb/




回答3:


Why don't you try require_once('../fb/login.php'); instead of changing php.ini file?

or just require_once('/fb/login.php');



来源:https://stackoverflow.com/questions/10221787/relative-paths-in-php-not-working-on-server

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