How do I set a variable in the configuration file setting.php and use it from code?
3 Answers
in settings.php:
$conf['yoursite_something'] = 5;
Then, in your code:
// Second argument is the default.
variable_get('yoursite_something', NULL);
Make sure to prefix the variables, either with the module you're using it in or with the site name.
Do note that it is not required to declare persistent variables in settings.php. You can simply call variable_get() from your code and define a default value in case the variable is not set. For instance, the following code will say hello on every page request as long as the 'mymodule_say_hello' variable is not explicitly set to 0
:
<?php
function mymodule_init() {
// Get the mymodule_say_hello variable or use 1 if it's not set.
if (variable_get('mymodule_say_hello', 1)) {
drupal_set_message('Hello world');
}
}
?>
If needed, your module could publish a form that allows the admin to turn of this feature (the system_settings_form function makes that really easy) or you could change the settings programmatically by calling variable_set('mymodule_say_hello', 0)
.
Drupal 8
In your settings.php:
$settings['foo'] = 'bar';
In your code:
use Drupal\Core\Site\Settings;
Settings::get('foo', 'mydefaultvalue');