How To Use The Include() And Require() Functions In PHP

How To Use The Include() And Require() Functions In PHP

·

2 min read

In this post, we will be learning how to add code from another PHP file into your code.

a.php

<?php 
echo "BBBBBBB";
?>

It is possible to include all the code written in a.php in another file called b.php without rewriting all the same code in b.php.

You may add all the code from another file by using two built-in functions called include() or require(). In fact, you can include files of any type that can run in PHP, such as text or HTML files (although generally speaking we only include PHP files).

Include() Include() includes all the code of one file, letter for letter, in another file.

Syntax

<?php
include("xxx.php");
?>

If you wish to include a file that is in another folder, you need to write the entire path name.

<?php 
include("folder/file.php");
?>

Require()

Another function we can use to include code from another file is the require() function. It works almost exactly the same way as include().

There is, however, a subtle difference between how they work.

If a file cannot be successfully executed(e.g. it doesn't exist), then require() will stop the code from running further.

Include(), however, will not; all the code below it keeps executing.

Include_once() And Require_once()

A slightly modified version of include() and require() are include_once() and require_once().

The added difference with those functions is the file cannot be included or required more than once.

Otherwise, their syntax is the same as include() or require().