Include an external file to my site, most of time, i use include(). But i've seen sites saying include_once is more secure, but they didn't specify a reason why it is more secure.
Asked
Active
Viewed 187 times
1
-
1Yes it is a duplicate. Also you need to think of autoloading your files. Please read articles about psr-4 or use composer for autoloading. So you will only use one include and you have a much better design of your software. – Thomas Deutschländer Jul 21 '19 at 07:41
-
1Doesn't exactly look like a duplicate to me. The question is more inclined to security implications. – nice_dev Jul 21 '19 at 08:14
-
1I've never heard *security* among the factors to choose between those constructs. If there's any truth in that let's wait and see if anyone can shead some light. But I suggest you edit the question and quote the actual statements or it'll possibly get closed again. – Álvaro González Jul 21 '19 at 08:40
-
2In my opinion it does **not affect security**, at all. I think it is meant the program is executed more _secure in terms of avoiding a crash_ (throwing exceptions). – Markus Zeller Jul 21 '19 at 08:56
2 Answers
3
When using include_once()
, it is guaranteed the file is only included once.
When using include()
it could be included multiple times - depending on your code.
Bad examples (program may throw an exception):
- Re-define a constant.
- Overwriting already existing functions.
Good example:
- Re-use template snippets.

Markus Zeller
- 8,516
- 2
- 29
- 35
-
I can't really see how any of this affects security at all. Plus you can't even overwrite functions in PHP (unlike JavaScript). – Álvaro González Jul 26 '19 at 17:17
-
-
Alright, I had overlooked that comment. Perhaps you should provide that info in the answer :) – Álvaro González Jul 26 '19 at 17:20
-
I thought not to write, because it is my opinion and no technical explanation. – Markus Zeller Jul 26 '19 at 17:23
-2
include_once() i don't think so it is related to secure, actually when we put include_once() means that if you include same file with multiple time then php will not give any error but if you are use include() it will give an error. according to my knowledge.

Ram
- 21
- 10
-
that's totally wrong ! The main (not the only one) difference between `include` and `include_once` is that `include` will include the desired file **even if it was already included**, but `include_once` **won't "re-include" a file if it has been already included**. Also, no errors are raised unless the file cannot be found (in fact the two function will raise a warning and the `script` isn't halted of course if there is no usual mistake that throws an error like redefining/assigning a `constant` for example). I think you have mixed between `include` and `require`. – ThS Jul 21 '19 at 08:53