Tutorials PHP Includes and Requires

Includes and Requires

Today you will learn how to insert a file into PHP. This is a very useful function as sometimes you might want only one copy of a global feature. If you have a navigation bar, headers or footers that stay the same throughout your site, it is really useful to have it in one central location. Imagine having a big website with a million pages and your boss tells you to change the new copyright year. There goes your weekend....

What files can I insert?

Pretty much any plain text file. HTML, TXT and PHP will work fine.

How do I do it?

There are four functions used to insert files. include, include_once, require, require_once.

include 'file.php';

include_once 'file.php';

require 'file.php';

require_once 'file.php';

What's the difference between include and require?

If you don't mess up, there is no difference. The difference is what happens if PHP can't find your file. If you use include, PHP will skip over the file and move onto the next item. If you use require, PHP will stop everything if it can't find the file. If the file is vital, you might want to use require to make sure it's there. If the file isn't that important, you might want to use include so users can see something instead of a blank page.

What does once mean?

once checks if the file has been inserted already. If the file doesn't need to be loaded multiple times, you can use once to make sure there's only one copy. If you plan to load the file again and again, don't use once.

Do I link relative to the actual file or the inserted file?

You have to link it relative to the actual PHP file. PHP inserts the file first before processing it. This won't mean anything if you use absolute links or have all the files in one location. If your PHP file is in one folder and you're inserting a file that's in another folder, and you have relative links inside your included file, you have to link to it like you would from the host file.

Does this process code inside the inserted file?

Yes. You can write HTML, PHP, JavaScript or any other code in these files and it would be the same as if it was on the actual page. If you do not want to process the PHP code, use file_get_contents to turn it into a string.

That's all for now. Try to use this to contain sitewide features such as navigation bars and footers. If you need to change something, you only need to edit one file. Have fun and see you guys next week!

Posted by on . Category: PHP


No comments posted yet

You need to register or login to post new comments.