The include statement in PHP copies the code of text from the file mentioned, into the file that uses the include statement. It directs the preprocessor to insert the content specified into the following program. The name of the file to be included is written in double-quotes. It is a good practice to write the basic database details and user details in a file named “config.php”. You can also include the connection building statements in the config.php file to automatically build the connection to the database for every page that includes the config.php file. Including files allows you to form a template of code that is required by multiple pages of a website.
Syntax:
<?php include('config.php'); ?>
Example 1: This shows the creation and including of config.php file.
- Code 1: Create a PHP file and save it with the name ‘config.php’.
<?php
$host
=
'localhost'
;
$database
=
'GeeksForGeeks'
;
$username
=
'admin'
;
$password
=
''
;
?>
- Code 2: Create a PHP file and save it with the name ‘try.php’ in the same folder as ‘config.php’ file. Copy the below code to include the ‘config.php’ file and get a print the name of the database and username.
<?php
include
(
'config.php'
);
echo
"Host: "
.
$host
.
" Database: "
.
$database
;
?>
- Output:
Example 2: If you want to save the contents of the config.php file into a variable, then the following code does that work.
- Code 1: Simply return the contents of the ‘config.php’ file.
<?php
return
[
'host'
=>
'localhost2'
,
'database'
=>
'GeeksForGeeks2'
,
'username'
=>
'admin'
,
'password'
=>
''
];
?>
- Code 2: Accept the returning array in a variable.
<?php
$details
=
include
(
'config.php'
);
echo
'Host: '
.
$details
[
'host'
] .
' Database: '
.
$details
[
'database'
];
?>
- Output: