示例#1
0
function pdb_get_data($key, $provider, $arguments = [])
{
    $mc_handler = memcache_pconnect(MC_HOST);
    $value = memcache_get($mc_handler, $key);
    if ($value !== false) {
        return $value;
    } else {
        $locking_key = 'lock_' . $key;
        $locking_value = microtime(true);
        for ($i = 0; $i < MC_LOCK_DELAY * 1000 / MC_SLEEP_TIME + 1; $i++) {
            $lock = memcache_add($mc_handler, $locking_key, $locking_value, 0, MC_LOCK_DELAY);
            if ($lock) {
                $value = call_user_func_array($provider, $arguments);
                memcache_set($mc_handler, $key, $value);
                memcache_delete($mc_handler, $locking_key);
                return $value;
            } else {
                usleep(MC_SLEEP_TIME);
                $value = memcache_get($mc_handler, $key);
                if ($value != false) {
                    return $value;
                }
            }
        }
    }
    return call_user_func_array($provider, $arguments);
}
示例#2
0
文件: cache.php 项目: senko/rfx
function _cache_init()
{
    global $config;
    global $_mch;
    if (!is_null($_mch)) {
        return;
    }
    $_mch = memcache_pconnect($config['memcache']['host']);
}
示例#3
0
 /**
  * Accepts the 2-d array with details of memcached servers
  *
  * @param array $servers
  */
 protected function __construct(array $servers)
 {
     if (!$servers) {
         trigger_error('No memcache servers to connect', E_USER_WARNING);
     }
     for ($i = 0, $n = count($servers); $i < $n; ++$i) {
         ($con = memcache_pconnect(key($servers[$i]), current($servers[$i]))) && ($this->mc_servers[] = $con);
     }
     $this->mc_servers_count = count($this->mc_servers);
     if (!$this->mc_servers_count) {
         $this->mc_servers[0] = null;
     }
 }
示例#4
0
function mcached_conn()
{
    global $config, $mem_flag, $mem_conn;
    if ($mem_flag != 1) {
        if ($config['mcache']['version'] == 0) {
            $mem_conn = memcache_pconnect($config['mcache']['host'], 11211);
        } else {
            $mem_conn = new Memcached();
            $mem_conn->addServer($config['mcache']['host'], 11211);
        }
        $mem_flag = 1;
    }
    return $mem_conn;
}
示例#5
0
 function delete_search_keys()
 {
     $dbh = new PDO('mysql:dbname=' . AppConfig::gacv("AC_db") . ';host=' . AppConfig::gacv("AC_server"), AppConfig::gacv("AC_user"), AppConfig::gacv("AC_pass"));
     $memcache_obj = memcache_pconnect('localhost', 11211);
     $sql = sprintf("select search_key from %s ", "memcache_search_keys");
     $sth = $dbh->prepare($sql, array(PDO::ATTR_CURSOR, PDO::CURSOR_FWDONLY));
     //
     $sth->execute();
     $res = $sth->fetchAll(PDO::FETCH_BOTH);
     //echo $sql.$this->lookup_tbl_id_col;//
     foreach ($res as $ar) {
         memcache_delete($memcache_obj, $ar["search_key"], 0);
     }
     /* Delete all rows from the FRUIT table */
     $count = $dbh->exec("DELETE FROM memcache_search_keys");
 }
示例#6
0
function MCache_connect($name)
{
    // use link for adding connection into global $Config
    $settings =& loadConfig('memcache')['memcache'][$name];
    // get connect if it already exists
    if (!is_null($settings['connect'])) {
        return $settings['connect'];
    }
    $mcConnect = memcache_pconnect($settings['hostname'], $settings['port']);
    if (!$mcConnect) {
        exit("Memcache connect error.");
    }
    // remember connection
    $settings['connect'] = $mcConnect;
    return $mcConnect;
}
示例#7
0
文件: memcache.php 项目: herrify/asyn
 public function __construct($queueName = '', $maxqueue = 1, $canRewrite = false, $expire = 0, $config = '')
 {
     if (empty($config)) {
         self::$client = memcache_pconnect('127.0.0.1', 11211);
     } elseif (is_array($config)) {
         //array('host'=>'127.0.0.1','port'=>'11211')
         self::$client = memcache_pconnect($config['host'], $config['port']);
     } elseif (is_string($config)) {
         //"127.0.0.1:11211"
         $tmp = explode(':', $config);
         $conf['host'] = isset($tmp[0]) ? $tmp[0] : '127.0.0.1';
         $conf['port'] = isset($tmp[1]) ? $tmp[1] : '11211';
         self::$client = memcache_pconnect($conf['host'], $conf['port']);
     }
     if (!self::$client) {
         return false;
     }
     ignore_user_abort(true);
     //当客户断开连接,允许继续执行
     set_time_limit(0);
     //取消脚本执行延时上限
     $this->access = false;
     $this->sleepTime = 1000;
     $expire = empty($expire) ? 0 : (int) $expire + 1;
     $this->expire = $expire;
     $this->queueName = $queueName;
     $this->retryNum = 20000;
     $this->MAXNUM = $maxqueue != null ? $maxqueue : 1;
     $this->canRewrite = $canRewrite;
     $this->getHeadAndTail();
     if (!isset($this->HEAD) || empty($this->HEAD)) {
         $this->HEAD = 0;
     }
     if (!isset($this->TAIL) || empty($this->TAIL)) {
         $this->TAIL = 0;
     }
     if (!isset($this->LEN) || empty($this->LEN)) {
         $this->LEN = 0;
     }
 }
示例#8
0
文件: genlib.php 项目: hcopr/Hubbub
function cache_connect()
{
    if (!cfg('memcache/enabled')) {
        return false;
    }
    if (isset($GLOBALS['obj']) && $GLOBALS['obj']['memcache']) {
        return true;
    }
    $mcUrl = explode(':', cfg('memcache/server'));
    $mc = null;
    $GLOBALS['errorhandler_ignore'] = true;
    $mc = @memcache_pconnect($mcUrl[0], $mcUrl[1] + 0);
    $GLOBALS['errorhandler_ignore'] = false;
    if ($mc === false) {
        $GLOBALS['config']['memcache']['enabled'] = false;
        $GLOBALS['errors']['memcache'] = 'Could not connect to memcache server ' . cfg('memcache/server');
        logError('', 'memcache: could not connect to server ' . cfg('memcache/server'));
        return false;
    }
    $GLOBALS['obj']['memcache'] = $mc;
    return true;
}
示例#9
0
文件: base.php 项目: nian2go/fatfree
 /**
 		Initialize cache backend
 			@return bool
 			@public
 	**/
 static function prep()
 {
     if (!self::$vars['CACHE']) {
         return TRUE;
     }
     if (is_bool(self::$vars['CACHE'])) {
         // Auto-detect backend
         self::detect();
     }
     if (preg_match('/^(apc)|(memcache)=(.+)|(xcache)|(folder)=(.+\\/)/i', self::$vars['CACHE'], $match)) {
         if (isset($match[5]) && $match[5]) {
             if (!is_dir($match[6])) {
                 self::mkdir($match[6]);
             }
             // File system
             self::$backend = array('type' => 'folder', 'id' => $match[6]);
         } else {
             $ext = strtolower($match[1] ?: ($match[2] ?: $match[4]));
             if (!extension_loaded($ext)) {
                 trigger_error(sprintf(self::TEXT_PHPExt, $ext));
                 return FALSE;
             }
             if (isset($match[2]) && $match[2]) {
                 // Open persistent MemCache connection(s)
                 $mcache = NULL;
                 foreach (self::split($match[3]) as $server) {
                     // Hostname:port
                     list($host, $port) = explode(':', $server);
                     if (is_null($port)) {
                         // Use default port
                         $port = 11211;
                     }
                     // Connect to each server
                     if (is_null($mcache)) {
                         $mcache = memcache_pconnect($host, $port);
                     } else {
                         memcache_add_server($mcache, $host, $port);
                     }
                 }
                 // MemCache
                 self::$backend = array('type' => $ext, 'id' => $mcache);
             } else {
                 // APC and XCache
                 self::$backend = array('type' => $ext);
             }
         }
         self::$buffer = NULL;
         return TRUE;
     }
     // Unknown back-end
     trigger_error(self::TEXT_Backend);
     return FALSE;
 }
示例#10
0
if ($a = $allan2->get('test2')) {
    print "Got value : " . $a . "<br>";
    var2($flags);
}
$flags = false;
if ($a = $allan3->get('test3')) {
    print "Got value : " . $a . "<br>";
    var2($flags);
}
$flags = false;
if ($a = $allan4->get('test4')) {
    print "Got value : " . $a . "<br>";
    var2($flags);
}
print "..<br>";
$memcache_obj = memcache_pconnect('127.0.0.1', 11211);
memcache_set($memcache_obj, 'test5', 'sdf2', false, 10);
memcache_set($memcache_obj, 'test6', true, false, 10);
memcache_set($memcache_obj, 'test7', false, false, 10);
$temp2 = array();
$temp = array($temp2);
memcache_set($memcache_obj, 'test8', $temp, false, 10);
#memcache_set($memcache_obj, 'test8', NULL, false, 10);
$flags = false;
if ($a = memcache_get($memcache_obj, 'test5', $flags)) {
    print "5:Got value : " . $a . "<br>";
    if ($flags) {
        print "Got flags";
    } else {
        print "No flags";
    }
示例#11
0
 /**
  * Lazy initialiser for memcache connection. Uses pconnect for to take
  * advantage of the persistence pool where possible.
  */
 private function connect()
 {
     if ($this->connection) {
         return;
     }
     if (class_exists("Memcached")) {
         $this->mc = new \Memcached();
         $this->mc->addServer($this->host, $this->port);
         $this->connection = true;
     } else {
         $this->connection = memcache_pconnect($this->host, $this->port);
     }
     if (!$this->connection) {
         $error = "Couldn't connect to memcache server";
         $this->log('error', $error);
         throw new CacheException($error);
     }
 }
示例#12
0
文件: F3.php 项目: seyyah/f3kulmysql
 /**
 		Initialize framework level-2 cache
 			@return boolean
 			@private
 	**/
 private static function prep()
 {
     if (!isset(F3::$global['CACHE'])) {
         // Extensions usable as cache back-ends
         $_exts = array_intersect(explode('|', 'apc|xcache'), get_loaded_extensions());
         foreach (array_keys($_exts, '') as $_null) {
             unset($_exts[$_null]);
         }
         $_exts = array_merge($_exts, array());
         F3::$global['CACHE'] = $_exts[0] ?: 'folder=' . F3::$global['BASE'] . 'cache/';
     }
     if (preg_match('/^(?:(folder)\\=(.+\\/)|(apc)|(memcache)=(.+))|(xcache)/i', F3::$global['CACHE'], $_match)) {
         if ($_match[1]) {
             if (!file_exists($_match[2])) {
                 if (!is_writable(dirname($_match[2])) && function_exists('posix_getpwuid')) {
                     $_uid = posix_getpwuid(posix_geteuid());
                     F3::$global['CONTEXT'] = array($_uid['name'], realpath(dirname($_match[2])));
                     trigger_error(F3::TEXT_Write);
                     return;
                 }
                 // Create the framework's cache folder
                 mkdir($_match[2], 0755);
             }
             // File system
             self::$l1cache = array('type' => 'folder', 'id' => $_match[2]);
         } else {
             $_ext = strtolower($_match[3] ?: ($_match[4] ?: $_match[6]));
             if (!extension_loaded($_ext)) {
                 F3::$global['CONTEXT'] = $_ext;
                 trigger_error(F3::TEXT_PHPExt);
                 return;
             }
             if ($_match[4]) {
                 // Open persistent MemCache connection(s)
                 // Multiple servers separated by semi-colon
                 $_pool = explode(';', $_match[5]);
                 $_mcache = NULL;
                 foreach ($_pool as $_server) {
                     // Hostname:port
                     list($_host, $_port) = explode(':', $_server);
                     if (is_null($_port)) {
                         // Use default port
                         $_port = 11211;
                     }
                     // Connect to each server
                     if (is_null($_mcache)) {
                         $_mcache = memcache_pconnect($_host, $_port);
                     } else {
                         memcache_add_server($_mcache, $_host, $_port);
                     }
                 }
                 // MemCache
                 self::$l1cache = array('type' => $_ext, 'id' => $_mcache);
             } else {
                 // APC and XCache
                 self::$l1cache = array('type' => $_ext);
             }
         }
         self::$l1cache['current'] = FALSE;
         return TRUE;
     }
     // Unknown back-end
     trigger_error(self::TEXT_Backend);
     return FALSE;
 }
示例#13
0
 /**
  * Lazy initialiser for memcache connection. Uses pconnect for to take
  * advantage of the persistence pool where possible.
  */
 private function connect()
 {
     if ($this->connection) {
         return;
     }
     if (class_exists("Memcached")) {
         $this->mc = new Memcached();
         $this->mc->addServer($this->host, $this->port);
         $this->connection = true;
     } else {
         $this->connection = memcache_pconnect($this->host, $this->port);
     }
     if (!$this->connection) {
         $error = "Couldn't connect to memcache server";
         $this->client->getLogger()->error($error);
         throw new Postman_Google_Cache_Exception($error);
     }
 }
 private function connect()
 {
     if (!($this->connection = @memcache_pconnect($this->host, $this->port))) {
         throw new Google_CacheException("Couldn't connect to memcache server");
     }
 }
示例#15
0
<?php 
error_reporting(E_ALL);
# Limit script runtime to 5 minutes
set_time_limit(300);
require_once "./config.default.php";
# If there are any overrides include them now
if (!is_readable('./config.php')) {
    echo "<H2>WARNING: Configuration file config.php does not exist. Please\n         notify your system administrator.</H2>";
} else {
    include_once './config.php';
}
######################################################
# Connect to memcache
######################################################
$memcache = memcache_pconnect($memcache_server, $memcache_port);
if ($memcache) {
    if (!isset($_GET['datetime'])) {
        $datetime = date('YmdH');
        $unixtime = time() - 7200;
    } else {
        $datetime = $_GET['datetime'];
        $unixtime = strtotime($datetime . "00");
    }
    $formatted_date = date('m/d/Y H', $unixtime);
    $time_prev = $unixtime - 3600;
    $prev_timeperiod = date('YmdH', $time_prev);
    $time_after = $unixtime + 3600;
    $next_timeperiod = date('YmdH', $time_after);
    ?>
Shows only GET requests with more than <?php 
 function connect_mcache($level = 3)
 {
     global $modSettings, $mcache, $db_persist;
     $servers = explode(',', $modSettings['cache_memcached']);
     $server = explode(':', trim($servers[array_rand($servers)]));
     // Don't try more times than we have servers!
     $level = min(count($servers), $level);
     if (empty($db_persist)) {
         $mcache = memcache_connect($server[0], empty($server[1]) ? 11211 : $server[1]);
     } else {
         $mcache = memcache_pconnect($server[0], empty($server[1]) ? 11211 : $server[1]);
     }
     if (!$mcache && $level > 0) {
         connect_mcache($level - 1);
     }
 }
示例#17
0
 /**
  * Lazy initialiser for memcache connection. Uses pconnect for to take
  * advantage of the persistence pool where possible.
  */
 private function connect()
 {
     if ($this->connection) {
         return;
     }
     if (class_exists("Memcached")) {
         $this->mc = new Memcached();
         $this->mc->addServer($this->host, $this->port);
         $this->connection = true;
     } else {
         $this->connection = memcache_pconnect($this->host, $this->port);
     }
     if (!$this->connection) {
         $error = "Couldn't connect to memcache server";
         $this->client->getLogger()->error($error);
         //throw new Google_Cache_Exception($error);
         echo json_encode(array('status' => FALSE, 'response-code' => 400, 'response' => $error, 'message' => ''));
         die;
     }
 }
示例#18
0
 /**
  * @return resource
  */
 function _conn($ns)
 {
     $id = $this->_keyNs[$ns]['daemon'];
     if (!isset($this->_conns[$id])) {
         $host = $this->_daemons[$id]['host'];
         $port = lor($this->_daemons[$id]['port'], 11211);
         $this->_conns[$id] = memcache_pconnect($host, $port);
         if (!$this->_conns[$id]) {
             $this->_conns[$id] = memcache_connect($host, $port);
         }
     }
     return $this->_conns[$id];
 }
示例#19
0
文件: F3.php 项目: seyyah/f3kayOLD
 /**
 		Initialize framework level-2 cache
 			@return boolean
 			@public
 	**/
 public static function prep()
 {
     if (preg_match('/^(apc)|(memcache)=(.+)|(xcache)|(folder)\\=(.+\\/)/i', F3::$global['CACHE'], $_match)) {
         if ($_match[5]) {
             if (!file_exists($_match[6])) {
                 if (!is_writable(dirname($_match[6])) && function_exists('posix_getpwuid')) {
                     $_uid = posix_getpwuid(posix_geteuid());
                     F3::$global['CONTEXT'] = array($_uid['name'], realpath(dirname($_match[6])));
                     trigger_error(F3::TEXT_Write);
                     return;
                 }
                 // Create the framework's cache folder
                 mkdir($_match[6], 0755);
             }
             // File system
             self::$backend = array('type' => 'folder', 'id' => $_match[6]);
         } else {
             $_ext = strtolower($_match[1] ?: ($_match[2] ?: $_match[4]));
             if (!extension_loaded($_ext)) {
                 F3::$global['CONTEXT'] = $_ext;
                 trigger_error(F3::TEXT_PHPExt);
                 return;
             }
             if ($_match[2]) {
                 // Open persistent MemCache connection(s)
                 // Multiple servers separated by semi-colon
                 $_pool = explode(';', $_match[3]);
                 $_mcache = NULL;
                 foreach ($_pool as $_server) {
                     // Hostname:port
                     list($_host, $_port) = explode(':', $_server);
                     if (is_null($_port)) {
                         // Use default port
                         $_port = 11211;
                     }
                     // Connect to each server
                     if (is_null($_mcache)) {
                         $_mcache = memcache_pconnect($_host, $_port);
                     } else {
                         memcache_add_server($_mcache, $_host, $_port);
                     }
                 }
                 // MemCache
                 self::$backend = array('type' => $_ext, 'id' => $_mcache);
             } else {
                 // APC and XCache
                 self::$backend = array('type' => $_ext);
             }
         }
         self::$l1cache = NULL;
         return TRUE;
     }
     // Unknown back-end
     trigger_error(self::TEXT_Backend);
     return FALSE;
 }
 private function connect() {
   if (! $this->connection = @memcache_pconnect($this->host, $this->port)) {
     throw new osapiStorageException("Couldn't connect to memcache server");
   }
 }
示例#21
0
function pagination_warm_prices($start_block_num, $block_start_id, $block_start_price, $end_block_num = PHP_INT_MAX)
{
    $mc_handler = memcache_pconnect('localhost');
    $pages_block_num = $start_block_num;
    $id = $block_start_id;
    $price = $block_start_price;
    $query_template = 'SELECT id, price FROM `%s` WHERE (price=%f AND id>=%d) OR price>%f ORDER BY price, id LIMIT %d, 1';
    $query = sprintf($query_template, DB_TABLE_NAME, $price, $id, $price, 0);
    $time = microtime(true);
    $item = __pagination_concurrent_create_warm_page($mc_handler, 'lock_warm_page_price_' . $pages_block_num, PAGINATION_WARM_PAGE_PRICE_PREFIX . $pages_block_num, $query);
    if (!$item) {
        return;
    }
    if (!isset($item['time'])) {
        //page wasn't in cache
        $id = $item['id'];
        $price = $item['price'];
        $page_block_data = ['id' => $id, 'price' => $price, 'time' => $time];
        memcache_set($mc_handler, PAGINATION_WARM_PAGE_PRICE_PREFIX . $pages_block_num, $page_block_data);
    }
    while ($pages_block_num < $end_block_num) {
        $query = sprintf($query_template, DB_TABLE_NAME, $price, $id, $price, PAGINATION_ROWS_PER_PAGE * PAGINATION_WARM_PAGES_STEP);
        $time = microtime(true);
        $item = __pagination_concurrent_create_warm_page($mc_handler, 'lock_warm_page_price_' . $pages_block_num, PAGINATION_WARM_PAGE_PRICE_PREFIX . $pages_block_num, $query);
        if ($item === false || count($item) == 0) {
            break;
        }
        $pages_block_num++;
        if (!isset($item['time'])) {
            $id = $item['id'];
            $price = $item['price'];
            $page_block_data = ['id' => $id, 'price' => $price, 'time' => $time];
            memcache_set($mc_handler, PAGINATION_WARM_PAGE_PRICE_PREFIX . $pages_block_num, $page_block_data);
        } else {
            $page_block_data = $item['time'];
        }
    }
    return $page_block_data;
}
 /**
  * @phutil-external-symbol function memcache_pconnect
  */
 private function getConnection($server)
 {
     if (empty($this->connections[$server])) {
         $spec = $this->servers[$server];
         $host = $spec['host'];
         $port = $spec['port'];
         $call_id = null;
         if ($this->getProfiler()) {
             $call_id = $this->getProfiler()->beginServiceCall(array('type' => 'kvcache-connect', 'name' => 'memcache', 'host' => $host));
         }
         $conn = memcache_pconnect($host, $spec['port']);
         if ($call_id) {
             $this->getProfiler()->endServiceCall($call_id, array());
         }
         if (!$conn) {
             throw new Exception("Unable to connect to memcache server ({$host}@{$port})!");
         }
         $this->connections[$server] = $conn;
     }
     return $this->connections[$server];
 }
示例#23
0
/**
 * Get memcache servers.
 *
 * - This function is used by cache_get_data() and cache_put_data().
 * - It attempts to connect to a random server in the cache_memcached setting.
 * - It recursively calls itself up to $level times.
 *
 * @param int $level = 3
 */
function get_memcached_server($level = 3)
{
    global $memcached, $db_persist, $cache_memcached;
    $servers = explode(',', $cache_memcached);
    $server = explode(':', trim($servers[array_rand($servers)]));
    $cache = function_exists('memcache_get') ? 'memcache' : (function_exists('memcached_get') ? 'memcached' : '');
    // Don't try more times than we have servers!
    $level = min(count($servers), $level);
    // Don't wait too long: yes, we want the server, but we might be able to run the query faster!
    if (empty($db_persist)) {
        if ($cache === 'memcached') {
            $memcached = memcached_connect($server[0], !isset($server[1]) ? 11211 : $server[1]);
        }
        if ($cache === 'memcache') {
            $memcached = memcache_connect($server[0], !isset($server[1]) ? 11211 : $server[1]);
        }
    } else {
        if ($cache === 'memcached') {
            $memcached = memcached_pconnect($server[0], !isset($server[1]) ? 11211 : $server[1]);
        }
        if ($cache === 'memcache') {
            $memcached = memcache_pconnect($server[0], !isset($server[1]) ? 11211 : $server[1]);
        }
    }
    if (!$memcached && $level > 0) {
        get_memcached_server($level - 1);
    }
}
示例#24
0
 private static function check($config)
 {
     global $_CONFIGS;
     if (!isset($_CONFIGS['DB'][$config])) {
         return "9001:No configuration found";
     }
     $init_cmds = array_filter(explode(",", isset($_CONFIGS['DB'][$config]['init_commnad']) ? $_CONFIGS['DB'][$config]['init_commnad'] : ''));
     $non_pdo = array('mysqli', 'mysql', 'mongo', 'memcache');
     $dns = str_replace("pdo_mysqli", "mysqli", $_CONFIGS['DB'][$config]['use']);
     //
     if (!in_array($dns, array('mysql', 'mysqli', 'pdo_mysql', 'mongo', 'memcache', 'pdo_pgsql'))) {
         return "9002:Driver not found";
     }
     //
     if ($dns === 'mysql') {
         if (!function_exists('mysql_connect')) {
             return "9005:mysql extension not found.";
         }
         $mysqllink = null;
         $server = is_int($_CONFIGS['DB'][$config]['port']) ? "{$_CONFIGS['DB'][$config]['host']}:{$_CONFIGS['DB'][$config]['port']}" : ":{$_CONFIGS['DB'][$config]['port']}";
         $username = $_CONFIGS['DB'][$config]['user'];
         $password = $_CONFIGS['DB'][$config]['password'];
         $newlink = isset($_CONFIGS['DB'][$config]['newlink']) && $_CONFIGS['DB'][$config]['newlink'] == true;
         $persistent = isset($_CONFIGS['DB'][$config]['persistent']) && $_CONFIGS['DB'][$config]['persistent'] == true;
         $client_flags = isset($_CONFIGS['DB'][$config]['driver_options']) ? $_CONFIGS['DB'][$config]['driver_options'] : 0;
         $charset = isset($_CONFIGS['DB'][$config]['charset']) ? $_CONFIGS['DB'][$config]['charset'] : false;
         $_CONFIGS['DB'][$config]['_default_charset'] = isset($_CONFIGS['DB'][$config]['_default_charset']) ? $_CONFIGS['DB'][$config]['_default_charset'] : '';
         if (!$persistent) {
             $mysqllink = @mysql_connect($server, $username, $password, $newlink, $client_flags);
         } else {
             $mysqllink = mysql_pconnect($server, $username, $password, $client_flags);
         }
         if (!$mysqllink) {
             return mysql_errno() . ":" . mysql_error();
         }
         $database = $_CONFIGS['DB'][$config]['database'];
         if (!mysql_select_db($database, $mysqllink)) {
             return mysql_errno($mysqllink) . ":" . mysql_error($mysqllink);
         }
         if ($persistent && $charset) {
             if (!isset($_CONFIGS['DB'][$config]['_default_charset'])) {
                 $ret = mysql_query("SHOW VARIABLES LIKE 'character_set_results'", $mysqllink);
                 $_charset = @mysql_fetch_assoc($ret);
                 $_CONFIGS['DB'][$config]['_default_charset'] = isset($_charset['Value']) ? $_charset['Value'] : '';
             }
         }
         if ($charset && !@mysql_query("SET SESSION character_set_results = '{$charset}'", $mysqllink)) {
             return @mysql_errno($mysqllink) . ":" . @mysql_error($mysqllink);
         }
         return array($mysqllink, $dns, $config, '', 'charset' => $charset);
     }
     if ($dns === 'mysqli') {
         //
         if (!class_exists('MySQLi')) {
             return "9003:MySQLi class not found.";
         }
         $MySQLi = mysqli_init();
         if (!$MySQLi) {
             return "9004:Unable to Initialise MySQLi.";
         }
         @mysqli_options($MySQLi, MYSQLI_INIT_COMMAND, 'SET AUTOCOMMIT = 1');
         @mysqli_options($MySQLi, MYSQLI_OPT_CONNECT_TIMEOUT, 60);
         if (isset($_CONFIGS['DB'][$config]['charset'])) {
             @mysqli_set_charset($MySQLi, $_CONFIGS['DB'][$config]['charset']);
         }
         @mysqli_real_connect($MySQLi, $_CONFIGS['DB'][$config]['host'], $_CONFIGS['DB'][$config]['user'], $_CONFIGS['DB'][$config]['password'], $_CONFIGS['DB'][$config]['database'], $_CONFIGS['DB'][$config]['port'], null, MYSQLI_CLIENT_COMPRESS | MYSQLI_CLIENT_FOUND_ROWS);
         if (mysqli_connect_errno($MySQLi)) {
             return mysqli_connect_errno($MySQLi) . ':' . mysqli_connect_error($MySQLi);
         }
         return array($MySQLi, $dns, $config, '');
     }
     if ($dns === 'mongo') {
         if (!class_exists('MongoClient')) {
             return "9005:Mongo class not found.";
         }
         $user_pass = isset($_CONFIGS['DB'][$config]['user']) ? $_CONFIGS['DB'][$config]['user'] : '';
         $user_pass .= ":" . (isset($_CONFIGS['DB'][$config]['pass']) ? $_CONFIGS['DB'][$config]['pass'] : '') . "@";
         if (!isset($_CONFIGS['DB'][$config]['user']) || empty($_CONFIGS['DB'][$config]['user'])) {
             $user_pass = '';
         }
         $driver = "mongodb://{$user_pass}" . $_CONFIGS['DB'][$config]['host'] . ":" . $_CONFIGS['DB'][$config]['port'] . ($_CONFIGS['DB'][$config]['database'] === '' ? '' : "/{$_CONFIGS['DB'][$config]['database']}");
         if (stripos($_CONFIGS['DB'][$config]['host'], 'mongodb://') === 0) {
             $driver = $_CONFIGS['DB'][$config]['host'];
         }
         $m_options = isset($_CONFIGS['DB'][$config]['options']) ? $_CONFIGS['DB'][$config]['options'] : array();
         $driver_options = isset($_CONFIGS['DB'][$config]['driver_options']) ? $_CONFIGS['DB'][$config]['driver_options'] : array();
         try {
             $conn = new MongoClient($driver, $m_options, $driver_options);
         } catch (Exception $e) {
             return "9006:Could not connect to host.";
         }
         return array($conn, $dns, $config, '');
     }
     if ($dns === 'memcache') {
         if (!function_exists('memcache_connect')) {
             return "9007:memcache class not found.";
         }
         $conn = null;
         $timeout = 1;
         $timeout = isset($_CONFIGS['DB'][$config]['timeout']) ? (int) $_CONFIGS['DB'][$config]['timeout'] : $timeout;
         if (isset($_CONFIGS['DB'][$config]['persistent']) && $_CONFIGS['DB'][$config]['persistent'] && function_exists('memcache_pconnect')) {
             $conn = @memcache_pconnect($_CONFIGS['DB'][$config]['host'], $_CONFIGS['DB'][$config]['port'], $timeout);
         } else {
             $conn = @memcache_pconnect($_CONFIGS['DB'][$config]['host'], $_CONFIGS['DB'][$config]['port'], $timeout);
         }
         if ($conn == null or $conn == false) {
             return "9008:Could not connect to host.";
         }
         return array($conn, $dns, $config, '');
     }
     // Else PDO
     $dns = explode("_", $dns);
     if ($dns[0] !== 'pdo') {
         return "9009:invalid pdo driver";
     }
     if (!class_exists('PDO')) {
         return "9010:pdo class not found";
     }
     if (!in_array($dns[1], PDO::getAvailableDrivers())) {
         return "9010:pdo driver not found";
     }
     $options = array();
     //PDO::ATTR_ERRMODE=>PDO::ERRMODE_SILENT);
     $PDO_DSN = "{$dns[1]}:dbname={$_CONFIGS['DB'][$config]['database']};host={$_CONFIGS['DB'][$config]['host']};port={$_CONFIGS['DB'][$config]['port']}";
     try {
         $conn = new PDO($PDO_DSN, $_CONFIGS['DB'][$config]['user'], $_CONFIGS['DB'][$config]['password'], $options);
     } catch (PDOException $e) {
         return "{$e->getCode()}:{$e->getMessage()}";
     }
     $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
     foreach ($init_cmds as $key => $value) {
         try {
             $keyval = explode("=", $value);
             $key = preg_replace("/[^a-z:_0-9]/i", "", $keyval[0]);
             $val = preg_replace("/[^a-z_:0-9]/i", "", $keyval[1]);
             eval("\$key={$key};");
             eval("\$val={$val};");
             @$conn->setAttribute($key, $val);
         } catch (PDOException $e) {
         }
     }
     return array($conn, join("_", $dns), $config, '');
 }
示例#25
0
 /**
  * Lazy initialiser for memcache connection. Uses pconnect for to take 
  * advantage of the persistence pool where possible. 
  */
 private function connect()
 {
     if ($this->connection) {
         return;
     }
     if (class_exists("Memcached")) {
         $this->mc = new Memcached();
         $this->mc->addServer($this->host, $this->port);
         $this->connection = true;
     } else {
         $this->connection = memcache_pconnect($this->host, $this->port);
     }
     if (!$this->connection) {
         throw new Google_Cache_Exception("Couldn't connect to memcache server");
     }
 }
 /**
  * @phutil-external-symbol function memcache_pconnect
  */
 private function getConnection($server)
 {
     if (empty($this->connections[$server])) {
         $spec = $this->servers[$server];
         $host = $spec['host'];
         $port = $spec['port'];
         $conn = memcache_pconnect($host, $spec['port']);
         if (!$conn) {
             throw new Exception(pht('Unable to connect to memcache server (%s:%d)!', $host, $port));
         }
         $this->connections[$server] = $conn;
     }
     return $this->connections[$server];
 }
示例#27
0
文件: Load.php 项目: alencarmo/OCF
function get_memcached_server($level = 3)
{
    global $modSettings, $memcached, $db_persist;
    $servers = explode(',', $modSettings['cache_memcached']);
    $server = explode(':', trim($servers[array_rand($servers)]));
    // Don't try more times than we have servers!
    $level = min(count($servers), $level);
    // Don't wait too long: yes, we want the server, but we might be able to run the query faster!
    if (empty($db_persist)) {
        $memcached = memcache_connect($server[0], empty($server[1]) ? 11211 : $server[1]);
    } else {
        $memcached = memcache_pconnect($server[0], empty($server[1]) ? 11211 : $server[1]);
    }
    if (!$memcached && $level > 0) {
        get_memcached_server($level - 1);
    }
}
 /**
  * Trigger to open the session
  * @param string $path
  * @param string $name
  */
 public function sessionOpen($path, $name)
 {
     $this->prefix = $path . $name;
     $this->memcache = memcache_pconnect($this->host, $this->port);
 }