search
HomeBackend DevelopmentPHP TutorialPHP calls memcache to store session


When php calls memcache to store the session in the following way, remember to set session.auto_start = 0 in

/usr/local/php/etc/php.ini to 0, otherwise calling memcache to store the session will not take effect. of.

The reason is: when php executes the first line, the session will be automatically started, and the default is files, so the session will be saved through the file by default, and the ini_set configured later will be useless.

// Session setting

Method 1:

This method is used in the production environment, there is no problem.

Add an initialization command at the beginning of the line of the php code file.

ini_set("session.save_handler", "memcache");

#If you need to configure multiple memcache addresses, just separate them with commas.

#ini_set("session.save_path", "tcp://127.0.0.1:11211,tcp://127.0.0.1:11212");

ini_set("session.save_path", "tcp://127.0 .0.1:11211");

session_start();

Method 2:

This method is to write a memcache node, which has been used in the production environment, and the IP addresses of the two memcache configurations have not been verified.

Set directly /usr/local/php/etc/php.ini

session.save_handler = memcache

session.save_path = "tcp://127.0.0.1:11211"

set_session.php

# ################################################ ########

ini_set("session.save_handler", "memcache");

ini_set("session.save_path", "tcp://10.12.4.25:11211, tcp://10.12.4.25:11212");
session_start();
$_SESSION['TEST3'] = time();
print $_SESSION['TEST3'];
print session_id();
?>

After accessing set_session.php through the browser, we can telnet 10.12.4.25 11211 to check whether the session value really exists, and it is proved that it is only saved on one of the memcache nodes

get rtv10q183u28kmmtfpi0bd5nq6

# ################################################ #########

Experiment whether the storage is distributed on multiple memcache nodes after configuring multiple memcache nodes

################### ################################################ ########

1. Configure memcache for multiple nodes, and then assign values ​​to them. You will find that they are scattered and stored on multiple nodes

$memcache = new Memcache;
$memcache ->addServer('10.12.4.25', 11211);
$memcache->addServer('10.12.4.25', 11212);
$memcache->addServer('10.12.4.25', 11213);
for ($i = 0; $i {
$memcache->set($i, $i."hehe", 0, 1000);
}
for ($i = 0; $i {
$val = $memcache->get("$i");
echo "Get $i key1 value: " . $val ."
}
?>

Through get_memcache.php you can see that the data is indeed scattered across multiple nodes.

echo '10.12.4.25 11211
';
$memcache = new Memcache;
$memcache->addServer('10.12.4.25', 11211);
#$memcache->addServer ('10.12.4.25', 11213);
for ($i = 0; $i {
$val = $memcache->get("$i");
echo "Get $i key1 value: " . $val ."
n";
}
echo '10.12.4.25 11212
';
$memcache = new Memcache;
$memcache->addServer ('10.12.4.25', 11212);
for ($i = 0; $i {
          $val = $memcache->get("$i");
            echo "Get $i key1 value: " . $val ."
n";
}
echo '10.12.4.25 11213
';
$memcache = new Memcache;
$memcache->addServer('10.12. 4.25', 11213);
for ($i = 0; $i {
          $val = $memcache->get("$i");
                                          using   using                    : " . $val ."
n";
}
?>

is used to clear the memcache value through clean_memcache.php, clear all, and then re-assign and check to see if there is any problem. It was found that the storage was indeed dispersed.

clean_memcache.php

$memcache = new Memcache;
$memcache->connect('10.12.4.25', 11211);
$memcache->addServer('10.12.4.25', 11212 );
$memcache->addServer('10.12.4.25', 11213);
#$memcache->addServer('10.12.4.25', 11214);
$memcache->flush();
?> ;

When php calls memcache to store the session in the following way, remember to set session.auto_start = 0 in

/usr/local/php/etc/php.ini to 0, otherwise, call memcache to store the session. is ineffective.

//session settings

ini_set("session.save_handler", "memcache");

#ini_set("session.save_path", "tcp://127.0.0.1:11211,tcp://127.0.0.1:11212");

ini_set("session.save_path", "tcp://127.0. 0.1:11211");

session_start();

The above introduces how PHP calls memcache to store sessions, including the content. I hope it will be helpful to friends who are interested in PHP tutorials.

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools