In PHP, there’s a handy dandy little function called ‘include’ that basically allows you to run a php script from another file in your current script. There is also a handy dandy little function called ‘require’ that basically does exactly the same thing. Basically. Likewise, there’s ‘require_once’ and ‘include_once’ which both due the same thing, but check the current document to see if its been included or required already, and won’t do it a second time. So…which should you use, and when should you use it?
It all depends on the application. With ‘include’, if an error occures in the included file, the remainder of your application can still function. At most, you will see get a warning, but nothing more. With ‘require’, if there is an error in the required file, the remainder of your application will not function, and your scripts will stop running. Sounds scary, right? Off the bat, it may seem like, from a usability standpoint, you should use ‘include’ or ‘include_once’ as a default – but this really isn’t the case. Think of what you are implying.
If you use include over require, you are doing a few things:
As best practice, you really shouldn’t be including code that doesn’t need to exist. At the very least, it can impact performance of your application. ‘include’ should really only be used for ‘optional’ code, but…how often is code you write used only part of the time? Very rarely.
Using require throws errors – which is a huge benefit in spite of how scary it may look. Checking your server logs, or getting immediate feedback as to what broke in your code is crucial when developing. If your required file patches a security loophole of some sort, it is obviously essential that your application stops running if the required file breaks.
So, best practices?
PHP is a widely used language, but is full of security holes. It is important to understand some of these basic practices as your develop your websites and/or applications in PHP to keep you and your users safe, and to make sure your code is running optimally.