asynchronus memcache on php - php

I am trying to write a method which will do asynchronus memcache queries.
This is my simple get/set memcache client class.
Class MemcacheClient
{
private $socket;
private $reply;
private $replies = array(
'OK' => true,
'EXISTS' => false,
'DELETED' => true,
'STORED' => true,
'NOT_STORED' => false,
'NOT_FOUND' => false,
'ERROR' => null,
'CLIENT_ERROR' => null,
'SERVER_ERROR' => null
);
public function __construct($host, $port)
{
$this->socket = stream_socket_client("$host:$port", $errno, $errstr);
if(!$this->socket) {
throw new Exception("$errst ($errno)");
}
}
public function get($key)
{
$reply = $this->query("get $key");
return $reply;
}
public function set($key, $value, $exptime = 0, $flags = 0)
{
return $this->query(array("set $key $flags $exptime ".strlen($value), $value));
}
public function aget($key, $function)
{
}
public function process()
{
}
public function hasTasks()
{
}
private function query($query)
{
$query = is_array($query) ? implode("\r\n", $query) : $query;
fwrite($this->socket, $query."\r\n");
return $this->parseLine();
}
private function parseLine()
{
$line = fgets($this->socket);
$this->reply = substr($line, 0, strlen($line) - 2);
$words = explode(' ', $this->reply);
$result = isset($this->replies[$words[0]]) ? $this->replies[$words[0]] : $words;
if (is_null($result)) {
throw new Exception($this->reply);
}
if ($result[0] == 'VALUE') {
$value = fread($this->socket, $result[3] + 2);
return $value;
}
return $result;
}
}
I'm looking for something like
$memClient->aget('key', function($data) {echo $data;});
Any ideas how it could be implemented? Will appreciate any help.
Thanks!

Related

warning in session_start() in php 7.1

my script has a problem and gives me this warning:
Warning: session_start(): Failed to read session data: user (path:
/Users/soroush/Documents/www/new/tmp/session) in
/Users/soroush/Documents/www/new/include/class.session.php on line 35
this is my class:
class SecureSessionHandler extends SessionHandler {
protected $key, $name, $cookie;
public function __construct($name = 'MY_SESSION', $cookie = [])
{
$this->key = SESSION_KEY;
$this->name = $name;
$this->cookie = $cookie;
$this->cookie += [
'lifetime' => 0,
'path' => ini_get('session.cookie_path'),
'domain' => ini_get('session.cookie_domain'),
'secure' => isset($_SERVER['HTTPS']),
'httponly' => true
];
$this->setup();
}
private function setup()
{
ini_set('session.use_cookies', 1);
ini_set('session.use_only_cookies', 1);
session_name($this->name);
session_set_cookie_params(
$this->cookie['lifetime'],
$this->cookie['path'],
$this->cookie['domain'],
$this->cookie['secure'],
$this->cookie['httponly']
);
}
public function start()
{
if (session_id() === '') {
if (session_start()) {
return mt_rand(0, 4) === 0 ? $this->refresh() : true; // 1/5
}
}
return false;
}
public function forget()
{
if (session_id() === '') {
return false;
}
$_SESSION = [];
setcookie(
$this->name,
'',
time() - 42000,
$this->cookie['path'],
$this->cookie['domain'],
$this->cookie['secure'],
$this->cookie['httponly']
);
return session_destroy();
}
public function refresh()
{
return session_regenerate_id(true);
}
public function read($id)
{
$data = openssl_decrypt(parent::read($id),'AES256',$this->key);
return $data;
}
public function write($id, $data)
{
return parent::write($id, openssl_encrypt(parent::read($id),'AES256',$this->key));
}
public function isExpired($ttl = 30)
{
$last = isset($_SESSION['_last_activity'])
? $_SESSION['_last_activity']
: false;
if ($last !== false && time() - $last > $ttl * 60) {
return true;
}
$_SESSION['_last_activity'] = time();
return false;
}
public function isFingerprint()
{
$hash = md5(
$_SERVER['HTTP_USER_AGENT'] .
(ip2long($_SERVER['REMOTE_ADDR']) & ip2long('255.255.0.0'))
);
if (isset($_SESSION['_fingerprint'])) {
return $_SESSION['_fingerprint'] === $hash;
}
$_SESSION['_fingerprint'] = $hash;
return true;
}
public function isValid()
{
return ! $this->isExpired() && $this->isFingerprint();
}
public function get($name)
{
$parsed = explode('.', $name);
$result = $_SESSION;
while ($parsed) {
$next = array_shift($parsed);
if (isset($result[$next])) {
$result = $result[$next];
} else {
return null;
}
}
return $result;
}
public function put($name, $value)
{
$parsed = explode('.', $name);
$session =& $_SESSION;
while (count($parsed) > 1) {
$next = array_shift($parsed);
if ( ! isset($session[$next]) || ! is_array($session[$next])) {
$session[$next] = [];
}
$session =& $session[$next];
}
$session[array_shift($parsed)] = $value;
}
}
and i use this class like this:
$session = new SecureSessionHandler();
ini_set('session.save_handler', 'files');
session_set_save_handler($session, true);
session_save_path(SITE_PATH.'tmp/session');
$session->start();
if ( ! $session->isValid(5)) {
$session->destroy();
die();
}
$session->put('site.langu', $lang->lang);
but it give me a warning in php 7.1
i use a mac os system and do this works
give 0777 permission to session folder
change chown with php running group and user
what should I do to fix this warning?
i solved this problem with this change:
public function read($id)
{
return (string)openssl_decrypt (parent::read($id) , "aes-256-cbc", $this->key);
}
public function write($id, $data)
{
return parent::write($id, openssl_encrypt($data, "aes-256-cbc", $this->key));
}
viva google :))

How to access variables from a object in php?

I'm following PHP Academy OOP Login/Register Tutorial currently in 16th part.
I used this code to create object in $data.
$data = $this->_db->get('users', array($field, '=', $user));
Then this code to add values from that object.
$this->_data = $data;
and trying to access the variables there by
public function data(){
return $this->_data;
}
$this->data()->password
The last code is throwing error. I tried to debug using this code
$vars = get_object_vars ($this->_data);
print_r($vars);
That is printing this line
Array ( [error] => [_requests] => Array ( [0] => stdClass Object ( [uid] => 16 [username] => admin [password] => 46651b6f1d743345d82d32da2cda7f891016ebe9f8b4416314b127e35b72fc30 [salt] => ²ê$ÓÕBF49ð®}€Æ¥A];ÛAc«íÊùÍ„s [name] => admin [joined] => 2015-03-17 22:53:52 [groups] => 1 ) ) )
What does this mean? How can I access those fields?
Here is the full code:
DB.php
<?php
/**
* Connect to database.
*
*/
class DB{
private static $_instance = null;
private $_pdo,
$_query,
$_error = false,
$_results,
$_count = 0;
private function __construct()
{
try
{
$this->_pdo = new PDO('mysql:host='.Config::get('mysql/host').';'.
'dbname='.Config::get('mysql/db'),
Config::get('mysql/username'),
Config::get('mysql/password')
);
}
catch(PDOException $e)
{
die($e->getMessage());
}
}
public static function getInstance()
{
if(!isset(self::$_instance))
{
self::$_instance = new DB();
}
return self::$_instance;
}
public function query($sql, $params = array())
{
$this->error = false;
if($this->_query = $this->_pdo->prepare($sql))
{
$x = 1;
if(count($params))
{
foreach ($params as $param)
{
$this->_query->bindvalue($x, $param);
$x++;
}
}
if($this->_query->execute())
{
$this->_requests = $this->_query->fetchAll(PDO::FETCH_OBJ);
$this->_count = $this->_query->rowCount();
}
else
{
$this->_error = true;
}
}
return $this;
}
public function action($action, $table, $where = array())
{
if(count($where) === 3)
{
$operators = array('=', '>', '<', '>=', '<=');
$field = $where[0];
$operator = $where[1];
$value = $where[2];
if(in_array($operator, $operators))
{
$sql = "{$action} FROM {$table} WHERE {$field} {$operator} ?";
if(!$this->query($sql, array($value))->error())
{
return $this;
}
}
}
return false;
}
public function get($table, $where)
{
return $this->action('SELECT *', $table, $where);
}
public function delete($table, $where)
{
return $this->action('DELETE', $table, $where);
}
public function insert($table, $fields = array())
{
if(count($fields))
{
$keys = array_keys($fields);
$values = '';
$x = 1;
foreach ($fields as $field) {
$values .= '?';
if($x < count($fields))
{
$values .= ', ';
}
$x++;
}
// die($values);
$sql = "INSERT INTO {$table} (`".implode('`, `', $keys)."`) VALUES ({$values})";
echo $sql;
if(!$this->query($sql, $fields)->error())
{
return true;
}
}
return false;
}
public function update($table, $id, $fields)
{
$set = '';
$x = 1;
foreach ($fields as $name => $value) {
$set .= "{$name} = ?";
if($x < count($fields))
{
$set .= ', ';
}
$x++;
}
$sql = "UPDATE {$table} SET {$set} WHERE uid = {$id}";
if(!$this->query($sql, $fields)->error())
{
return true;
}
return false;
}
public function results()
{
return $this->_results;
}
public function first()
{
return $this->results()[0];
}
public function error()
{
return $this->_error;
}
public function count()
{
return $this->_count;
}
}
user.php
<?php
class User{
private $_db,
$_data;
public function __construct($user = null)
{
$this->_db = DB::getInstance();
}
public function create($fields = array())
{
if(!$this->_db->insert('users', $fields))
{
throw new Exception("Problem Creating User Account");
}
}
public function find($user = null)
{
if($user)
{
$field = (is_numeric($user)) ? 'uid' : 'username';
$data = $this->_db->get('users', array($field, '=', $user));
if($data->count())
{
$this->_data = $data;
$vars = get_object_vars ($this->_data);
print_r($vars);
return true;
}
}
}
public function login($username = null, $password = null)
{
$user = $this->find($username);
if($user)
{
if($this->data()->password === Hash::make($password, $this->_data->salt))
{
echo "ok";
}
}
return false;
}
public function data()
{
return $this->_data;
}
}
login.php
<?php
require_once 'core/init.php';
if(Input::exists())
{
if(Token::check(Input::get('token')))
{
$validate = new Validation();
$validation = $validate->check($_POST, array(
'username' => array(
'required' => true
),
'password' => array(
'required' => true
),
));
if($validation->passed())
{
$user = new User();
$login = $user->login(Input::get('username'), Input::get('password'));
if($login)
{
echo "Success";
}
else{
echo "sorry! Failed";
}
}
else{
foreach ($validation->errors() as $error) {
echo $error, '<br />';
}
}
}
}
?>
<form action="" method="post">
<div class="field">
<label for="username">Username</label>
<input type="text" name="username" id="username" autocomplete="off">
</div>
<div class="field">
<label for="password">Password</label>
<input type="password" name="password" id="password" autocomplete="off">
</div>
<input type="hidden" name="token" value="<?php echo Token::generate(); ?>">
<input type="submit" value="Log In">
</form>
The variable returns array output. So you need to get values like $this->_data[0]->password, $this->_data[0]->username. Or when you store value to $this->_data, you can store the first child of the array.
instead of
$this->_data = $data;
You can use
$this->_data = $data->first();
So now you can get fields like $this->_data->username,$this->_data->password

Fatal error: Call to a member function count() on a non-object [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am learning PHP OOP by utilizing a PHP Academy tutorial. The tutorial is a Registration/Login system. I am having trouble on the "Remember Me" portion of the tutorial. This part of the tutorial retains a users selection to be able to stay logged in.
I am having an error:
"Fatal error: Call to a member function count() on a non-object in C:\xampp\htdocs\Rikarsen.hol.es\core\init.php on line 32
I have placed the PHP classes below to show what I have done thus far. Since I am new to PHP coding I am unable to locate the problem. Can anyone please help me? If any additional code is needed please let me know so I can supply it to you in order to help you discover my problem.
init.php
<?php
session_start();
$GLOBALS ['config'] = array(
'mysql' => array(
'host' => '127.0.0.1',
'username' => 'root',
'password' => '',
'db' => 'rikars'
),
'remember' => array(
'cookie_name' => 'hash',
'cookie_expiry' => 604800
),
'session' => array(
'session_name' => 'user',
'token_name' => 'token'
)
);
spl_autoload_register(function($class) {
require_once 'classes/' . $class . '.php';
});
require_once 'functions/sanitize.php';
if(Cookie::exists(Config::get('remember/cookie_name')) && Session::exists(Config::get('session/session_name'))) {
$hash = Cookie::get(Config::get('remember/cookie_name'));
$hashCheck = DB::getInstance()->get('users_sessions', array('hash', '=', $hash));
if($hashCheck->count()) {
echo 'asass';
}
}
I think I made a mistake in DB.php
<?php
class DB {
private static $_instance = null;
private $_pdo,
$_query,
$_error = false,
$_result,
$_count = 0;
private function __construct() {
try {
$this->_pdo = new PDO('mysql:host=' . Config::get('mysql/host') . ';dbname=' . Config::get('mysql/db'), Config::get('mysql/username'), Config::get('mysql/password'));
} catch(PDOException $e) {
die($e->getMessage());
}
}
public static function getInstance() {
if(!isset(self::$_instance)) {
self::$_instance = new DB();
}
return self::$_instance;
}
public function query($sql, $params = array()) {
$this->_error = false;
if($this->_query = $this->_pdo->prepare($sql)) {
$x = 1;
if(count($params)){
foreach($params as $param){
$this->_query->bindValue($x, $param);
$x++;
}
}
if($this->_query->execute()){
$this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
$this->_count = $this->_query->rowCount();
} else {
$this->_error = true;
}
}
return $this;
}
public function action($action, $table, $where = array()) {
if(count($where) === 3) {
$operators = array('=', '>', '<', '>=', '<=');
$field = $where[0];
$operator = $where[1];
$value = $where[2];
if(in_array($operator, $operators)) {
$sql = "{$action} FROM {$table} WHERE {$field} {$operator} ?";
if(!$this->query($sql, array($value))->error()) {
return $this;
}
}
}
return false;
}
public function get($table, $where) {
return $this->action('SELECT *', $table, $where);
}
public function delete($table, $where) {
return $this->action('DELETE *', $table, $where);
}
public function insert($table, $fields = array()) {
$keys = array_keys($fields);
$values = null;
$x = 1;
foreach($fields as $field) {
$values .= '?';
if($x < count($fields)) {
$values .= ', ';
}
$x++;
}
$sql = "INSERT INTO {$table} (`" . implode('`, `', $keys) . "`) VALUES ({$values})";
if(!$this->query($sql, $fields)->error()) {
return true;
}
return false;
}
public function update($table, $id, $fields) {
$set = '';
$x= 1;
foreach ($fields as $name => $value) {
$set .= "{$name} = ?";
if($x < count($fields)) {
$set .= ', ';
}
$x++;
}
$sql = "UPDATE {$table} SET {$set} WHERE id = {$id}";
if($this->query($sql, $fields)->error()) {
return true;
}
return false;
}
public function results() {
return $this->_results;
}
public function first() {
return $this->results()[0];
}
public function error() {
return $this->_error;
}
public function count() {
return $this->_count;
}
public function ins() {
$instance = DB::getInstance();
$instance->get('users',array('user_id','=','1'));
if (!$instance->Count()) {
echo 'No user';
} else {
echo 'User exists';
}
}
}
?>
Your method action return false but you expect object.
if(Cookie::exists(Config::get('remember/cookie_name')) && Session::exists(Config::get('session/session_name'))) {
$hash = Cookie::get(Config::get('remember/cookie_name'));
$hashCheck = DB::getInstance()->get('users_sessions', array('hash', '=', $hash));
if($hashCheck === false) {
echo 'Action return false';
} else {
$count = $hashCheck->count();
if($count) {
echo 'Its object and count ='.$count;
}
}
}
Make sure your table name and column names are correct in get method. I was having the same problem and this was the solution that worked for me.

php oop not submitting to db

I know a bit of php and starting to learn php oop and following a guide from alex at php academy how every when trying to insert into a db it doesn't seem to insert.
I have db detail set up like this
init.php
<?php
session_start();
$GLOBALS['config'] = array(
'mysql' => array(
'host' => '127.0.0.1',
'username' => 'root',
'password' => '',
'db' => 'oop'
),
'remember' => array(
'cookie_name' => 'hash',
'cookie_expiry' => 2592000
),
'session' => array(
'session_name' => 'user'
)
);
spl_autoload_register(function($class){
require_once 'classes/' . $class . '.php';
});
require_once 'functions/sanitize.php';
?>
this is my database class every thing seems to work fine untill i get to public function insert
db.php
<?php
class db {
private static $_instance = null;
private $_pdo,
$_query,
$_error = false,
$_result,
$_count = 0;
private function __construct(){
try {
$this->_pdo = new PDO('mysql:host=' . config::get('mysql/host') . ';dbname=' . config::get('mysql/db'), config::get('mysql/username'), config::get('mysql/password'));
} catch (PDOException $e) {
die($e->getMessage());
}
}
public static function getInstance() {
if(!isset(self::$_instance)){
self::$_instance = new db();
}
return self::$_instance;
}
public function query($sql, $params = array()) {
$this->_error = false;
if($this->_query = $this->_pdo->prepare($sql)){
$x = 1;
if(count($params)) {
foreach($params as $param){
$this->_query->bindValue($x, $param);
$x++;
}
}
if($this->_query->execute()) {
$this->_result = $this->_query->fetchAll(PDO::FETCH_OBJ);
$this->_count = $this->_query->rowCount();
} else {
$this->_error = true;
}
}
return $this;
}
public function action($action, $table, $where = array()) {
if(count($where) === 3) {
$operators =array('=', '>', '<', '>=', '<=');
$field = $where[0];
$operator = $where[1];
$vaule = $where[2];
if(in_array($operator, $operators)) {
$sql = "{$action} FROM {$table} WHERE {$field} {$operator} ?";
if (!$this->query($sql, array($vaule))->error()) {
return $this;
}
}
}
return false;
}
public function get($table, $where) {
return $this->action('SELECT *', $table, $where);
}
public function delete() {
return $this->action('DELETE', $table, $where);
}
public function insert($table, $fields = array()){
if(count($fields)){
$keys = array_keys($fields);
$values = '';
$x = 1;
foreach($fields as $field){
$values .= '?';
if($x < count($fields)){
$values .= ', ';
}
$x++;
}
$sql = "INSERT INTO users (`" . implode('`,`', $keys) . "`) VALUES ({$values})";
if(!$this->query($sql, $fields)->error()){
return true;
}
}
return false;
}
public function results(){
return $this->_result;
}
public function first() {
return $this->results()[0];
}
public function error() {
return $this->_error;
}
public function count() {
return $this->_count;
}
}
?>
and this is what I am using to submit to db
index.php
<?php
require_once 'core/init.php';
$user = db::getInstance()->insert('users', array(
'username' => 'pravaut',
'passowrd' => 'test',
'salt' => 'salt'
));
?>

How to get imap flags?

I used the imap4flag plugin for Dovecot sieve: http://wiki.dovecot.org/LDA/Sieve#Flagging_or_Highlighting_your_mail
The flag is correctly show in thunderbird but I search how get the flags for show them in roundcube.
Thank's in advance.
This is a missing feature, see the PHP bug #53043 : http://bugs.php.net/bug.php?id=53043
A example code using directly the IMAP protocol:
<?php
declare(strict_types=1);
class ImapSocket
{
private $socket;
public function __construct($options, $mailbox = '')
{
$this->socket = $this->connect($options['server'], $options['port'], $options['tls']);
$this->login($options['login'], $options['password']);
if ($mailbox !== null) {
$this->select_mailbox($mailbox);
}
}
private function connect(string $server, int $port, bool $tls)
{
if ($tls === true) {
$server = "tls://$server";
}
$fd = fsockopen($server, $port, $errno);
if (!$errno) {
return $fd;
}
else {
throw new \Exception('Unable to connect');
}
}
private function login(string $login, string $password): void
{
$result = $this->send("LOGIN $login $password");
$result = array_pop($result);
if (substr($result, 0, 5) !== '. OK ') {
throw new \Exception('Unable to login');
}
}
public function __destruct()
{
fclose($this->socket);
}
public function select_mailbox(string $mailbox): void
{
$result = $this->send("SELECT $mailbox");
$result = array_pop($result);
if (substr($result, 0, 5) !== '. OK ') {
throw new \Exception("Unable to select mailbox '$mailbox'");
}
}
public function get_flags(int $uid): array
{
$result = $this->send("FETCH $uid (FLAGS)");
preg_match_all("|\\* \\d+ FETCH \\(FLAGS \\((.*)\\)\\)|", $result[0], $matches);
if (isset($matches[1][0])) {
return explode(' ', $matches[1][0]);
}
else {
return [];
}
}
private function send(string $cmd, string $uid = '.')
{
$query = "$uid $cmd\r\n";
$count = fwrite($this->socket, $query);
if ($count === strlen($query)) {
return $this->gets();
}
else {
throw new \Exception("Unable to execute '$cmd' command");
}
}
private function gets()
{
$result = [];
while (substr($str = fgets($this->socket), 0, 1) == '*') {
$result[] = substr($str, 0, -2);
}
$result[] = substr($str, 0, -2);
return $result;
}
}
Usage:
<?php
$imap = new ImapSocket([
'server' => 'localhost',
'port' => 143,
'login' => 'login',
'password' => 'secret',
'tls' => false,
], 'INBOX');
var_dump($imap->get_flags(0));

Categories