开发者

Should I include locally or remotely?

Just something I wonder about when including files:开发者_JAVA技巧

Say I want to include a file, or link to it. Should I just for example:

include("../localfile.php");

or should I instead use

include("http://sameserver.com/but/adirect/linkto/localfile.php");

Is one better than the other? Or more secure? Or is it just personal preference?

Clearly it would be a necessity if you had a file that you would include into files in multiple directories, and THAT file includes a different file, or is there some other way of doing that?


Reading a file is much faster than making an HTTP request and getting the response. Never include(a_uri) if you can help it.

Use $_SERVER['DOCUMENT_ROOT'] if you want to calculate a complete file path for your include.


As said before, definitely include a local file and not do an HTTP request (which takes more time, is not cached and the contents are technically viewable to all the world, if he knows where to look for it).
One more small detail, if you use full paths to your included files, it will even be faster then relative paths, especially if you use some kind Byte Code Cache.


Definitely include the local file, because the php script doesn't really know or care that you're including a script on your local server, so the url path causes an http request, and network latency from http requests is pretty much the bottleneck for rendering any html page in general, the fewer of them you have, the better off you're going to be.

Personally, I try to avoid using include and require in general, in favor of require_once, because using require_once means that you are writing your code reusably instead of writing code that executes immediately when you include it. Pull in class definitions, pull in function libraries, but try to avoid code that executes immediately when you include it, because that will make it harder to reuse.


If your question is about keeping it so you don't have to change a billion paths when you move from staging to production, go with this little tidbit I learned:

 define('BASE_DIR',  '/path/to/root/');

Then use BASE_DIR in all of your path references. When it's time to move your site, just change that definition to the new path (which should just be / at that point).


In addition to what other people say, these invocations will have different results, since the remove invocation will execute php output, not the file contents. Unless you stop php from processing the file, in which case you're exposing your code to the world which is also not necessarily what you actually want to.


Always include locally, cause if you include remote someone can create a different file and do nasty things. And the other problem you can't really test this with remote includes. As far as i know you should use require_once instead...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜