How to connect to redis server with init file and no passwd - php

First, I have wrapper Datasource class for connecting redis server.
And I have a init file of ip port and passwd etc;
The content redis.ini.php file is:
<?php
$config['redis']['instance1'] = array(
'default' => array(
'host' => '127.0.0.1',
'port' => '6379',
'timeout' => 5,
'pconnect' => 1,
'password' => '',
)
);
$config['redis']['instance2'] = array(
'default' => array(
'host' => '127.0.0.1',
'port' => '6379',
'timeout' => 5,
'pconnect' => 1,
'password' => '',
)
);
And the code of class Datasource.php is:
<?php
namespace common;
class Datasource {
public static $config_name;
public static $server_region;
public static $redis_config;
public function __construct() {}
public static function getRedis($config_name = NULL, $server_region = 'default') {
self::$config_name=$config_name;
self::$server_region=$server_region;
global $config;
self::$redis_config = $config['redis'][$config_name];
if (self::$config_name && self::$redis_config && self::$server_region) {
try {
self::$redis = new \Redis();
self::$redis->connect(self::$redis_config[$server_region]['host'], self::$redis_config[$server_region]['port']);
} catch (Exception $e) {
self::$redis = null;
}
} else {
self::$redis = null;
}
return self::$redis_config[$server_region]['host'] ;
}
}
Now, I want to use this class in html code:
<body style="height:100%" >
<?php
include "o1ws1v/class/common/Datasource.php";
include 'o1ws1v/conf/redis.ini.php';
$redis_obj = common\Datasource::getRedis('instance1');
echo $redis_obj;
?>
</body>
But unlucky, I can not get corrent value:127.0.0.1 in html .
I have found that the problem was try{}catch{}, when i delete these code, it work fine.
//delete these code, it works fine
try {
self::$redis = new \Redis();
self::$redis->connect(self::$redis_config[$server_region]['host'], self::$redis_config[$server_region]['port']);
} catch (Exception $e) {
self::$redis = null;
}
I have asked one question one hour ago in stackoverflow, sorry about one more question. My boss claim me to solve this question today.
I have defined my redis server with no password for logging. It seems nothing wrong for connecting redis server, Who can help me?

I have solved this porblem
self::$redis = new \Redis();// it is wrong
$redis=new \Redis();//it is right

Related

WHMCS changing database

I'm still trying to understand why in WHMCS on the same MySQL database if I try to connect to a different db, he still tries to search a table in his default database.
Example: I'm trying to connect to the table "test" in "admin_test" so he needs to search for "admin_test.test", but instead he gives me the error:
VPN Database Query Error: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'admin_billing.test' doesn't exist (SQL: insert into test (user_id) values (fdffddfg))
So I think he doesn't want to change db, I tried to write this module based on the freeradius module, as it works fine and has his own db on the same localhost mysql.. I don't know how to fix this as of now.
function rscmodule_DatabaseInsert()
{
try {
$vpnsql = rscmodule_DatabaseConnect();
if (is_string($vpnsql)) {
return $vpnsql; // Error condition
}
Capsule::connection()->transaction(
function ($vpnsql)
{
/** #var \Illuminate\Database\Connection $connectionManager */
$vpnsql->table('test')->insert(
[
'user_id' => 'fdffddfg',
]
);
}
);
} catch (\Exception $e) {
return "VPN Database Query Error: " . $e->getMessage();
}
return "success";
}
function rscmodule_DatabaseConnect()
{
$pdo = null;
try {
$pdo = Capsule::getInstance()->getConnection('rscmodule');
} catch (\Exception $e) {
$config = array(
'driver' => 'mysql',
'host' => 'localhost',
'database' => 'admin_test',
'username' => 'admin_test',
'password' => '*****',
'charset' => 'utf8',
);
try {
Capsule::getInstance()->addConnection(
$config,
'rscmodule'
);
$pdo = Capsule::getInstance()->getConnection('rscmodule');
} catch (\Exception $e) {
return "Unable to connect to rscmodule Database. "
. "Please check rscmodule server configuration. "
. $e->getMessage();
}
}
if (is_object($pdo)) {
if (method_exists($pdo, 'query')) {
$ret = $pdo->query();
} else {
$processor = $pdo->getPostProcessor();
$ret = new \Illuminate\Database\Query\Builder($pdo, $pdo->getQueryGrammar(), $processor);
}
} else {
$ret = $pdo;
}
return $ret;
}
Well turns out WHMCS doesn't want other DBs inside the same connection IP, so we created a VM on a new IP and on that the connection works properly.

How to get redis key value with class function and init file

In my project, I use redis.
And I have a init file including ip port and port, so class Datasource is used for analying init file and connecting redis.
Here is class Datasource.php code with function getRedis() in it:
namespace common;
class Datasource {
public function __construct() {}
public static function getRedis($config_name = NULL, $server_region = 'default') {
global $config;
$redis_config = $config['redis'][$config_name];
if ($config_name && $redis_config && $server_region) {
$this->_config_name = $config_name;
$this->_redis_config = $redis_config;
$this->_server_region = $server_region;
try {
$this->_redis = new \Redis();
$this->_redis->connect($this->_redis_config[$server_region]['host'], $this->_redis_config[$server_region]['port']);
if($this->_redis_config[$server_region]['password'] && !$this->_redis->auth($this->_redis_config[$server_region]['password'])) {
$this->_redis = null;
}
} catch (Exception $e) {
$this->_redis = null;
}
} else {
$this->_redis = null;
}
return self::$this->_redis;
}
}// end of class Datasource
Here is init file code of redis.ini.php
<?php
$config['redis']['instance1'] = array(
'default' => array(
'host' => '127.0.0.1',
'port' => '6379',
'timeout' => 5,
'pconnect' => 1,
'password' => '',
)
);
$config['redis']['instance2'] = array(
'default' => array(
'host' => '127.0.0.1',
'port' => '6379',
'timeout' => 5,
'pconnect' => 1,
'password' => '',
)
);
Now I want to get xie value which is in redis, Here is my html code:
<body style="height:100%" >
<?php
include "o1ws1v/class/common/Datasource.php";
include 'o1ws1v/conf/redis.ini.php';
$redis_obj = common\Datasource::getRedis('instance1');
$value = $redis_obj->get("xie");
echo "get key xie is:".$value."\n";
?>
</body>
Actually, key xie should be zuo. The corrent result is a line : "get key xie is:zuo"
But it showed nothing, Who can help me?
You use $this in a static method, and you can't. Additionaly, you catch all Exceptions while connecting to Redis, so you can't know why it wasn't unsuccessful. You need to do two things:
Turning on PHP errors (for development only of course)
Don't catch the Exceptions while connecting, and if you do - then log / keep the Exception's message.
Try something like this:
<?php
namespace common;
class Datasource
{
private static $_redis, $_config_name, $_redis_config, $_server_region;
public static function getRedis($config_name = NULL, $server_region = 'default')
{
error_reporting(E_ALL);
ini_set("display_errors", true);
global $config;
$redis_config = $config['redis'][$config_name];
if (!$config_name || !$redis_config || !$server_region) {
throw new \Exception('$config_name or $redis_config or $server_region is not set');
}
if (!$redis_config[$server_region]['password']) {
throw new \Exception('Redis password is not set');
}
self::$_config_name = $config_name;
self::$_redis_config = $redis_config;
self::$_server_region = $server_region;
self::$_redis = new \Redis();
self::$_redis->connect(self::$_redis_config[$server_region]['host'], self::$_redis_config[$server_region]['port']);
if (!self::$_redis->auth(self::$_redis_config[$server_region]['password'])) {
throw new \Exception("Can't login to Redis. Check password");
}
return self::$_redis;
}
}
And the error displaying code is obviously not belong here, it's just for you to see if there are any errors temporarly.
Also, I would add a condition to see if Redis is already set, then return the connection. Otherwise you will make another connection every time you call getRedis method. Something like this:
public static function getRedis(...)
{
if (!self::$_redis) {
...
}
return self::$_redis;
}

How to set global variables in Laravel?

I developing a app and I want to get some data with CURL, I'm using Guzzle to get this informations. In every request I need to put the param api_token. I don't have problems with requests but I need to create a globals variables or config this values. My ask is: how I can define this values and after use them in every request that I made?
$response = $client->request('POST', 'https://api.iugu.com/v1/payment_token?api_token=API_TOKEN', [
'json' => [
'account_id' => $account_id,
'method' => $method,
'test' => true,
'data' => [[
'number' => $number,
'verification_value' => $verification_value,
'first_name' => $first_name,
'last_name' => $last_name,
'month' => $month,
'year' => $year
]]
]
]);
When I create a project in pure PHP. I use this:
require 'environment.php';
$config = array();
if(ENVIRONMENT == 'development') {
define("BASE_URL", "http://localhost/plans/");
define("ACCOUNT_ID", "SECRET");
define("ACCESS_TOKEN", "SECRET");
$config['db_name'] = 'SECRET';
$config['host'] = 'localhost';
$config['db_user'] = 'root';
$config['db_password'] = 'XXXXXX';
} else {
define("BASE_URL", "http://www.blablabla/test");
define("ACCOUNT_ID", "SECRET");
define("ACCESS_TOKEN", "MY_TOKEN");
$config['db_name'] = 'INSERIR DATABASE';
$config['host'] = 'INSERIR HOST';
$config['db_user'] = 'INSERIR USUARIO';
$config['db_password'] = 'INSERIR SENHA';
}
global $database;
try {
$database = new PDO("mysql:dbname=".$config['db_name'].";host=".$config['host'], $config['db_user'],$config['db_password']);
} catch (Exception $ex) {
echo "Erro: ".$ex->getMessage();
exit;
}
And in the environment.php:
<?php
define("ENVIRONMENT", "development");
//define("ENVIRONMENT", "production");
All these values should be in your .env file. Then you need to read these values in a config file by using env() helper:
'variable' => env('SOME_DATA'),
And then you'll be able to use these values globally with:
config('config_file.variable')
For Global Variables, you can create a file like constants.php within config folder.
Inside constants.php file, you can define your global variable api_token like below:
<?php
return [
'api_token' => env('API_TOKEN','https://api.iugu.com/v1/payment_token?api_token=API_TOKEN'),
];
?>
You can access this variable now using either of these two functions:
Config::get('constants.api_token')
config('constants.api_token')
For Blade file, do like below:
{{ config('constants.api_token') }}
Other alternative is to set Global Variable in __construct function in Controller.php file located at Controllers folder like below:
class Controller extends BaseController
{
public $api_token;
public function __construct(){
$this->api_token = "https://api.iugu.com/v1/payment_token?api_token=API_TOKEN";
}
I don't know exactly from your question that you want to make api_token or ENVIRONMENT as Global Variable but both solutions can resolve your issue.

How to get a bootstrap resource in a controller plugin in Zend Framework

protected function _initDatabase()
{
$params = array(
'host' => '',
'username' => '',
'password' => '',
'dbname' => '',
);
$database = Zend_Db::factory('PDO_MYSQL', $params);
$database->getConnection();
return $database;
}
.
class App_Controller_Plugin_Test extends Zend_Controller_Plugin_Abstract
{
public function preDispatch(Zend_Controller_Request_Http $request)
{
// how i get database?
}
}
You can always get a reference to the front controller:
$front = Zend_Controller_Front::getInstance();
From that you can get the bootstrap:
$bootstrap = $front->getParam("bootstrap");
From the bootstrap you can get bootstrap plugins:
if ($bootstrap->hasPluginResource("database")) {
$dbResource = $bootstrap->getPluginResource("database");
}
$db = $dbResource->getDatabase();
But that's a lot of extra plumbing!
Honestly, you'd be better off storing the database adapter object in the registry during your bootstrap:
protected function _initDatabase()
{
$params = array(
'host' => '',
'username' => '',
'password' => '',
'dbname' => '',
);
$database = Zend_Db::factory('PDO_MYSQL', $params);
$database->getConnection();
Zend_Registry::set("database", $database);
return $database;
}
Then you can get the database adapter anywhere:
Zend_Registry::get("database");
See also my answer to What is the “right” Way to Provide a Zend Application With a Database Handler
Too bad there's nothing like Zend_Controller_Action's getInvokeArg("bootstrap") in a plugin. You could always get the bootstrap reference through the front controller:
$db = Zend_Controller_Front::getInstance()->getParam("bootstrap")->getResource("database");
But what I usually do is
Zend_Registry::set('database', $database);
and then in your plugin:
try
{
$db = Zend_Registry::get('database');
}
catch (Zend_Exception $e)
{
// do stuff
}
Easier, and database can be retrieved pretty much anywhere in the application.
[I need to check this against some working code on another machine. I believe it's something like this...]
$db = Zend_Controller_Front::getInstance()->getParam('bootstrap')->getResource('db');
$db = Zend_Db_Table::getDefaultAdapter();

Zend_OpenId_Extension_Sreg fails on me

Below is a working example of my OpenId implementation. I use hyves.nl as the OpenId provider but this also works with me.yahoo.com and probably other OpenId providers as well (but not Google).
So far so good. But now I want to fetch the nickname and/or fullname from my hyves profile. But when I set nickname and/or fullname to true in the $props array I can't login anymore at all.
What am I doing wrong here?
class TestController extends Zend_Controller_Action
{
private $_sreg = null;
public function init()
{
$props = array('nickname' => false,
'email' => false,
'fullname' => false,
'dob' => false,
'gender' => false,
'postcode' => false,
'country' => false,
'language' => false,
'timezone' => false);
$this->_sreg = new Zend_OpenId_Extension_Sreg($props);
}
public function loginAction()
{
$consumer = new Zend_OpenId_Consumer();
if (!$consumer->login('hyves.nl', 'http://localhost/trouwcom/public/test/verify', 'http://localhost/trouwcom', $this->_sreg))
{
echo 'Login failed';
}
$this->_helper->viewRenderer->setNoRender();
}
public function verifyAction()
{
$consumer = new Zend_OpenId_Consumer();
if ($consumer->verify($_GET, $id, $this->_sreg))
{
echo 'VALID ' . htmlspecialchars($id);
$data = $this->_sreg->getProperties();
print_r($data);
}
else
{
echo 'INVALID ' . htmlspecialchars($id);
}
$this->_helper->viewRenderer->setNoRender();
}
}
Could it be this bug? http://framework.zend.com/issues/browse/ZF-5266
Don't know if you found your answer already. But if you didn't or anyone else is reading this question like me and having the same problem I just found the answer.
The problem with openId provider "hyves.nl" is that they don't return the verification parameters by $_GET but by $_POST.
# This works
$consumer->verify($_POST, $id, $this->_sreg);

Categories