Current Location: Home> Latest Articles> Essential Guide for PHP Developers: Common Memcache Issues and Practical Code Examples

Essential Guide for PHP Developers: Common Memcache Issues and Practical Code Examples

M66 2025-07-10

Introduction

In modern web development, caching technologies are essential tools for optimizing performance and improving response times. Among caching solutions in PHP environments, Memcache is widely used. Despite its power, developers may encounter questions during implementation. This article addresses common operational issues with Memcache and provides clear code examples to help PHP developers quickly master Memcache techniques.

How to Connect and Close a Memcache Server

Basic code to connect to a Memcache server:

$memcache = new Memcache;
$memcache->connect('localhost', 11211);

Example code to close the connection:

$memcache->close();

How to Store and Retrieve Data

Example of storing data:

$memcache->set('key', 'value', MEMCACHE_COMPRESSED, 3600);

Example of retrieving data:

$data = $memcache->get('key');

How to Check if Data Exists

Determine if data exists by checking the returned value:

$data = $memcache->get('key');
if ($data === false) {
    echo 'Data does not exist in Memcache';
} else {
    echo 'Data is cached in Memcache';
}

How to Delete Data

Delete specified cached data:

$memcache->delete('key');

How to Increment and Decrement Values

Increment a cached value:

$memcache->increment('key', 1);

Decrement a cached value:

$memcache->decrement('key', 1);

How to Get and Set Expiration Time

Example of retrieving expiration time:

$expiration = $memcache->get('key', MEMCACHE_GET_EXTENDED);
echo $expiration['expiration'];

Setting cache expiration time:

$memcache->set('key', 'value', 0, 3600);

How to Handle Adding Existing Data

The add() method returns false if the key already exists:

$result = $memcache->add('key', 'value', MEMCACHE_COMPRESSED, 3600);
if ($result === false) {
    echo 'Data already exists in Memcache';
}

How to Handle Replacing Non-Existent Data

The replace() method returns false if the data does not exist:

$result = $memcache->replace('key', 'value', MEMCACHE_COMPRESSED, 3600);
if ($result === false) {
    echo 'Data does not exist in Memcache';
}

How to Handle Connection Failures

If connection to the main server fails, try connecting to a backup server:

$memcache->addServer('backup-server', 11211);
$connected = $memcache->getVersion();
if ($connected !== false) {
    echo 'Connected to backup server';
} else {
    echo 'Failed to connect to backup server';
}

Conclusion

This article summarizes common Memcache operation issues faced by PHP developers, accompanied by practical code samples. Using caching effectively can significantly improve website performance and user experience. We hope this guide helps you work more efficiently with Memcache in your projects. Happy coding!