How could read application.ini on controller using zend framework - php

I have these lines in my application.ini
how can I read user in my contrroler
resources.doctrine.dbal.connections.default.parameters.driver = "pdo_mysql"
resources.doctrine.dbal.connections.default.parameters.dbname = "zc"
resources.doctrine.dbal.connections.default.parameters.host = "localhost"
resources.doctrine.dbal.connections.default.parameters.port = 3306
resources.doctrine.dbal.connections.default.parameters.user = "root"
resources.doctrine.dbal.connections.default.parameters.password = "123456"
I use of this code but it retuens null
$bootstrap = Zend_Controller_Front::getInstance()->getParam('bootstrap');
$user = $bootstrap->getOption('user');
var_dump($user);
edit:
how may I read all of connections options ?

I think you should use
$this->getInvokeArgs('bootstrap');
For more info see this chapter in manual.
What about using
$conf = $bootstrap->getOption('resources');
$dbConf = $conf['doctrine']['dbal']['connections']['default']['parameters'];

How about something like:
$config = new Zend_Config_Ini(APPLICATION_PATH . '/configs/application.ini', APPLICATION_ENV);
$connectionParams = $config->resources->doctrine->connections;
Or during Bootstrap, create and save this $config object in the Bootstrap or in the Zend_Registry for later retrieval in your controller.

This goes in your controller.
$bootstrap = $this->getInvokeArg('bootstrap');
$appinidata = $bootstrap->getOptions();
$user=$appinidata['resources']['doctrine']['dbal']['connections']['default']['parameters'] ['user'];
This should print "root".
print_r($user);

To get to the Doctrine container resource, just use :
$bootstrap = $this->getInvokeArg('bootstrap');
$doctrine = $bootstrap->getResource('doctrine');
From there you can drill down to the user name of the default connection (you can specify the connection if needed, just pass the name of the connection in the call to getConnection) :
$username = $doctrine->getConnection()->getUsername();

In this case you should use Zend_Config_Ini class
$config = new Zend_Config_Ini('/path/to/config.ini','staging',$options);
second parameter is a section in INI file should be loaded ;
third parameter is the key to allow modify loaded file.
You can put out value user this way:
$config->resources->doctrine->dbal->connections->default->parameters->user;

you can set any variable using set method as following on index.php inside the public folder
Let
$config = 'test';
Zend_Registry::set('config', $config);
once the variable has been set then you can get on any controllers/models by following method
Zend_Registry::get('config');
Hop it Helps!!

Related

How to not reinstantiate a new cookie on each page load in CodeIgniter?

I was having some troubles with Sessions/Cookies in CodeIgniter. After investigating with Inspect Element more I've figured out my code is creating a new cookie every single time I load a page on my website. I cannot for the life of me figure out how to prevent this from happening/only assign a user one consistent cookie per session.
My Session settings are like so:
$config['sess_driver'] = 'files';
$config['sess_cookie_name'] = 'ci_session';
$config['sess_save_path'] = BASEPATH . 'Writable/sessions/';
$config['sess_match_ip'] = True;
$config['sess_time_to_update'] = 120;
$config['sess_regenerate_destroy'] = False;
$config['cookie_prefix'] = '';
$config['cookie_domain'] = '.myapp.com';
$config['cookie_path'] = '/';
$config['cookie_secure'] = False;
$config['cookie_httponly'] = False;
In addition I've given the /Writable/sessions/ folder the correct permissions and ownership. I think my configuration is fine (the cookies show up in the browser/seem to be working).
My question then, is how do I make it so that the cookie is kept consistent with the individual user on first log-in instead of creating a new cookie with missing data each time I load a page? My controller class (where I initialize the coookie) looks like this:
BaseController.php
class BaseController extends \CodeIgniter\Controller {
// Class vars set to null
public function __construct($request, $response, $logger = null) {
parent::__construct($request, $response, $logger);
error_reporting(E_ALL);
ini_set('display_errors', 1);
$this->db = \Config\Services::db();
$this->RefTypes = new RefTypesModel($this);
$this->url = new \CodeIgniter\HTTP\URI();
// This is the problematic code
if ($this->session == null) {
$this->session = \Config\Services::session();
$this->session->start();
}
$this->init();
}
}
Then in my other Controllers I have code that uses the session like so:
MyController.php
class MyController extends BaseController {
public function login() {
// Set data in cookie and then redirect to new page
$this->session->set('userId', $userId);
return redirect()->to('/dashboard');
}
public function dashboard() {
// This is where I run into a problem...
$test = $this->session->get('userId'); //Returns null
echo "<script type=\"text/javascript\">alert('$test');</script>";
}
}
Essentially, since PHP is a scripting language, each time I load a new page the code in BaseController.php is run which is then running the code to initialize the session again. I've tried using the database driver as well and that did not remedy the problem. Does anyone know of any workarounds to this or any way to have a "shared" instance of my session variable so that it'll be independent of my controllers? Thank you!! Any help is very much appreciated :)
EDIT: My /application/config/config.php appears to have no effect. I think this is because I'm on CI4 instead of CI3. I've been setting my Session settings explicitly right now. The code for that looks like this:
/system/Session/Session.php:
public function __construct(\SessionHandlerInterface $driver, $config) {
$this->driver = $driver;
$config->sessionSavePath = BASEPATH . 'Writable/sessions/';
$config->sessionMatchIP = True;
$config->cookieDomain = '.autoloapp.com';
$this->sessionDriverName = $config->sessionDriver;
$this->sessionCookieName = $config->sessionCookieName;
$this->sessionExpiration = $config->sessionExpiration;
$this->sessionSavePath = $config->sessionSavePath;
$this->sessionMatchIP = $config->sessionMatchIP;
$this->sessionTimeToUpdate = $config->sessionTimeToUpdate;
$this->sessionRegenerateDestroy = $config->sessionRegenerateDestroy;
$this->cookieDomain = $config->cookieDomain;
$this->cookiePath = $config->cookiePath;
$this->cookieSecure = $config->cookieSecure;
}
I managed to fix this (finally) but replacing all the /application files and all of the /shared/config files with files from the default CI4 framework. I was using CI3 files (shoutout to the dev before me) and updating these config files with the correct values fixed the problem. I also deleted the code in BaseController.php that was creating the session. Thanks to #DFriend for helping me figure out the problem!

Combining php strings

I have two files, one config.php and source.php in a subdirectory. In the config file I have something that looks like this
<?php
//app settings
$GLOBALS['app_url'] = 'http://www.website.com/subdirectory'; //ex:
//demo mode
$GLOBALS['demo_mode'] = 0; //possible values: 0 or 1
$GLOBALS['db_table']['sms'] = 'sms_numbers';
$GLOBALS['db_table']['sms_history'] = 'sms_history';
?>
In the config.php file, I have this string $GLOBALS['app_url'] = 'http://www.website.com/subdirectory'; for the base URL and I'd like to make it so that the base URL is automatically detected. I'd like to use something similar to this <?php echo "http://" . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI']; ?>. I'm using these files under different directories and that's why I'd like to combine them in order to make it automatic without me having to update the base URL manually every time I create a new subdirectory.
Also, inside config.php I have:
//Admin access
$GLOBALS['admin_username'] = 'admin';
$GLOBALS['admin_password'] = 'password';
These values are not in a database but a local file named source.php and I'd like to be able to update the values "admin" and "password" from this source.php file.
Inside the source.php file I guess I'd have to have something thta'd look like this: $username = 'admin';
I'm really sorry but I'm new and would like to learn this stuff. I appreciate any help I can get.
Thank you
Use global constants in config.php
define('APP_URL', 'http://www.website.com/subdirectory');
Then anywhere in the code you can do:
$path = APP_URL . "/path/to/file"
I dont recommend storing admin_username and admin_password as global variables or constants, instead you can create a class in your config.php that contains the values.
Config Example:
config.php
define('APP_URL','http://www.website.com/subdirectory');
define('DEMO_MODE',0); //possible values: 0 or 1
.....
class DB{
var $conn;
public function __construct()
{
$user = "admin";
$pass = "pass";
$host = "127.0.0.1";
$database = "database_name";
$this->conn = mysqli_connect($host, $user, $pass, $database);
}
}
Then in your index.php file you do:
require_once("config.php")
$db = new DB;
$conn = $db->conn();
....

How to access dynamic references from other container items?

How can I pass a dynamic dependency from one registered container definition to another? In this case, a generic Database object wants to inherit from a generic Config object. The twist is config is not static, but loaded depending on a given environment variable.
Config pertinent methods
public function __construct()
{
$configFile = 'example.config.yml';
$yamlParser = new Parser();
$reader = new Config\Reader($yamlParser);
$configYaml = $reader->parse(file_get_contents($configFile));
$config = new Config\Environment(getenv('SITE'), $configYaml);
$this->config = $config;
}
public function getEnvironmentConfig()
{
return $this->config;
}
Registering config is as simple as
$container->register('config', 'Config');
Database is currently added to the container as follows:
$container
->register('database', 'Database')
->addArgument($config->getEnvironmentConfig('Database', 'db.username'))
->addArgument($config->getEnvironmentConfig('Database', 'db.password'))
;
But I want to do something like
$container
->register('database', 'Database')
->addArgument(new Reference('config')->getEnvironmentConfig('Database', 'db.username'))
->addArgument(new Reference('config')->getEnvironmentConfig('Database', 'db.password'))
;
The $config in-PHP variable makes migrating from a PHP-built config impossible. I want to define the services in yaml force the container to:
Instantiate Config
Parse the config yaml file and create an environment-specific version
Return this on a call to getEnvironmentConfig
Is this possible?
This was solved by using the Expression Language Component
So you can easily chain method calls, for example:
use Symfony\Component\ExpressionLanguage\Expression;
$container->register('database', 'Database')
->addArgument(new Expression('service("config").getEnvironmentConfig("Database", "db.username")'));

How to write and use config files in Zend Framework 2

Hi,
In Zend Framwork 1, I used to have an application\configs\appsettings.xml, where I used to store params and values like hostnames for Rest API URLs, debug settings and other application specific settings for dev, test and prod environments. This registry was available to me across all controllers and models and was created in index.php
$applicationEnvironment = 'development';
$config = new Zend_Config_Xml( APPLICATION_PATH . '/configs/appsettings.xml',
$applicationEnvironment, true );
Zend_Registry::set( 'config', $config );
How do I achieve similar thing in Zend Framework 2?
Thanks
There is no such thing as a Registry in ZF2 because it is kind of an anti pattern. It's just a fancy substitution for global variables, which can cause all sort of unwanted side effects in your application.
In ZF2 you have the serviceManager and this allow to cleanly inject all your dependencies into your controllers/models/services. All config files in the config/autoload directory are automaticaly merged into one single array by ZF2 and you can retrieve this from the service manager using $serviceLocator->get('Config'). Whenever you need to use configuration in your controller just create a serviceFactory and inject the config.
class FooController
{
protected $config;
public __construct($config)
{
$this->config = $config;
}
public barAction()
{
//use $this->config
}
}
class Module
{
public function getControllerConfig()
{
return array(
'factories' => array(
'fooController' => function(ControllerManager $cm)
{
$sm = $cm->getServiceLocator();
$config = $sm->get('Config');
$controller = new FooController($config);
return $controller;
},
),
);
}
}
For sake of simplicity the factory above is defined as a closure, but I'd suggest to create a seperate factory class. There are many resources which explain how to do that.
In this example we are injecting the complete configuration, but depending on your use case it will generally be better to only inject the config keys you need.
Alternatively you can wrap certain config values into a dedicated config object with explicit getters and setters and inject this into your controller. Zend\StdLib\AbstractOptions can help you.
If you wish to work with config files and you dont have access to the Service Manager or you wish to write content to it, you can use Zend\Config
To read from, you can do something like:
$config = new Config(include 'config/autoload/my_amazing_config.global.php');
$details = $config->get('array_key')->get(sub_key)->toArray();
To write to, you can do:
// Create the config object
$config = new Zend\Config\Config(array(), true);
$config->production = array();
$config->production->webhost = 'www.example.com';
$config->production->database = array();
$config->production->database->params = array();
$config->production->database->params->host = 'localhost';
$config->production->database->params->username = 'production';
$config->production->database->params->password = 'secret';
$config->production->database->params->dbname = 'dbproduction';
$writer = new Zend\Config\Writer\Xml();
echo $writer->toString($config);
The class support ini, xml, phpArray, json, yaml
You can read more at:
http://framework.zend.com/manual/2.2/en/modules/zend.config.introduction.html

How do i remove a file from Rackspace's Cloudfiles with their api?

I was wondering how do i remove a file from Rackspace's Cloudfiles using their API?
Im using php.
Devan
Use the delete_object method of CF_Container.
Here is my code in C#. Just guessing the api is similar for php.
UserCredentials userCredientials = new UserCredentials("xxxxxx", "99999999999999");
cloudConnection = new Connection(userCredientials);
cloudConnection.DeleteStorageItem(ContainerName, fileName);
Make sure you set the container and define any sudo folder you are using.
$my_container = $this->conn->get_container($cf_container);
//delete file
$my_container->delete_object($cf_folder.$file_name);
I thought I would post here since there isn't an answer marked as the correct one, although I would accept Matthew Flaschen answer as the correct one. This would be all the code you need to delete your file
<?php
require '/path/to/php-cloudfiles/cloudfiles.php';
$username = 'my_username';
$api_key = 'my_api_key';
$full_object_name = 'this/is/the/full/file/name/in/the/container.png';
$auth = new CF_Authentication($username, $api_key);
$auth->ssl_use_cabundle();
$auth->authenticate();
if ( $auth->authenticated() )
{
$this->connection = new CF_Connection($auth);
// Get the container we want to use
$container = $this->connection->get_container($name);
$object = $container->delete_object($full_object_name);
echo 'object deleted';
}
else
{
throw new AuthenticationException("Authentication failed") ;
}
Note that the "$full_object_name" includes the "path" to the file in the container and the file name with no initial '/'. This is because containers use a Pseudo-Hierarchical folders/directories and what end ups being the name of the file in the container is the path + filename. for more info see http://docs.rackspace.com/files/api/v1/cf-devguide/content/Pseudo-Hierarchical_Folders_Directories-d1e1580.html
Use the method called DeleteObject from class CF_Container.
The method DeleteObject of CF_Container require only one string argument object_name.
This arguments should be the filename to be deleted.
See the example C# code bellow:
string username = "your-username";
string apiKey = "your-api-key";
CF_Client client = new CF_Client();
UserCredentials creds = new UserCredentials(username, apiKey);
Connection conn = new CF_Connection(creds, client);
conn.Authenticate();
var containerObj = new CF_Container(conn, client, container);
string file = "filename-to-delete";
containerObj.DeleteObject(file);
Note DonĀ“t use the DeleteObject from class *CF_Client*

Categories