I am creating a reusable app, which requires some configurations stored in config.php
. This configuration file does not have any function, but the configuration are returned as an array, eg
<?php
return [
'db_name' => 'db_name',
'password' => 'password',
........
];
I was hoping to create a function which includes this config file, and get each config set. An example is laravel config()
function which returns a configuration value. Is there any way to acheive this?
I have tried
$filename = 'config.php';
include $filename;
$contents[] = file_get_contents($filename);
but this just gets whatever is in the file as a string.
2
Answers
Edit I have just followed the link from where your question was closed (Creating a config file in PHP) and was interested to find out that the approach you have taken (using
return
) does appear to be valid and is recommended there. So, don’t let me put you off that. I always do it like I explain below:In config.php get rid of
return
and assign the array to a variable.Then use
require_once './config.php';
to get it into any .php script you like. You can then use $config in that script.Note the path to config.php must be correct. I have assumed above that it is in the same directory as the file you are importing it into with
require_once
so the path used was./config.php
. If config.php was in the parent directory of the file using it then the path would have had two dots:../config.php
.In a nutshell, this is possible if you assign the config array to a variable instead of
return
:Then, you can access the
$config
everywhere this file is included. You don’t needfile_get_contents
in this case.But please note that this solution adds a potential vulnerability to your application, literally allowing to execute an arbitrary code provided inside
config.php
.Instead of storing the configuration in a php file, consider using the dotenv component, or if this too complex for your app, use a harmless format such as JSON or YAML:
config.json:
then, in your code: