skip to Main Content

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


  1. 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.

    <?php
    $config =  [
        'db_name' => 'db_name',
        'password' => 'password',
         ........
    ];
    

    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.

    Login or Signup to reply.
  2. In a nutshell, this is possible if you assign the config array to a variable instead of return:

    <?php
    
    $config = [
        'db_name' => 'db_name',
        'password' => 'password',
         ........
    ];
    

    Then, you can access the $config everywhere this file is included. You don’t need file_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:

    {
        "db_name": "some_name",
        "password": "some_password",
        ...
    }
    

    then, in your code:

    $filename = 'config.json';
    $parsed = json_decode(file_get_contents($filename), true);
    echo $parsed['db_name'];  // -> some_name
    echo $parsed['password']; // -> some_password
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search