Memcached passing data using php - php

I have installed memcached 1.4.4-14 on my windows systems. I have started the service and everything is in order. Now all I am trying to do is test it using .php which is served using IIS.
So I right a basic index.php page and browse through IIS. I can render the page and general .php works. Its just nothing happens with the memcache. There is so much confusion out there about what pre-requisites I need to install. I can't fathom which ones are essential. The PHP I installed is a new clean install with only the php_memcache.dll extensions dumped in .php.
It is worth noting that in phpinfo I can see no reference to memcache.
Would love some basic assistance.
Here is my example that I am using, I believe it is the standard test for memcache session dump.
session_start();
header("Content-type: text/plain");
$memcache = new Memcache;
$memcache->connect("localhost",11211); # You might need to set "localhost" to "127.0.0.1"5
echo $memcache->get(session_id());
Thank you.

If you're interested in using compression, please note that, at least for PHP version 5.3.2 and Memcache version 3.0.4, when retrieving a key who's value is a numeric or boolean type, PHP throws a notice of the following:
Message: MemcachePool::get(): Failed to uncompress data
The way around this is to test your variable type before setting or adding it to Memcache, or even cast it as a string.
<?php
$key = 'mc_key';
$value = 12345;
$compress = is_bool($value) || is_int($value) || is_float($value) ? false : MEMCACHE_COMPRESSED;
$mc= new Memcache;
$mc->connect('localhost', 11211);
$mc->set($key, $value, $compress);
echo $mc->get($key);
//Alternative is to cast the variable
$value = is_scalar($value) ? (string)$value : $value;
$mc->set($key, $value, MEMCACHE_COMPRESSED);
?>

Related

Introduction to Memcached

I am trying to use Memcached right now, and I am a little confuse about this:
First, do I need to make a class for Memcached? like this: click me! or is it automatically works? do I just need to make a connection to the memcached server and then I can cache data?
UPDATE
When I tried to use the code exiang provided, my output in all of the var_dumps are boolean false. Anybody knows why is this happened?
UPDATE PART 2
When I tried to use this code echo $m->getResultMessage(),"\n"; it returns:
SERVER HAS FAILED AND IS DISABLED UNTIL TIMED RETRY
make sure you have enabled the php memcache module, it looks like this in your phpinfo
Make sure your memcached server is running
Then, you can use it directly like this:
http://php.net/manual/en/memcached.set.php
<?php
$m = new Memcached();
$m->addServer('localhost', 11211);
$m->set('int', 99);
$m->set('string', 'a simple string');
$m->set('array', array(11, 12));
/* expire 'object' key in 5 minutes */
$m->set('object', new stdclass, time() + 300);
var_dump($m->get('int'));
var_dump($m->get('string'));
var_dump($m->get('array'));
var_dump($m->get('object'));
?>

PHP filter_input(INPUT_SERVER, 'REQUEST_METHOD') returns null?

Why does this line return null in my live server?
filter_input(INPUT_SERVER, 'REQUEST_METHOD');
The live server is php5.5.9
Have I missed something?
I thought it is used to replace the global method below?
$_SERVER['REQUEST_METHOD'];
some of the code,
public function __construct()
{
// Construct other generic data.
$this->clientRequestMethod = filter_input(INPUT_GET, 'method'); // such as list, add, update, etc
$this->clientPostMethod = filter_input(INPUT_POST, 'method'); // such as update
$this->serverRequestMethod = filter_input(INPUT_SERVER, 'REQUEST_METHOD'); //such as get or post
}
public function processEntry()
{
// Determine the $_SERVER['REQUEST_METHOD'] whether it is post or get.
if ($this->serverRequestMethod === 'POST' && $this->clientPostMethod != null)
{
$this->processPost();
}
else if($this->serverRequestMethod === 'GET' && $this->clientRequestMethod != null)
{
$this->processRequest();
}
}
So the problem/bug is this:
filter_input() doesn't work with INPUT_SERVER or INPUT_ENV when you use FASTCGI
The bug has been known for years and I found nothing saying it was addressed. I found several work-arounds but no complete solution so I plopped the best work-around into this helper function for a project-wide solution. To provide some level of security and avoid train wrecks, the function falls back to filter_var() where filter_input() fails. It uses the same format as the native filter_input() function for easy integration into projects and easy future removal should the bug ever be fixed.
function filter_input_fix ($type, $variable_name, $filter = FILTER_DEFAULT, $options = NULL )
{
$checkTypes =[
INPUT_GET,
INPUT_POST,
INPUT_COOKIE
];
if ($options === NULL) {
// No idea if this should be here or not
// Maybe someone could let me know if this should be removed?
$options = FILTER_NULL_ON_FAILURE;
}
if (in_array($type, $checkTypes) || filter_has_var($type, $variable_name)) {
return filter_input($type, $variable_name, $filter, $options);
} else if ($type == INPUT_SERVER && isset($_SERVER[$variable_name])) {
return filter_var($_SERVER[$variable_name], $filter, $options);
} else if ($type == INPUT_ENV && isset($_ENV[$variable_name])) {
return filter_var($_ENV[$variable_name], $filter, $options);
} else {
return NULL;
}
}
This seems the best solution. Please let me know if it contains errors that might cause issues.
I had the same problem where it was working on my local machine (OSX Mavericks, PHP version 5.4.24) and not on my live server (Cent OS 5). I upgraded the server from 5.3.9 to 5.5.15 (and added the mb and mcrypt functions although that's probably irrelevant) and now it works.
This probably isn't helpful if you're on a shared host but you could ask them if they can rebuild PHP/Apache.
I was having the same issue in my XAMPP localhost as well and was looking for solutions madly. What I ended up with, it is a known PHP bug for this function if you are running the PHP in FCGI mode (FCGI/PHP 5.4 in my case). I was confirmed going through this link.
The workaround I used is to filter_var($_SERVER['PHP_AUTH_USER'], FILTER_SANITIZE_STRING) but this is not an alternative of filter_input. filter_input is more secure.
FastCGI seems to cause strange side-effects with unexpected null values when using INPUT_SERVER and INPUT_ENV with this function. You can use this code to see if it affects your server.
If you want to be on the safe side, using the superglobal $_SERVER and $ENV variables will always work. You can still use the filter* functions for Get/Post/Cookie without a problem, which is the important part!
Source: http://php.net/manual/es/function.filter-input.php#77307
I solve it changing my php.ini from:
variables_order = "GPCS"
To:
variables_order = "GPCSE"
By default PHP wasn't registering the environment variables, so this change enabled them. The interesting is that the INPUT_SERVER variables came back to work too!
Just two addiotional informations, i am using PHP 7.0.13 and as said in other answers, this issue is related to a PHP bug.
Another option is use the following:
filter_var(getenv('REQUEST_METHOD'));
My personal solution was to change filter_input to filter_var :
With filter_input (not working on a Siteground shared hosting):
filter_input(INPUT_SERVER, 'REQUEST_URI')
With filter_var (now it works on Siteground)
filter_var($_SERVER['REQUEST_URI'],FILTER_UNSAFE_RAW, FILTER_NULL_ON_FAILURE)
The problem affects Apache + fcgid + php-cgi 8.1.9 too.
It't caused by auto_globals_jit enabled (default) . When disabled (in php.ini on php startup), filter_input(INPUT_SERVER) works correctly.

PHP Memcached Session Locking Enable

I use "memcached" to store php sessions.
It is important, that request must be synchronously (to avoid duplicate transactions or operations), but while using "memcached" session, "session locking" not works.
is some method to lock "memcached" session until one request will executed?
There's nothing built in no, but you can write stuff yourself to make your code atomic.
$key = 'lockable_key_name';
$lockkey = $key.'##LOCK';
if($memcached->add($lockkey, '', 60)) {
$storedvalue = $memcached->get($key);
// do something with $storedvalue
$memcached->set($key, $newvalue);
// release
$memcached->delete($lockkey);
}
In your code you could check for the lock by doing:
if(!$memcached->get($lockkey)) {
// then do something
}
If the get method returns false then there's no lock, or the operation has hung and passed the 60 second timeout specified in the add call above.
Since you were asking for credible/official sources:
The memcached extension supports session locking since version 3.0.4, according to the changelog document on the PECL extension page: http://pecl.php.net/package-info.php?package=memcache&version=3.0.4
If you happen to run an earlier version (it means that your version of the memcached extension is more than 4 years old), you are out of luck and should upgrade.
Maybe try something like $(field_name)_is_locked = true when you start then when you are done $(field_name)_is_locked = false and pass the variable to the server when you update it.

Why is DOMDocument not working with WAMP server?

I’m using DOMDocument to retrieve several bits of text from a webpage and place them into an array. The same code works on another server, yet doesn’t on mine. I get Trying to get property of non-object for each iteration of the while loop and the array remains empty at the end.
$html = file_get_contents("http://sugarkettle.site44.com/catering.html");
$doc = new DOMDocument();
libxml_use_internal_errors(true);
$doc->loadHTML($html);
libxml_clear_errors();
$meatPrices = array();
function fillArrayFromDOM($array,$type) {
global $doc;
$i = 0;
$label = 1;
$array = array();
while ($label <= 15):
$array[$i] = $doc->getElementById($type.$label)->textContent;
$i++;
$label++;
endwhile;
return $array;
}
fillArrayFromDOM($meatPrices,"meat");
echo var_dump($meatPrices);
Here’s a link to it working:
http://www.evintr.com/willtest.php
He’s running a GoDaddy server and I have a local WAMP (2.2) server. Any configuration options I can provide that might explain why this is happening? Or does the problem have nothing to do with my server config?
Any help much appreciated. Thanks in advance!
Update 1 - 11/16/12
On my server, I've tested $meatPrices[1] = $doc->getElementById('meat1')->textContent; and it works. For whatever reason, inside the while loop the same expression (except with variables in the getElementById parameters) tosses an error: Trying to get property of non-object.
Update 2 - 11/17/12
My WAMP server is running PHP version 5.3.13.
My friend's server is running PHP version 5.3.6.
Try with adding allow_url_fopen=on in your PHP configuration file (php.ini). Save it and restart Apache; it should work...
EDIT:
Check also if you have extension php_openssl.dll enabled (extension=php_openssl.dll in your php.ini file). Again, restart of Apache would be required.
EDIT:
It depends on PHP version you have but here are two potential solutions:
replace line fillArrayFromDOM($meatPrices,"meat"); with
$meatPrices = fillArrayFromDOM($meatPrices,"meat"); You can also
change your function to remove necessary $meatPrices parameter).
or
replace line function fillArrayFromDOM($array,$type) { with function fillArrayFromDOM(&$array,$type) { //note new character &; it will keep reference to $array variable so it could be changeable; you can also remove line: $array = array();
Both should work; I am in rush have no time to wait on your comment response. Let us know what you get...

apc_exist() does not exist?

I'm having some hard time getting PHP APC to work. Here's my test code:
<form>
<input type="text" name="apc">
<input type="submit">
</form>
<?php
apc_store('foo','FOO');
if (isset($_GET['apc'])) {
apc_store($_GET['apc'],$_GET['apc']);
}
?>
<pre>CACHE INFO (USER): <?php print_r(apc_cache_info("user",false)); ?></pre>
<pre>CACHE INFO: <?php print_r(apc_cache_info()); ?></pre>
<pre>FOO: <?php print_r(apc_fetch("foo")); ?></pre>
<pre>BAR: <?php print_r(apc_fetch("bar")); ?></pre>
<pre><?php if (apc_exists("bar")) { ?>bar exists!<?php } else { ?>bar does not exist!<?php } ?></pre>
<?php apc_clear_cache(); ?>
In short: you fill the form and the inserted value gets stored in APC. The key "foo" is always stored. You can try storing "bar" to see apc_fetch() working with a newly added key.
What works OK:
apc_store()
apc_fetch()
What does not:
apc_cache_info() (regardless of which parametres I pass to the function) always prints an empty array, despite apc_fetch() retrieving data successfully
apc_clear_cache() never clears the cache ("bar" is always displayed once input). This is true both if I provide a "user" parametre or leave the function with no parametres.
calling apc_exists() yields a fatal error: call to undefined function apc_exists()
In case it's helpful: I'm running Zend Server CE 5.6.0 (fresh install, finished half an hour ago), with PHP 5.3.9. Same happened with a more antique version of Zend Server CE yesterday (running PHP 5.3.5). I do not know which version of APC ships with Zend Server, phpinfo() only shows APC is enabled. I am on a Windows machine (Windows 7 Professional, 32 bit).
So. What's wrong here? Issues with my code? Maybe Zend Server ships with an older version of APC that just is buggy and/or does not support the functions I'm trying to use? Any clues?
[EDIT]
Inspired by clues provided by #Hannes, I modified the code, adding:
<?php
if (!function_exists('apc_exists') {
function apc_exists($key) { return (boolean)apc_fetch($key); }
}
?>
Since no error is raised, the code passes to the next line and the cache is cleared OK. This must have been why it wasn't cleared in the first place.
Still, apc_cache_info() doesn't return anything...
apc_exists is available for PECL apc >= 3.1.4 http://www.php.net/manual/en/function.apc-exists.php so your APC Version is probbaly lower, but its basically just a boolean wraper anyhow, a simple function shoud basically do the same:
function user_apc_exists($key){ return (bool) apc_fetch($key); }
in both cases your didint provide information for which cache to use, your probaby want user:
apc_clear_cache('user');
apc_cache_info('user);
http://www.php.net/manual/en/function.apc-clear-cache.php
http://www.php.net/manual/en/function.apc-cache-info.php
I ran across the same problem and after some debugging found out that the function in Hannes' answer works unless the stored data is a boolean false or an empty array.
This works also in those cases:
if (!function_exists('apc_exists')) {
function apc_exists($key) {
$success = false;
apc_fetch($key, $success);
return $success;
}
}

Categories