Use php to update joomla configuration file

Viewed 546

I want to be able to use php to set values in the Joomla 3.x configuration.php file.

I can get values easily enough with something like:

$config = new JConfig();
$dbprefix = $config->dbprefix;

I've searched but can't find any way of setting the value. I assume it's possible since joomla does it. I can read the whole file in and use php to search and replace but I'm hoping that Joomla has an API with a setter or similar to allow me to do it.

I've searched and searched but there is nothing that I can find

Help!

ta

I have also now tried adding a setter to the JConfig but that didn't seem to work!

public function setTestvar($testvar) { 
  $this->ftp_user = $testvar; 
}
1 Answers

Unfortunately I'm not familiar with Joomla! but I had a quick look at the source code on GitHub and there appears to be some functionality that does what you want in ConfigModelApplication::writeConfigFile() which takes a Joomla\Registry\Registry instance.

This class is defined in file administrator/components/com_config/model/application.php

I'm assuming you're using a recent version of Joomla! and I haven't tested this so YMMV.

Here's the method in question:

/**
 * Method to write the configuration to a file.
 *
 * @param   Registry  $config  A Registry object containing all global config data.
 *
 * @return  boolean  True on success, false on failure.
 *
 * @since   2.5.4
 * @throws  RuntimeException
 */
private function writeConfigFile(Registry $config)
{
    jimport('joomla.filesystem.path');
    jimport('joomla.filesystem.file');

    // Set the configuration file path.
    $file = JPATH_CONFIGURATION . '/configuration.php';

    // Get the new FTP credentials.
    $ftp = JClientHelper::getCredentials('ftp', true);

    $app = JFactory::getApplication();

    // Attempt to make the file writeable if using FTP.
    if (!$ftp['enabled'] && JPath::isOwner($file) && !JPath::setPermissions($file, '0644'))
    {
        $app->enqueueMessage(JText::_('COM_CONFIG_ERROR_CONFIGURATION_PHP_NOTWRITABLE'), 'notice');
    }

    // Attempt to write the configuration file as a PHP class named JConfig.
    $configuration = $config->toString('PHP', array('class' => 'JConfig', 'closingtag' => false));

    if (!JFile::write($file, $configuration))
    {
        throw new RuntimeException(JText::_('COM_CONFIG_ERROR_WRITE_FAILED'));
    }

    // Attempt to make the file unwriteable if using FTP.
    if (!$ftp['enabled'] && JPath::isOwner($file) && !JPath::setPermissions($file, '0444'))
    {
        $app->enqueueMessage(JText::_('COM_CONFIG_ERROR_CONFIGURATION_PHP_NOTUNWRITABLE'), 'notice');
    }

    return true;
}

Hope this helps :)

Related