Question

So I correct have a script that uses a config.ini for connecting to the database and with other options, but I have a script that I created which is a config.php and uses the same database. There are variables (database host/username/password) that I would like to pull from the config.ini file and read them inside of the config.php. Is this possible?

Was it helpful?

Solution 2

From your question & later comments I think that you could be wanting to read an ini file from within two php scripts. There is nothing stopping you doing this, it would be possible to read the file from within both scripts, but we do not want to repeat the code in each script.

So I would suggest you need three scripts, something along these lines:

database.php   // the original which is currently reading from config.ini
config.php     // the new script which you also want to read the config.ini
readconfig.php // does the reading of the ini 

The readconfig.php should have a public function that does something like:

public function ReadDbSettings($inifile, $host, $user, $password)
{
       // do the mechanics of reading the ini, use your existing code which is working

       // set the supplied parameters which values from the ini
       $host = $ini_array['HOST'];
       ...

       return TRUE;  // the settings were read
}

In terms of the actual mechanics of reading the ini one option is to use parse_ini_file to read in the contents into an array. A contrived example:

    $ini_array = parse_ini_file("my.ini");
    if (empty($ini_array['IniSetting']))
    {
        $this->variable = 'defaultvalue';
    }
    else
    {
        $this->variable = $ini_array['IniSetting'];
    }

OTHER TIPS

Okay after pulling my head out of my * i was able to figure it out!

This is what my config.php file looks like:
<? $ini_array = parse_ini_file('config.ini'); $host = $ini_array['database.params.host']; $username = $ini_array['database.params.username']; $password = $ini_array['database.params.password']; $db_name = $ini_array['database.params.dbname']; mysql_connect($host,$username,$password,$db_name) or die('Could not connect to MySQL'); mysql_select_db($db_name) or die ('could not open db'.mysql_error()); ?>

and it connects fantastically!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top