Edit the array and save the file as a new php file - php

There is a file named default.Db.php just containing:
<?php
// OLD FILE
function get_DbConfig(){
$config = array (
'source' => 'array',
'host' => 'DATABASE_HOST',
'port' => 'DATABASE_PORT',
'username' => 'DATABASE_USER',
'password' => 'DATABASE_PASSWORD',
'database' => 'DATABASE_NAME'
);
return $config;
}
require_once './../Common/php/face.php';
?>
What is way to replace $config inside get_dbConfig with my own array? For example, an array where each key has a specific value. After replacing the values inside this array, I will rename the file to Db.php
<?php
// NEW FILE
function get_DbConfig(){
$config = array (
'source' => 'array',
'host' => 'localhost',
'port' => '3306',
'username' => 'foo',
'password' => 'bar',
'database' => 'foobar'
);
return $config;
}
require_once __DIR__.'./../Common/php/OperateDB/DbMgrInterface.php';
?>

I don't know why you want to do this way. There are better methods to achieve this. However, you could do the following:
try {
// Read the whole file into memory
$fileStr = file_get_contents('../default.Db.php');
// Replace each string with a valid value
$fileStr = str_replace('DATABASE_HOST', HOST, $fileStr);
$fileStr = str_replace('DATABASE_USER', USER, $fileStr);
$fileStr = str_replace('DATABASE_PASSWORD', PASSWORD, $fileStr);
$fileStr = str_replace('DATABASE_NAME', DB_NAME, $fileStr);
$fileStr = str_replace('DATABASE_PORT', PORT, $fileStr);
// Write the modified content
file_put_contents("../default.Db.php", $fileStr);
// Rename default.Db.php to Db.php
$isRenamed = rename('../default.Db.php','../Db.php');
if($isRenamed) {
require_once './../Db.php';
}
}catch(Exception $exc) {
}

First you have to pass argument in your function. after that when you call that function, at that time you have to pass your array in that and assign array value with assign variable.
<?php
function get_DbConfig($configdata){
$config = array (
'source' => $configdata ['array'],
'host' => $configdata['DATABASE_HOST'],
'port' => $configdata['DATABASE_PORT'],
'username' => $configdata['DATABASE_USER'],
'password' => $configdata['DATABASE_PASSWORD'],
'database' => $configdata['DATABASE_NAME']
);
return $config;
}
require_once './../Common/php/face.php';
?>

Related

Code works in php 5 but not php 7, returning single element of array from class function

This was working but now on php7, recent install, returns
"Array ( [host] => 127.0.0.1 [username] => root [password] => [db] => scaryminds ) 127.0.0.1 "
Am after 127.0.0.1 btw.
Relavent code
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];
}
print_r($config);
//return $config;
}
}
}
Calling routine line
echo Config::get('mysql/host'); // 127.0.0.1
MySQL details stored in an array from an include file
$GLOBALS['config'] = array(
'mysql' => array(
'host' => '127.0.0.1',
'username' => 'root',
'password' => '',
'db' => 'scaryminds'
),
So I guess the question is why the line $config = $config[$bit] is returning the entire array with the additional $bit appended rather than just returning $bit.

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 predis connect to Redis Sentinel

I've set up a new PHP predis connection to a redis server using the documented code. I can verify it's connected ok, but I don't know how to simply test if the connection exists.
$options = array(
'scheme' => 'tcp',
'host' => '127.0.0.1',
'port' => $port,
'instance' => 'myinstance',
'timeout' => '0.100' // possibly add this to connections?
);
$sentinels = [
"tcp://{$options['host']}:{$options['port']}?timeout={$options['timeout']}",
];
$connection = new Predis\Client($sentinels, [
'replication' => 'sentinel',
'service' => $options['instance'],
]);
if ($connection->isConnected() === true) {
// undocumented-- I don't think this works?
echo "connected";
} else {
echo "failed"; // this is what gets echoed
}
Is there a method to test if the connection is good short of actually reading / writing to it? isConnected() doesn't appear to work.
As suggested by #drot:
$options = array(
'scheme' => 'tcp',
'host' => '127.0.0.1',
'port' => $port,
'instance' => 'myinstance',
'timeout' => '0.100' // possibly add this to connections?
);
$sentinels = [
"tcp://{$options['host']}:{$options['port']}?timeout={$options['timeout']}",
];
$connection = new Predis\Client($sentinels, [
'replication' => 'sentinel',
'service' => $options['instance'],
]);
// do this:
$connection->connect();
if ($connection->isConnected() === true) {
// undocumented-- I don't think this works?
echo "connected";
} else {
echo "failed"; // this is what gets echoed
}

Cakephp set database timezone

I'm setting timezone to php and mysql to internacionalize my CakePHP application.
When the server receives a request from a client, before process request, it connects to a GeoIp location server and gets the Timezone. Then I use date_default_timezone_set() to set php timezone. The problem comes up when I want to set database timezone. Once Cakephp connected, I need to execute sql query like SET time_zone='-06:00'.
In /lib/Cake/Model/Datasource/Database/Mysql.php I can see at connect() function the following code:
try {
$this->_connection = new PDO(
$dsn,
$config['login'],
$config['password'],
$flags
);
$this->connected = true;
if (!empty($config['settings'])) {
foreach ($config['settings'] as $key => $value) {
$this->_execute("SET $key=$value");
}
}
} catch (PDOException $e) {
throw new MissingConnectionException(array(
'class' => get_class($this),
'message' => $e->getMessage()
));
}
There is a $config['settings'] array that can be configured to do it. But I don't know how to fill settings array and where it's the best place to do that.
What I need is modify default datasource config on-the-fly
You can add an additional key to config array located at app/Config/database.php like this:
public $default = array(
'datasource' => 'Database/Mysql',
'persistent' => false,
'host' => 'localhost',
'login' => 'db_user',
'password' => 'db_pass',
'database' => 'db_name',
'prefix' => '',
'settings' => array(
'time_zone' => "'+01:00'", // note the quotes!
)
);
Related: CakePHP switch database (using same datasource) on the fly?
I solved it in the following way.
First of all, adding setOptions() method into DATABASE_CONFIG class as follows:
public function setOptions ($datasource, array $options){
$this->{$datasource} = array_merge($this->{$datasource}, $options);
}
Afterwards, extending ConnectionManager class to initialize it:
class ConnectionManagerCustomConfig extends ConnectionManager
{
public static function initialize(){
self::_init();
}
}
Now I initialize the class and add new options:
ConnectionManagerCustomConfig::initialize();
$configClass = ConnectionManagerCustomConfig::$config;
$configClass->setOptions('default', array(
'settings' => array(
'time_zone' => $offset
)
));

CakePHP send email

I've got a problem with sending mail using CakePHP. Everythings giong well, but i didn't receive any single mail , i tired to send to 2 different emails .
//WebsitesController.php
App::uses('AppController','Controller');
App::uses('CakeEmail','Network/Email');
class WebsitesController extends AppController
{
public $helpers = array('Html','Form','Session');
public $components = array('Email','Session');
public function contact()
{
$this->set('dane', $this->Website->findById(4));
}
public function contact_email()
{ /* all data is taken from contact.ctp, I debuged all data below and it's correct */
$useremail = $this->data['Website']['useremail'];
$usertopic = $this->data['Website']['usertopic'];
$usermessage = $this->data['Website']['usermessage'];
$Email = new CakeEmail();
$Email->from(array($useremail => ' My Site'));
$Email->to('wigan#mail.com');
$Email->subject($usertopic); // all data is correct i checked several times
$Email->send($usermessage);
if($Email->send($usermessage))
{
$this->Session->setFlash('Mail sent','default',array('class'=>'alert alert-success'));
return $this->redirect(array('controller'=>'websites','action'=>'contact'));
}
$this->Session->setFlash('Problem during sending email','default',array('class'=>'alert alert-warning'));
}
}
//contact.ctp
<fieldset>
<?php
echo $this->Form->create('Website',array('controller'=>'websites','action'=>'contact_email'));
echo $this->Form->input('useremail',array('class'=>'form-control'));
echo $this->Form->input('usertopic',array('class'=>'form-control'));
echo $this->Form->input('usermessage',array('class'=>'form-control'));
echo $this->Form->submit('Send',array('class'=>'btn btn-default'));
echo $this->Form->end();
?>
</fieldset>
all seems to be fine, even if statement in function contact_email is approved.
configuration ( i'm working on localhost, xampp, netbeans 7.4)
public $smtp = array(
'transport' => 'Smtp',
'from' => array('site#localhost' => 'My Site'),
'host' => 'localhost',
'port' => 25,
'timeout' => 30,
'username' => 'user',
'password' => 'secret',
'client' => null,
'log' => false,
//'charset' => 'utf-8',
//'headerCharset' => 'utf-8',
);
try this, you didn't set the config
public function contact_email()
{ /* all data is taken from contact.ctp, I debuged all data below and it's correct */
$useremail = $this->data['Website']['useremail'];
$usertopic = $this->data['Website']['usertopic'];
$usermessage = $this->data['Website']['usermessage'];
$Email = new CakeEmail();
$Email->config('smtp')
->emailFormat('html')
->from($useremail)
->to('wigan#mail.com')
->subject($usertopic); // all data is correct i checked several times
if($Email->send($usermessage))
{
$this->Session->setFlash('Mail sent','default',array('class'=>'alert alert-success'));
return $this->redirect(array('controller'=>'websites','action'=>'contact'));
} else {
$this->Session->setFlash('Problem during sending email','default',array('class'=>'alert alert-warning'));
}
}
Please follow the steps:
step 1: In this file (app\Config\email.php)
add this:
public $gmail = array(
'transport' => 'Smtp',
'from' => array('site#localhost' => 'Any Text...'),
'host' => 'ssl://smtp.gmail.com',
'port' => 465,
'timeout' => 30,
'username' => 'youremail#example.com',
'password' => 'yourPassword',
'client' => null,
'log' => false,
//'charset' => 'utf-8',
//'headerCharset' => 'utf-8',
);
step 2: Add an email template (app\View\Emails\html\sample.ctp)
<body>
<h1>Email Testing: <?php echo $first_name?></h1>
</body>
step 3: Change the code in your method as shown below:
public function send_my_email() {
App::uses('CakeEmail', 'Network/Email');
$Email = new CakeEmail();
$Email->config('gmail'); //configuration
$Email->emailFormat('html'); //email format
$Email->to('receiveremail#ex.com');
$Email->subject('Testing the emails');
$Email->template('sample');//created in above step
$Email->viewVars(array('first_name'=>'John Doe' ));//variable will be replaced from template
if ($Email->send('Hi did you receive the mail')) {
$this->Flash->success(__('Email successfully send on receiveremail#ex.com'));
} else {
$this->Flash->error(__('Could not send the mail. Please try again'));
}
}

Categories