PHP Include and Require

PHP Include and Require

Last Updated on Mar 21, 2023

What do they do?

include/require will take all the code/content from an specified file and put it in your current file.

For example let’s say I have a file like this

<?php
echo "Hello Pratham!";

And My current file is like this:

<?php
echo "Hello World!";

If I include/require the first file in my current file it will echo both of the statements.

The order of them depends on where I include the other file

<?php
include "./name.php";
echo "<br>";
echo "Hello World!";
// output is:
// Hello Pratham!
// Hello World!

and

<?php
echo "Hello World!";
echo "<br>";
include "./name.php";
// output is:
// Hello World!
// Hello Pratham!

In both cases we could use require as well.

Include vs. Require

So what’s the difference between include and require?

If ther's an error, include shows a warning and then the rest of your script keeps running.

But require will throw an error and stops the execution of the code

Use case

"so what's the use case?" you might ask.

well one of the most common use cases is that you can easily organize your files and avoid repeating yourself.

for example you can have footer and header and sidebar in a seperate file and include them in your files. that way you don't have to repeat yourself and you can update your footer or header in one place and your code will be updated everywhere

<?php
require './header.php';
require './sidebar.php';
// main content goes here
require './footer.php';

Include once

when you use include_once or require_once, PHP will keep track of the files, and if you have already included/required a file, it won't include/require it again. this way PHP helps you avoid issues like function redefinition, etc. other than that their behaviour is identical.

https://youtu.be/yy8QogjpuiI

Conclusion

Now you know about working with include and require in PHP.

I recommend you to open multiple PHP files and try to include/require their content inside another file. include/require them multiple times to see if you get any errors.

If you have any suggestions, questions, or opinions, please contact me. I’m looking forward to hearing from you!

Key takeaways

  • working with include and require
  • include vs require
  • include vs include once
  • require vs require once

Category: programming

Tags: #php

Join the Newsletter

Subscribe to get my latest content by email.

I won't send you spam. Unsubscribe at any time.

Related Posts

Courses