How to read PHP file which contains array - php

I have a php file, config.php and it contains following code.
$_config = array(
'db' => array(
'mysolidworks' => array(
'host' => 'localhost',
'username' => 'netvibes',
'password' => 'frakcovsea',
'dbname' => 'sw_mysolidworks',
'driver_options' => array(
PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true
)
)
)
);
I want to read this file into a variable and then read the variable like an array. Could anyone help?

Simply using PHP the way it's meant to work:
include('config.php');
echo $_config['db']['mysolidworks']['host'];

you can use any of the following
<?php
$file_loc = 'SomeDir/config.php';
require $file_loc; //Throw a fatal if it's not found
require_once $file_loc; //If this might be called somewhere else in your script, only include it once
include $file_loc; //Include but just show a warning if not found
include_once $file_loc; //Include if not already included and throw warning if not
?>

Related

Escaping a PHP function as an Array value

I'm working on a Drupal 8 starter kit with Composer, similar to drupal-composer/drupal-project.
In my post-install script, I want to re-generate a settings.php file with my custom values.
I've seen that can be done with the drupal_rewrite_settings function.
For example, I'm rewriting the config_sync_directory value like that :
require_once $drupalRoot . '/core/includes/bootstrap.inc';
require_once $drupalRoot . '/core/includes/install.inc';
new Settings([]);
$settings['settings']['config_sync_directory'] = (object) [
'value' => '../config/sync',
'required' => TRUE,
];
drupal_rewrite_settings($settings, $drupalRoot . '/sites/default/settings.php');
Problem is I want my Drupal 8 project to have a Dotenv so the maintainers don't have to modify the settings.php but only a .env file in the root folder of the project. To make it work, my settings.php must look like this :
$databases['default']['default'] = [
'database' => getenv('MYSQL_DATABASE'),
'driver' => 'mysql',
'host' => getenv('MYSQL_HOSTNAME'),
'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
'password' => getenv('MYSQL_PASSWORD'),
'port' => '',
'prefix' => '',
'username' => getenv('MYSQL_USER'),
];
$settings['trusted_host_patterns'] = explode(',', '^'.getenv('SITE_URL').'$');
As you can see, the values are replaced by PHP functions, and I can't see a good way to print those values, to the point I'm not even sure that's possible.
So my question is : is it possible to escape a PHP function as an Array value when declaring this variable ?
Looks like it's not possible because of the way the Drupal function works.
Solution 1 by #misorude
Using the drupal_rewrite_settings function, we can add the value of settings as a String, like this :
$settings['settings']['trusted_host_patterns'] = (object) [
'value' => "FUNC[explode(',', '^'.getenv('SITE_URL').'$')]",
'required' => TRUE,
];
And after that, we can replace all occurrences of "FUNC[***]" by *** directly in the settings.php file.
Solution 2
Put all your settings in a separate file. Example here, a custom.settings.php file :
if (getenv('DEBUG') == 'true') {
$settings['container_yamls'][] = DRUPAL_ROOT . '/sites/dev.services.yml';
$config['system.performance']['css']['preprocess'] = FALSE;
$config['system.performance']['js']['preprocess'] = FALSE;
}
$databases['default']['default'] = [
'database' => getenv('MYSQL_DATABASE'),
'driver' => 'mysql',
'host' => getenv('MYSQL_HOSTNAME'),
'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
'password' => getenv('MYSQL_PASSWORD'),
'port' => '',
'prefix' => '',
'username' => getenv('MYSQL_USER'),
];
$settings['trusted_host_patterns'] = explode(',', '^'.getenv('SITE_URL').'$');
$settings['file_private_path'] = 'sites/default/files/private';
$settings['config_sync_directory'] = '../config/sync';
Then we can copy the default.settings.php and add our custom settings.
$fs = new Filesystem();
$settings_generated = $drupalRoot . '/sites/default/settings.php';
$settings_default = $drupalRoot . '/sites/default/default.settings.php';
$settings_custom = $drupalRoot . '/../includes/custom.settings.php';
$fs->remove($settings_generated);
$fs->dumpFile($settings_generated, file_get_contents($settings_default) . file_get_contents($settings_custom));
There's also a appendToFile method that seems way better than dumping a new file with dumpFile, but it was not working unfortunatly.

PHP connection Wamp+Solr

I am trying to setup and test a connection using php.
Below you will notice I have not defined base, which will be my home directory for the 'require_once'. My question is regarding what needs to be on the line for require once?
<?php
define('base',
require_once( 'C:\Program Files\Solr\solr-7.5.0\server\solr\sqltest' );
$options = array
(
'hostname' => 'localhost',
'login' => 'root',
'password' =>'',
'port' => '8983',
'path' => 'C:\Program Files\Solr\solr-7.5.0\server\solr\sqltest'
);
$client = new SolrClient( $options );
if ( ! $solr->ping() ) {
echo 'Solr service not up dude.';
exit;
}
?>
My local server was setup using Wamp. Many pages I have looked at for help use another service and their request_once is like this:
require_once( 'Apache/Solr/Service.php' );
this leads me to believe mine should point to something in my wamp directory
Turns out I am missing the solr php client
https://github.com/PTCInc/solr-php-client

What is the best way to edit a settings file containing a global named config in php

I've got the file 'init.php'. This one is being used to start the session, set some settings and that sort of stuff. I call to this file using this line:
require_once 'core/init.php';
This works perfectly in my opinion. Now, I've written the following script so that it becomes very easy to call a setting in the init.php file.
class Config {
public static function get($path = null) {
if ($path){
$config = $GLOBALS['config'];
$path = explode('/', $path);
foreach($path as $bit) {
if(isset($config[$bit])) {
$config = $config[$bit];
}
}
return $config;
}
return false;
}
}
So now I can use this line of code in my other pages to use the setting:
Config::get('settings/main_color')
This is very easy of course. But now I'd like to edit a setting without having to change the file myself. It should all be done by scripts in the browser. The rest of my init.php settings global looks like this:
$GLOBALS['config'] = array(
'mysql' => array(
'host' => 'localhost:3307',
'username' => 'root',
'password' => 'usbw',
'db' => 'webshop'
),
'remember' => array(
'cookie_name' => 'hash',
'cookie_expiry' => 604800
),
'sessions' => array(
'session_name' => 'user',
'token_name' => 'token'
),
'settings' => array(
'main_color' => '#069CDE',
'front_page_cat' => 'Best Verkocht,Populaire Producten',
'title_block_first' => 'GRATIS verzending van €50,-',
'title_block_second' => 'Vandaag besteld morgen in huis!',
),
'statics' => array(
'header' => 'enabled',
'title_block' => 'enabled',
'menu' => 'enabled',
'slideshow' => 'enabled',
'left_box' => 'enabled',
'email_block' => 'enabled',
'footer' => 'enabled',
'keurmerken' => 'enabled',
'copyright' => 'enabled'
)
);
What I hope for is a solution like this:
Config::update('settings/main_color','blue')
What is the best way to achieve this? Use str_replace and replace the word in the file? I hope there's a better way of doing this, and I'd be very pleased if you could help me out.
EDIT: (my complete init.php file)
<?php
session_start();
define('DS',DIRECTORY_SEPARATOR);
$GLOBALS['config'] = json_decode(__DIR__.DS.'prefs.json', true);
spl_autoload_register(function($class) {
require_once 'classes/' . $class . '.php';
});
require_once 'functions/sanitize.php';
require_once 'functions/statics.php';
require_once 'functions/pagination.php';
if(Cookie::exists(Config::get('remember/cookie_name')) && !Session::exists(Config::get('sessions/session_name'))) {
$hash = Cookie::get(Config::get('remember/cookie_name'));
$hashCheck = DB::getInstance()->get('users_session', array('hash', '=', $hash));
if($hashCheck->count()) {
$user = new User($hashCheck->first()->user_id);
$user->login();
}
}
$_link = DB::getConnected();
$url_parts = explode('/',$_SERVER['REQUEST_URI']);
$current = $url_parts[count($url_parts)-2];
if($current == 'page'){
$_SESSION['location'] = 1;
}
else{
$_SESSION['location'] = 0;
}
This is somewhat opinion-based, but I use a json or xml file that the config file parses. The update would call the file, parse it then resave it.
/core/init.php
$GLOBALS['config'] = json_decode(__DIR__.DS.'prefs.json', true);
/core/prefs.json
{"mysql":{"host":"localhost:3307","username":"root","password":"usbw","db":"webshop"},"remember":{"cookie_name":"hash","cookie_expiry":604800},"sessions":{"session_name":"user","token_name":"token"},"settings":{"main_color":"#069CDE","front_page_cat":"Best Verkocht,Populaire Producten","title_block_first":"GRATIS verzending van €50,-","title_block_second":"Vandaag besteld morgen in huis!"},"statics":{"header":"enabled","title_block":"enabled","menu":"enabled","slideshow":"enabled","left_box":"enabled","email_block":"enabled","footer":"enabled","keurmerken":"enabled","copyright":"enabled"}}
Pseudo-code for your update:
class Config
{
public static function update($path,$value)
{
# Fetch the file and convert it to json
$file = json_decode(file_get_contents(CONFIG_PATH),true);
# Do some code that will update the value....
# Save file back
file_put_contents(CONFIG_PATH,json_encode($data));
# Call your prefs to GLOBALS function here so the settings
# are updated in your global array
}
}

PHP crashing my webpage for unknown reason

For some reason, PHP crashes when I try to open a page. I am using localhost:82 in Uniform Server Zero.
The code is as follows:
index.php
<?php
require_once 'core/init.php';
$db = new DB();
?>
core/init.php
<?php
session_start();
$GLOBALS['config'] = array(
'mysql' => array(
'host' => 'localhost:82',
'username' => 'root',
'password' => 'password',
'db' => 'forum'
),
'remember' => array(
'coolie_name' => 'hash',
'cookie_expiry' => 604800
),
'session' => array(
'session_name' => 'user'
)
);
spl_autoload_register(function($class) {
require_once '../classes/' . $class . '.php';
});
require_once '../functions/sanitize.php';
?>
functions/sanitize.php
<?php
function escape($string) {
return htmlentities($string, ENT_QUOTES, 'UTF-8');
}
?>
I tried adding the text test before and after each of the php tags, and it seems that only index.php crashes (It displays the test text before the php tags, but not after - even in View Source mode).
The browser I am using is the Aurora dev version, and I am getting the code from this youtube tutorial.

PHP - the browser doesn't display echo'ed values after "require_once" command, why?

I am new to PHP and I've been following one tutorial where I am building a user registration system using OOP in PHP. I've been digesting the code quite well and learning fast, but encountered one minor (but frustrating) problem.
My web browser doesn't want to display echo'ed values if the echo command follows require_once command unless I add an extra echo '<br'> before the values that I want to echo. This is how it looks like:
<?php
require_once 'core/init.php';
echo Config::get('mysql/host');
This code above WILL NOT echo the last line in the browser.
<?php
require_once 'core/init.php';
echo '<br>';
echo Config::get('mysql/host');
The code above WILL echo the last line in the browser.
Why do I need to add echo '<br>' to display?
I will be very grateful for your advice.
Best,
Lucas
The code in core/init.php looks like that:
<?php
session_start();
$GLOBALS['config'] = array(
'mysql' => array(
'host' => '127.0.0.1',
'username' => 'root',
'password' => '',
'db' => 'lr'
),
'remember' => array(
'cookie_name' => 'hash',
'cookie_expiry' => 604800
),
'session' => array(
'session_name' => 'user'
)
);
spl_autoload_register(function ($class) {
require_once 'classes/' .$class . '.php';
});
require_once '/../functions/sanitize.php';
echo $config['mysql']['host'];
I've tested the code and everything works fine. By the way you should consider not using $GLOBALS in your code.
Below the full working code:
index.php
<?php
require_once 'core/init.php';
echo Config::get('mysql/host');
core/init.php
<?php
session_start();
$GLOBALS['config'] = array(
'mysql' => array(
'host' => '127.0.0.1',
'username' => 'root',
'password' => '',
'db' => 'lr'
),
'remember' => array(
'cookie_name' => 'hash',
'cookie_expiry' => 604800
),
'session' => array(
'session_name' => 'user'
)
);
spl_autoload_register(function ($class) {
require_once 'classes/' .$class . '.php';
});
require_once '/../functions/sanitize.php';
echo $config['mysql']['host'];
functions/sanitize.php
<?php
function escape ($string)
{
return htmlentities($string, END_QUOTES, 'UTF-8');
}
classes/Config.php
<?php
class Config {
static function get($what) {
$what = explode ('/', $what);
echo $GLOBALS['config'][$what[0]][$what[1]];
}
}
Result of launching index.php file in browser is:
127.0.0.1127.0.0.1
as expected (127.0.0.1 is being displayed 2 times without space between)

Categories