TYPO3 own file for database connection - php

I tried to take out my database connection from the LocalConfiguration. But it doesn't work on this way. Do you have any ideas how i can realize it. Here what i tried to make it work:
LocalConfiguration.php:
<?php
include_once 'databaseConn.php';
return [
'BE' => [
'debug' => false,
'explicitADmode' => 'explicitAllow',
'installToolPassword' => '$P$CcKE/MYkjKWDzNWsnVZhMBDAttVVrf.',
'loginSecurityLevel' => 'rsa',
],
and in the databaseConn.php:
<?php
$TYPO3_CONF_VARS['DB']['database'] = 'db_name';
$TYPO3_CONF_VARS['DB']['host'] = 'localhost';
$TYPO3_CONF_VARS['DB']['password'] = 'password';
$TYPO3_CONF_VARS['DB']['socket'] = '';
$TYPO3_CONF_VARS['DB']['username'] = 'usr_name';
Hope you can help me.
thanks
Chris

Create a file called AdditionalConfiguration.php in same directory. You can override every value there by addressing it directly
$GLOBALS['TYPO3_CONF_VARS']['DB']['database'] = 'custom';
You can also check the ApplicationContext by $context = GeneralUtility::getApplicationContext()->__toString(); which can be set in a .htaccess or vhost config

Use the following code in AdditionalConfiguration.php:
$configurationSettings = array();
#include_once(__DIR__.'/DatabaseCredentials.php');
#include_once(… some other files …);
if (is_array($configurationSettings)) {
foreach ($configurationSettings as $path => $value) {
$GLOBALS['TYPO3_CONF_VARS'] = \TYPO3\CMS\Core\Utility\ArrayUtility::setValueByPath($GLOBALS['TYPO3_CONF_VARS'], $path, $value);
}
}
unset($configurationSettings);
then set your database credentials in DatabaseCredentials.php:
$configurationSettings = array_merge($configurationSettings, array(
'DB/database' => 'local_database',
'DB/username' => 'local_username',
'DB/password' => 'secret'
));
and you're done.

It is better that you add your database connection code into "LocalConfiguration.php".
return array(
'BE' => array(
'debug' => false,
'explicitADmode' => 'explicitAllow',
'installToolPassword' => '$P$CcKE/MYkjKWDzNWsnVZhMBDAttVVrf.',
'loginSecurityLevel' => 'rsa',
),
'DB' => array(
'database' => 'db_name',
'extTablesDefinitionScript' => 'extTables.php',
'host' => 'localhost',
'password' => 'password',
'socket' => '',
'username' => 'username',
),

Related

how to make multiple connection to database using php and mysql

I have an associative array contain multiple database configuration and I want to make all connection to database in this array
$dbconfig = array(
'servername' => array('localhost','localhost'),
'username' => array('root1','root2'),
'password' => array('p1','p2'),
'db' => array('db1','db2'),
);
$conn = mysqli_connect($dbconfig['servername'], $dbconfig['username'], $dbconfig['password'], $dbconfig['db']);
You should transpose your array structure to this:
<?php
$dbconfig = array(
array(
'servername' => 'localhost',
'username' => 'root1',
'password' => 'p1',
'db' => 'db1'
),
array(
'servername' => 'localhost',
'username' => 'root2',
'password' => 'p2',
'db' => 'db2'
)
);
Because this allows you to more easily iterate through the array:
for($i = 0; $i < sizeof($dbconfig); $i++) {
$conn[$i] = mysqli_connect($dbconfig[$i]['servername'], $dbconfig[$i]['username'], $dbconfig[$i]['password'], $dbconfig[$i]['db']);
}

zf2 dynamic database connection (with parameters)

I'm trying to create a ZF2 application with multiple databases. Based on a user, the database should be dynamically set.
Right now I've the following:
database.local.php
return array(
'db' => array(
'adapters' => array (
'master_db' => array(
'driver' => 'Pdo',
'dsn' => 'mysql:dbname=master_db;host=localhost',
'driver_options' => array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''
),
'username' => 'USERNAME',
'password' => 'PASSWORD'
),
'tentant_db' => array(
'driver' => 'Pdo',
'dsn' => 'mysql:dbname=tenant_db;host=localhost',
'driver_options' => array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''
),
'username' => 'USERNAME',
'password' => 'PASSWORD'
),
)
),
'service_manager' => array(
'abstract_factories' => array(
'Zend\Db\Adapter\AdapterAbstractServiceFactory',
)
),
);
For test purposes I've created a form that has a method to fetch some data and put it in a select box. The code to get the database connection is shown in the code below.
MyController.php (in some module)
//... some code
public function someAction(){
$dbAdapter = $this->getServiceLocator()->get('tentant_db');
$form = new AddEolConnectorForm($dbAdapter);
$viewModel = new ViewModel(array(
'form' => $form
));
return $viewModel;
}
//... some more code
My question is, how can I dynamically set the dbname for the tentant_db adapter in my controller (or module)?
Thanks for your help.
The config merge event is one of zend newer event's I believe. It triggers when zend is mergin the config array's which is perfect for the problem you are facing since you can override some array key's dynamically.
public function onMergeConfig(ModuleEvent $e)
{
$configListener = $e->getConfigListener();
$config = $configListener->getMergedConfig(false);
// I'm actually not sure if you have the route match here otherwise you may have to
// use some other method to retrieve the url.
$match = $e->getRouteMatch();
switch ($match) {
case 'first-dependency':
$config['db']['adapter'] => array(
'driver' => 'Pdo',
'dsn' => 'mysql:dbname=master_db;host=localhost',
'driver_options' => array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''
),
'username' => 'USERNAME',
'password' => 'PASSWORD',
),
break;
case 'second-dependency':
$config['db']['adapter'] => array(
'driver' => 'Pdo',
'dsn' => 'mysql:dbname=tenant_db;host=localhost',
'driver_options' => array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''
),
'username' => 'USERNAME',
'password' => 'PASSWORD',
),
break;
// Pass the changed configuration back to the listener:
$configListener->setMergedConfig($config);
}
Based on the above answer I've created to following:
Module.php
class Module implements AutoloaderProviderInterface
{
public function init(ModuleManager $moduleManager)
{
$events = $moduleManager->getEventManager();
// Registering a listener at default priority, 1, which will trigger
// after the ConfigListener merges config.
$events->attach(ModuleEvent::EVENT_MERGE_CONFIG, array($this, 'onMergeConfig'));
}
public function onMergeConfig(ModuleEvent $e)
{
$db = $this->getTentantDb();
$configListener = $e->getConfigListener();
$config = $configListener->getMergedConfig(false);
$config['db']['adapters']['tenant_db']['dsn'] = 'mysql:dbname='. $db .';host=localhost';
$configListener->setMergedConfig($config);
}
// Some more code
public function getTenantDb(){
$tenant_db = 'tenant_12345'
return $tenant_db;
}
}
I don't know if it is the best solution, but the above code is working. I think the next steps should be to put the code in a generic module or something so I can access it from all my modules.

SSL error in CURL call to Twitter API

Below is some code of my controller (dont worry, de keys are fake). Im using the ZendService\Twitter\Twitter module. Almost everything is working only the last error is a bit strange and i can not figure it out:
Unable to enable crypto on TCP connection api.twitter.com: make sure the "sslcafile" or "sslcapath" option are properly set for the environment.
As you can see i the code below of my controller, you can see that both the Verify of Peer and Host are set to false. The adapter is already set to Curl instead of HTTP.
<?php
namespace Twitter\Controller;
use QDCore\Controller\AbstractController;
use Zend\Mvc\MvcEvent;
use Zend\View\Model\JsonModel;
use ZendService\Twitter\Twitter;
class GetController extends AbstractController
{
protected $instance;
public function onDispatch(MvcEvent $e)
{
$config = array(
'access_token' => array(
'token' => '1024003resagsDQGyVC5YZ23423PpBNOwefS',
'secret' => 'oES8Jergewagewahsh2hTqrYGDJo',
),
'oauth_options' => array(
'consumerKey' => 'QY360Nersehr234gg4aV2pw',
'consumerSecret' => 'eEfgdagewa0Hkt4z6nCqHPY1M4wwuubY',
),
'username' => 'myusername',
'http_client_options' => array(
'adapter' => 'Zend\Http\Client\Adapter\Curl',
'curloptions' => array(
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_SSL_VERIFYPEER => false,
),
),
);
$this->instance = new Twitter($config);
return parent::onDispatch($e);
}
public function indexAction()
{
$result = new JsonModel(array('message' => 'No valid function call made'));
return $result;
}
public function usertimelineAction()
{
$options = array(
'user_id' => 'myaccountname',
'count' => 30,
);
$twitter = new Twitter($options);
$response = $twitter->statuses->userTimeline();
var_dump($response);
die;
return new JsonModel($response);
}
}
Hope that someone has an idea on how to fix it. My main domain is not running on SSL and is not going to be.
Thanks
NEVER set verify host or peer verification to false, unless you know what you are doing!
You have to point curl to your certification bundle. For Linux (Debian based systems) that is etc/ssl/certs. You could set that as "sslcapath" variable:
'http_client_options' => array(
'adapter' => 'Zend\Http\Client\Adapter\Curl',
'curloptions' => array(
'sslcapath' => '/etc/ssl/certs',
),
),
Because the path varies between systems, it's good to have it as an option set in your config/autoload/global.php file which users could change with a local.php configuration. In your config:
'http_client' => array(
'options' => array(
'sslcapath' => '/etc/ssl/certs',
),
),
Then your code becomes:
public function onDispatch(MvcEvent $e)
{
$app = $e->getApplication();
$sm = $app->getServiceManager();
$cnf = $sm->get('Config');
$config = array(
'access_token' => array(
'token' => '1024003resagsDQGyVC5YZ23423PpBNOwefS',
'secret' => 'oES8Jergewagewahsh2hTqrYGDJo',
),
'oauth_options' => array(
'consumerKey' => 'QY360Nersehr234gg4aV2pw',
'consumerSecret' => 'eEfgdagewa0Hkt4z6nCqHPY1M4wwuubY',
),
'username' => 'myusername',
'http_client_options' => array(
'adapter' => 'Zend\Http\Client\Adapter\Curl',
'curloptions' => $cnf['http_client']['options'],
),
);
$this->instance = new Twitter($config);
return parent::onDispatch($e);
}
I had the same exact problem and found this on Google. I understood I should either disable CURLOPT_SSL_VERIFYHOST and CURLOPT_SSL_VERIFYPEER or specify the correct path to the local certificates, but didn't know how to do that.
This answer has helped me a lot:
$config = array(
'callbackUrl' => 'http://example.com/callback.php',
'siteUrl' => 'http://twitter.com/oauth',
'consumerKey' => 'myConsumerKey',
'consumerSecret' => 'myConsumerSecret'
);
$consumer = new ZendOAuth\Consumer($config);
// this is the key:
$adapter = new \Zend\Http\Client\Adapter\Curl();
$adapter = $adapter->setCurlOption(CURLOPT_SSL_VERIFYHOST, false);
$adapter = $adapter->setCurlOption(CURLOPT_SSL_VERIFYPEER, false);
$httpClient = $consumer->getHttpClient();
$httpClient->setAdapter($adapter);
// now finally fetch a request token
$token = $consumer->getRequestToken();

Apache Solr with Php

I am trying to setup apache solr search for one of my project. I have installed solr 3.6 in my development server and it is reachable with
http://127.0.0.1:8080/solr/admin/
I tried to put the sample application available in php manual but it is setting username and password for solr. I am not sure where can I get this information from. I have also tried below code from net but I was getting 500 error whenever I run it
$options = array (
'hostname' => '127.0.0.1',
);
//$client = new SolrClient($options, "4.0"); // use 4.0 for any version of Solr 4.x, ignore this parameter for previous versions
$doc = new SolrInputDocument();
$doc->addField('id', 100);
$doc->addField('title', 'Hello Wolrd');
$doc->addField('description', 'Example Document');
$doc->addField('cat', 'Foo');
$doc->addField('cat', 'Bar');
$response = $client->addDocument($doc);
$client->commit();
/* ------------------------------- */
$query = new SolrQuery();
$query->setQuery('hello');
$query->addField('id')
->addField('title')
->addField('description')
->addField('cat');
$queryResponse = $client->query($query);
$response = $queryResponse->getResponse();
print_r( $response->response->docs );
Please help
your solr version is 3.6 so you should assign $client = new SolrClient($options);
$client = new SolrClient($options, "4.0"); // I see that in your code you commented this line which is required thinking that it is only for solt 4.x in your case, you should uncomment it and only remove the "4.0" in order to create a client.
To create a client :
$options = array (
'host' => "localhost",
'port' => 8983, //port is required
'path' => '/solr/collection1', //collection1 or core are mandatory it can be just /solr/
);
$client = new SolrClient($options); //for solr 3.x
According to the example code, you are not setting the port in your $options array. Should be:
var $options = array(
'hostname' => '127.0.0.1',
'port' => '8080',
);
That could be the cause of the 500 error.
you need to add 3 things host, port, and webapp. I hope you have included the service.php file in that.
var $options = array(
'hostname' => '127.0.0.1',
'port' => '8080', //Port number where solr runs.
'webapp' => '/solr/', //path of the webapp.
);
Master site configuration
For settings.php file in your master site you do not have to change much. Leave your $databases array as it as. Master site will store all the user names, passwords, and sessions.
For settings.php file in your master site you do not have to change much. Leave your $databases array as it as. Master site will store all the user names, passwords, and sessions.
$databases = array(
'default' =>
array(
'default' =>
array(
'database' => 'drupal1',
'username' => 'username',
'password' => 'password',
'host' => 'localhost',
'port' => '',
'driver' => 'mysql',
'prefix' => '',
),
),
);
Slave sites configuration
The slave sites shall be connected to the Master site's database for certain tables, specially the ones that include user information. For settings.php file in your slave sites you need to specify master site database and call its users and other tables. We can do so by adding configuration settings within the "prefix" key of the $databases array.
$databases = array(
'default' =>
array(
'default' =>
array(
'database' => 'drupal2',
'username' => 'username',
'password' => 'password',
'host' => 'localhost',
'port' => '',
'driver' => 'mysql',
'prefix' => array(
'default' => 'drupal2.',
'users' => 'drupal1.',
'sessions' => 'drupal1.',
'role' => 'drupal1.',
'authmap' => 'drupal1.',
'users_roles' => 'drupal1.',
),
),
),
);
For more detailed instruction visit - How to set up and use Apache Solr in php

Redis error "Connection read timed out" during caching

I have Zend Framework project and I decided to use Rediska as Redis client.
Rediska has cache backend adapter for ZF - Rediska_Zend_Cache_Backend_Redis.
I fetch from DB collection of objects and try to save it in cache but get error: Connection read timed out. My example of code:
$rediskaOptions = array(
'name' => 'cache',
'namespace' => 'Cache_',
'servers' => array( 'cache' => array(
'host' => Rediska_Connection::DEFAULT_HOST,
'port' => Rediska_Connection::DEFAULT_PORT,
'password' => 'qwerty'
)
)
);
$cache = Zend_Cache::factory('Core', 'Rediska_Zend_Cache_Backend_Redis',
array('lifetime' => NULL, 'automatic_serialization' => true),
array('rediska' => $rediskaOptions), false, true
);
$cacheId = 'news_main';
if (!($topics = $cache->load($cacheId))) {
$topics = DAOFactory::getInstance()->getTopicDAO()->fetchTopic(1);
$cache->save($topics, $cacheId);
}
Size of content after serialization is 26787 bytes.
Maybe Redis have size limitations for sending?
If it helps, I am using Rediska with ZF as well. Here is how I set it up.
$options = array(
'servers' => array(
array( 'host' => '127.0.0.1',
'port' => 6379,
'alias' => 'cache'
),
//'name' => 'cache',
//'namespace' => 'Cache_'
)
);
$rediska = new Rediska($options);
$frontendOptions = array('automatic_serialization' => true);
$backendOptions = array('rediska' => $rediska);
$cache = Zend_Cache::factory( 'Core',
'Rediska_Zend_Cache_Backend_Redis',
$frontendOptions,
$backendOptions,
false,
true
);
A difference I see is in the backend options. I point rediska to a rediska instance.

Categories