Server environment
1 | $ cat /etc/issue |
Session in PHP has two problem in a web project.
- If cookie is disable in client browser
- How to synchronize session
Session base usage in PHP
1 | session_start(); //Start session |
Different sub-domains direct to the same server:
There are three way to do this.
- Add this code at the beginning of the php page (before any output and before the method session_start() )
1 | ini_set('session.cookie_path', '/'); |
or
1 | session_set_cookie_params(1800 , '/', '.mydomain.com'); |
- Point to domain forever in php configuration file php.ini:
1
2
3session.cookie_path = /
session.cookie_domain = .mydomain.com
session.cookie_lifetime = 1800
The above methods have the same effect.
Different sub-domains direct to different server:
Use NFS to share session
- If session number is relatively large and all session files are under the same directory
- If NFS Server get malfunction
- If NFS network can not be connected
It may causes a serious load problem
There will be three server machine
NFS | Hostname | IP |
---|---|---|
Server | site1 | 192.168.33.10 |
Client | site2 | 192.168.33.11 |
Client | site3 | 192.168.33.12 |
Step 1. Change PHP session storage directory
Step 2. Install NFS on each server machine
Step 3. NFS clients mount to the main server then share the main server ‘s session directory
Server
Use /tmp/php_sess as the session sharing directory
1 | $ mkdir /tmp/php_sess |
Direct php session save path to redis
1 | $ sudo vim /etc/php/5.6/apache2/php.ini |
Restart apache
1 | $ sudo service apache2 restart |
Install NFS client
1 | $ sudo apt-get install -y nfs-kernel-server |
Limit NFS client connecting ip
1 | $ sudo vim /etc/exports |
Restart NFS service
1 | $ sudo service nfs-kernel-server restart |
Client
Use /tmp/php_sess as the session sharing directory
1 | $ mkdir /tmp/php_sess |
Install NFS client
1 | $ sudo apt install -y nfs-common |
Show NFS server info
1 | $ sudo showmount -e 192.168.33.10 |
Mount the directory
1 | $ sudo mount 192.168.33.10:/tmp/php_sess /tmp/php_sess |
Check NFS mount result
1 | $ ls -lh /tmp/php_sess/ |
Direct php session save path to redis
1 | $ sudo vim /etc/php/5.6/apache2/php.ini |
Restart apache
1 | $ sudo service apache2 restart |
Mount NFS share directory automatically as machine boot
1 | $ sudo vim /etc/fstab |
Different domains direct to different server:
Install redis
1 | $ sudo apt-get install -y redis-server |
Bind redis ip
1 | $ sudo vim /etc/redis/redis.conf |
Restart redis
1 | $ sudo service redis-server restart |
Install php-redis extension
1 | $ sudo apt-get install -y php5.6-redis |
Direct the session save path to redis in php
1 | $ sudo vim /etc/php/5.6/apache2/php.ini |
Restart apache
1 | $ sudo service apache2 restart |