How to import config.php file in a PHP script ?

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’.
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <?php
       $host = 'localhost';
       $database = 'GeeksForGeeks';
       $username = 'admin';
       $password = '';
    ?>

    chevron_right

    
    

  • 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.
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <?php
       include('config.php');
       echo "Host: ".$host." Database: ".$database;
    ?>

    chevron_right

    
    

  • 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.
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <?php
       return [
       'host' => 'localhost2',
       'database' => 'GeeksForGeeks2',
       'username' => 'admin',
       'password' => ''
       ];
    ?>

    chevron_right

    
    

  • Code 2: Accept the returning array in a variable.
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <?php
       $details = include('config.php');
       echo 'Host: ' . $details['host'] . 
            ' Database: ' . $details['database'];
    ?>

    chevron_right

    
    

  • Output:
    window2



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.