How to Include File in PHP [All Methods]

There are two methods to include a file in PHP.

  1. Include() Method
  2. Require() Method

Include file in PHP is helpful to append various global or config files. We can include .php files via include and require functions.

We can write global functions and classes in a config file and include them where it is needed.

Method 1: include()

Include() method is used for soft include file in PHP. This means if the included file does not include properly compiler will skip include file process and start to compile the rest of the code.

Include method will not prompt any error while runtime if a file could not be included.

Syntax

<?php

include("file_name_path");

?>

Example

<?php

include("/config_folder/demo_config.php");

?>

Method 2: require()

Require() method is used for hard include file in PHP. This means if the included file does not include properly compiler will throw an error and stops to compile the rest of the code.

Require method will prompt runtime error if a file could not be included.

Syntax

<?php

require("file_name_path");

?>

Example

<?php

require("/config_folder/demo_config.php");

?>

Conclusion

Include and Require both methods have their own pros and cons. Both methods are popular among PHP programmers.

There is no strict rule to use these methods. The usage depends on the workflow and structure of the website.

Enjoy Coding 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *

Read previous post:
call api in php using curl
How to Call API in PHP Using Curl

PHP is the most used back-end language for websites because of its flexibility and long-lasting support. PHP provides effortless inbuilt...

Close