PHP SESSION Principle
Session is a method to maintain user session data on the server side, and the corresponding cookie is to maintain user data on the client side. The HTTP protocol is a stateless protocol. After the server responds, it loses contact with the browser. Cookies are introduced into the browser, allowing data to be exchanged across pages.
First, the client and the server establish a one-to-one relationship. Each client has a unique identifier so that the server can identify it. It is recommended that there are two methods of unique identification: cookie or specified through GET. The default configuration of PHP will create a cookie named "PHPSESSID" when using a session (can be specified by modifying the session.name value in php.ini). If the client disables cookies, you can also specify to pass the session id to via GET. Server (modify parameters such as session.use_trans_sid in php.ini).
The client passes the session id to the server, and the server finds the corresponding file based on the session id. When reading, it deserializes the file content to get the session value. When saving, it is serialized first and then written.
This is the fact. If the server does not support session or you want to customize the session, you can DIY it. Use PHP's uniqid to generate a session id that will never be repeated, and then find a place to store the session content. You can also put the session Stored in MySQL database.
The so-called session is actually a session id on the client side and a session file on the server side. When creating a new session, tell the server to generate a cookie and prepare the session file. Otherwise, how will your session content be stored? When reading the session, tell Server, quickly deserialize the session file according to the session id.
Session affects system performance
Session does affect system performance on websites with high traffic. One of the reasons affecting performance is the file system design. When there are more than 10,000 files in the same directory, file positioning will be very time-consuming. PHP supports session directories. hash, we can modify session.save_path = "2;/path/to/session/dir" in php.ini, then the session will be stored in two-level subdirectories, each directory has 16 subdirectories [0~f] , but it seems that PHPsession does not support creating directories, you need to create those directories in advance.
Another problem is the efficiency of small files. Generally, our session data is not too large (1~2K). If there are a large number of 1~2K files on the disk, the IO efficiency will definitely be very poor. Efficiency can be provided by caching memcache and mysql databases.
Session synchronization
There may be many servers on the front end. The user logs in on server A, plants the session information, and then visits some pages of the website and may jump to server B. If there is no session information on server B at this time, there is no session information. Special processing may cause problems.
There are many types of session synchronization. If you store it in memcached or MySQL, it is very easy. Just specify it to the same location. If it is in file form, you can use NFS to store it uniformly.
(NFS is the abbreviation of Network File System, that is, Network File System. Network File System is one of the file systems supported by FreeBSD, also known as NFS. NFS allows a system to share directories and files with others on the network . By using NFS, users and programs can access files on the remote system as if they were local files)
Another way is to use encrypted cookies. When the user successfully logs in on server A, an encrypted cookie is planted on the user's browser. When the user accesses server B, check whether there is a session. If so, Of course, no problem. If not, check whether the cookie is valid. If the cookie is valid, recreate the session on server B. This method is actually very useful. It is very useful if the website has many sub-channels and the servers are not in the same computer room. The sessions cannot be synchronized and you want to log in uniformly.
Of course, another method is to maintain the session at the load balancing layer and bind the visitor to a certain server. All his visits will be on that server and there is no need for session synchronization.
session_start();
if(isset($_SESSION['test_sess'])){
$_SESSION['test_sess']++;
}else{
$_SESSION['test_sess'] = 0;
}
echo$_SESSION['test_sess'];
?>;
First request to the server:
GET/test.php HTTP/1.1
Accept:*/*
Referer:http://localhost/
Accept-Language:zh-cn
Accept-Encoding:gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE6.0; Windows NT 5.1; SV1; Maxthon; .NET CLR 1.1.4322)
Host:localhost
Connection:Keep-Alive
The server returns for the first time:
HTTP/1.1200 OK
Date:Fri, 26 Aug 2005 07:44:22 GMT
Server:Apache/2.0.54 (Win32) SVN/1.2.1 PHP/5.0.4 DAV/2
X-Powered-By:PHP/5.0.4
Set-Cookie:PHPSESSID=bmmc3mfc94ncdr15ujitjogma3; path=/
Expires:Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache,must-revalidate, post-check=0, pre-check=0
Pragma:no-cache
Content-Length:1
Keep-Alive:timeout=15, max=99
Connection:Keep-Alive
Content-Type:text/html; charset=utf-8
Content-Language:Off
第二次请求服务器:
GET/test.php HTTP/1.1
Accept:*/*
Referer:http://localhost/
Accept-Language:zh-cn
Accept-Encoding:gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE6.0; Windows NT 5.1; SV1; Maxthon; .NET CLR 1.1.4322)
Host:localhost
Connection:Keep-Alive
Cookie: PHPSESSID=bmmc3mfc94ncdr15ujitjogma3
服务器第二次返回:
HTTP/1.1200 OK
Date:Fri, 26 Aug 2005 07:44:23 GMT
Server:Apache/2.0.54 (Win32) SVN/1.2.1 PHP/5.0.4 DAV/2
X-Powered-By:PHP/5.0.4
Set-Cookie:PHPSESSID=bmmc3mfc94ncdr15ujitjogma3; path=/
Expires:Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache,must-revalidate, post-check=0, pre-check=0
Pragma:no-cache
Content-Length:1
Keep-Alive:timeout=15, max=98
Connection:Keep-Alive
Content-Type:text/html; charset=utf-8
Content-Language:Off
仔细对比这些输出,第二次请求比第一次请求多出来的就是:
Cookie:PHPSESSID=bmmc3mfc94ncdr15ujitjogma3
这个header将会向服务器发送一个cookie信息,告诉服务器我有一个cookie,名字叫PHPSESSID,内容是bmmc3mfc94ncdr15ujitjogma3。
这个cookie是怎么来的呢?看第一次服务器返回的信息里边有:
Set-Cookie:PHPSESSID=bmmc3mfc94ncdr15ujitjogma3; path=/
这是服务器向客户端浏览器写一个cookie,名字是PHPSESSID,值是bmmc3mfc94ncdr15ujitjogma3,这个值实际就是所谓的session_id。
继续看第二次向服务器发出的请求,仍然向服务器发送了PHPSESSID这个cookie
可以得到以下结论:
1、只要使用了session,就会通过cookie的方式向客户端浏览器发送session
2、每次向服务器发出请求的时候,本地浏览器会把cookie附带在请求信息中
COOKIE
cookie 是一种在远程浏览器端储存数据并以此来跟踪和识别用户的机制。
PHP在http 协议的头信息里发送cookie,因此setcookie()函数必须在其它信息被输出到浏览器前调用。
原理.
a.服务器通过随着响应发送一个http 的Set-Cookie 头,在客户机中设置一个cookie(多个cookie 要多个头)。
b.客户端自动向服务器端发送一个http 的cookie 头,服务器接收读取。
HTTP/1.x 200 OK
X-Powered-By: PHP/5.2.1
Set-Cookie:TestCookie=something from somewhere; path=/
Expires: Thu, 19 Nov 2007 18:52:00 GMT
Cache-Control: no-store, no-cache,must-revalidate, post-check=0,pre-check=0
Pragma: no-cache
Content-type: text/html
这一行实现了cookie 功能,收到这行后
Set-Cookie: TestCookie=something fromsomewhere; path=/
浏览器将在客户端的磁盘上创建一个cookie 文件。
下面的同样的效果:
setcookie('TestCookie','something from somewhere','/');
header('Set-Cookie:TestCookie=something from somewhere; path=/')
常见问题解决:
1) 用 setcookie()时有错误提示,可能是因为调用setcookie()前面有输出或空格。
2) $_COOKIE 受magic_quotes_gpc 影响,可能自动转义。
3) 使用的时候,有必要测试用户是否支持cookie。
下面以用户登录为例分析session和cookie
HTTP协议是一种无状态协议,服务器响应完用户的请求,就失去了与浏览器的联系,PHP是如何实现session的。
用户第一次访问服务器时,因为没有session信息,需要登录验证,用户通过表单把用户名,密码,验证码等信息提交给服务器,服务器在验证用户的合法性之前先对数据进行预处理。通过到数据库验证,用户是合法的,这个时候服务器会给浏览器信息中包含Set-Cookie: PHPSESSID=bmmc3mfc94ncdr15ujitjogma3;这样的信息,这样浏览器会把信息写到本地文件中,其中PHPSESSID为唯一标识符。同时服务器也会在指定的文件把序列化的session信息保存在文件中。当用户再次请求时,浏览器会把对应cookie中的PHPSESSID也发送给服务器,服务器得到PHPSESSID,会到session文件中验证,如果验证成功,就直接登录。从而类似的可以实现数据在不同用户页面之前的传递。session中的值是key-value。
session影响系统性能
Session does affect system performance on websites with high traffic. One of the reasons for affecting performance is the file system design. When there are more than 10,000 files in the same directory, file positioning will be very time-consuming. PHP supports session directories. hash, we can modify session.save_path = "2;/path/to/session/dir" in php.ini, then the session will be stored in two-level subdirectories, each directory has 16 subdirectories [0~f] , but it seems that PHPsession does not support creating directories, you need to create those directories in advance.
Another problem is the efficiency of small files. Generally, our session data is not too large (1~2K). If there are a large number of 1~2K files on the disk, the IO efficiency will definitely be very poor. Efficiency can be provided by caching memcache and mysql databases.
Session synchronization
There may be many servers on the front end. The user logs in on server A, plants the session information, and then visits some pages of the website and may jump to server B. If there is no session information on server B at this time, there is no session information. Special processing may cause problems.
There are many types of session synchronization. If you store it in memcached or MySQL, it is very easy. Just specify it to the same location. If it is in file form, you can use NFS to store it uniformly.
(NFS is the abbreviation of Network File System, that is, Network File System. Network File System is one of the file systems supported by FreeBSD, also known as NFS. NFS allows a system to share directories and files with others on the network . By using NFS, users and programs can access files on the remote system as if they were local files)
Another way is to use encrypted cookies. When the user successfully logs in on server A, an encrypted cookie is planted on the user's browser. When the user accesses server B, check whether there is a session. If so, Of course, no problem. If not, check whether the cookie is valid. If the cookie is valid, recreate the session on server B. This method is actually very useful. It is very useful if the website has many sub-channels and the servers are not in the same computer room. The sessions cannot be synchronized and you want to log in uniformly.
Another method is to maintain the session at the load balancing layer and bind the visitor to a certain server. If all other accesses are on that server, there is no need