Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
251 views
in Technique[技术] by (71.8m points)

How do I set an absolute include path in PHP?

In HTML, I can find a file starting from the web server's root folder by beginning the filepath with "/". Like:

/images/some_image.jpg

I can put that path in any file in any subdirectory, and it will point to the right image.

With PHP, I tried something similar:

include("/includes/header.php");

...but that doesn't work.

I think that that this page is saying that I can set include_path once and after that, it will be assumed. But I don't quite get the syntax. Both examples start with a period, and it says:

Using a . in the include path allows for relative includes as it means the current directory.

Relative includes are exactly what I don't want.

How do I make sure that all my includes point to the root/includes folder? (Bonus: what if I want to place that folder outside the public directory?)

Clarification

My development files are currently being served by XAMPP/Apache. Does that affect the absolute path? (I'm not sure yet what the production server will be.)

Update

I don't know what my problem was here. The include_path thing I referenced above was exactly what I was looking for, and the syntax isn't really confusing. I just tried it and it works great.

One thing that occurs to me is that some people may have thought that "/some/path" was an "absolute path" because they assumed the OS was Linux. This server is Windows, so an absolute path would have to start with the drive name.

Anyway, problem solved! :)

question from:https://stackoverflow.com/questions/344419/how-do-i-set-an-absolute-include-path-in-php

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

What I do is put a config.php file in my root directory. This file is included by all PHP files in my project. In that config.php file, I then do the following;

define( 'ROOT_DIR', dirname(__FILE__) );

Then in all files, I know what the root of my project is and can do stuff like this

require_once( ROOT_DIR.'/include/functions.php' );

Sorry, no bonus points for getting outside of the public directory ;) This also has the unfortunate side affect that you still need a relative path for finding config.php, but it makes the rest of your includes much easier.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...