sudo apt-get install memcached sudo apt-get install php-memcached
After installation, you need to enable the Memcache extension in the php.ini file. You can find the location of the php.ini file by running this command:
php -i | grep php.ini
Once you locate the php.ini file, open it with a text editor and find the following line:
;extension=memcached.so
Change it to:
extension=memcached.so
Save and exit the editor, then restart your web server to apply the changes.
$memcache = new Memcache();
Next, use the connect() method to connect to the Memcache server by specifying the IP address and port number:
$memcache->connect('127.0.0.1', 11211);
$key = 'username'; $value = 'John Doe'; $expiration = 3600; // Expiration time is 1 hour $memcache->set($key, $value, 0, $expiration);
This code stores the data with the key username and value John Doe in Memcache, setting the expiration time to 1 hour.
To retrieve data from Memcache, use the get() method, passing the key as a parameter:
$key = 'username'; $data = $memcache->get($key); if ($data !== false) { // Data exists echo "Username: " . $data; } else { // Data does not exist or has expired echo "Username not found"; }
This code attempts to retrieve data from Memcache using the username key. If the data exists, it will display the username; otherwise, it will show a message indicating the data was not found or has expired.
$key = 'username'; $memcache->delete($key);
This code will delete the data associated with the username key in Memcache.
$memcache = new Memcache(); $memcache->connect('127.0.0.1', 11211); function getUserData($userId) { global $memcache; $key = 'user_' . $userId; $userData = $memcache->get($key); if ($userData === false) { // Fetch user data from the database $userData = getUserDataFromDatabase($userId); $expiration = 3600; // Expiration time is 1 hour $memcache->set($key, $userData, 0, $expiration); } return $userData; } $userId = 123; $userData = getUserData($userId); echo "User Name: " . $userData['name']; echo "Email: " . $userData['email'];
This code defines a getUserData() function that retrieves user data. The function first attempts to fetch data from Memcache. If the data doesn't exist, it will fetch it from the database and store it in Memcache for future use. Each time data is requested, it will be fetched from Memcache unless it has expired, in which case the database will be queried again.