Home >Backend Development >PHP Tutorial >How to Import config.php File in a PHP Script?
The include() function in PHP copies the code from the specified file into the file that uses the include statement. It directs the preprocessor to insert the content of the specified file into the current program. The name of the file to be included is written in double quotes. It is good practice to write basic database and user details in a file named “config.php”. You can also include connection-building statements in the “config.php” file to automatically establish a database connection for every page that includes “config.php”. Including files allows you to create a template of code that can be reused by multiple pages of a website.
<?php include('config.php'); ?>
Example 1: This shows the creation and including of the 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:
Want to be a Software Developer or a Working Professional looking to enhance your Software Development Skills? Then, master the concepts of Full-Stack Development. Our Full Stack Development - React and Node.js Course will help you achieve this quickly. Learn everything from Front-End to Back-End Development with hands-on Projects and real-world examples. This course enables you to build scalable, efficient, dynamic web applications that stand out. Ready to become an expert in Full-Stack? Enroll Now and Start Creating the Future!
The above is the detailed content of How to Import config.php File in a PHP Script?. For more information, please follow other related articles on the PHP Chinese website!