The Difference Between require, require_once, include, include_once in PHP

If you are writing PHP, I am pretty sure you wrote require or/and include. But are you sure which one you really need? Let’s check what all that means and which one you should use in specific areas.

Require vs Include

We can think of “require” as a necessity. If we add a file into another file with “require” that means we absolutely need that file to execute our remaining code. But if we add a file with “include” that means even if that file does not exist, our code still can work.

So if the file exists, you won’t see any difference when you use require or include. But they will fire different errors when the file doesn’t exist. For both methods, they are not working like copy/paste the codes. Even PHP doesn’t know the file is exists or not until PHP runtime reaches to require/include line. For example, if you write this code, it will never fire an error, because PHP will never reach to require line;

if(false){
 require_once('the_required_file.php');
}

And what will happen if PHP can reach to require or include code and file is not there. If you write “include” PHP will throw a warning error. If you write “require” PHP will throw a fatal error. By the way, if there is an include and warning error fired, PHP still will continue to read the remaining codes.

Once vs Multiple

Who will win?

Should we run our functions as one or as many? When we write require_once or include_once PHP will check is this file called before or not. If the file called before, then PHP won’t call it again.

Because of once come with extra check, we can say it effects the speed of code executing time. Probably you won’t feel the difference if your site doesn’t get millions of visitors. But still, you know which one is doing what 🙂 Now you know what exactly these functions doing and can decide which one to use based on your needs.

Don’t forget to share this post, if you think it’s useful, cheers…

Leave a Reply