1 Maintain user information in the website through SessionID
<code><span><span><?php</span> session_start(); <span>$_SESSION</span>[<span>'visits'</span>]++; <span>print</span><span>'You have visited here '</span>.<span>$_SESSION</span>[<span>'visits'</span>].<span>' times.<br>'</span>; <span>echo</span><span>'session id = '</span>.<span>$_COOKIE</span>[<span>'PHPSESSID'</span>]; <span>echo</span><span>"<br>"</span>; <span>echo</span><span>"session name = "</span>.session_name().<span>"<br>"</span>; <span>?></span></span></code>
SessionID is recorded in the global variable _COOKIE. The name of SessionID is PHPSESSID, and PHPSESSID can also be obtained through session_name().
2 Prevent Session Hijacking
<code><span><span><span><?php</span> ini_set(<span>'sessio.use_only_cookies'</span>, <span>true</span>); session_start(); <span>$salt</span> = <span>'YourSpecialValueHere'</span>; <span>$tokenstr</span> = date(<span>'W'</span>).<span>$salt</span>; <span>$token</span> = md5(<span>$tokenstr</span>); <span>echo</span><span>'token = '</span>.<span>$token</span>.<span>'<br>'</span>; <span>if</span>(!<span>isset</span>(<span>$_REQUEST</span>[<span>'token'</span>]) || <span>$_REQUEST</span>[<span>'token'</span>] != <span>$token</span>) { <span>exit</span>; } <span>$_SESSION</span>[<span>'token'</span>] = <span>$token</span>; output_add_rewrite_var(<span>'token'</span>, <span>$token</span>); <span>echo</span><span>'<a href="test.php">link</a>'</span>; ob_flush(); output_reset_rewrite_vars(); <span>?></span></span></span></code>
<code><span><span><span><?php</span> session_start(); output_add_rewrite_var(<span>'var'</span>, <span>'value'</span>); <span>echo</span><span>'<a href="file.php">link</a>'</span>; ob_flush(); output_reset_rewrite_vars(); <span>echo</span><span>'<a href="file.php">link</a>'</span>; <span>?></span></span>以上例程会输出: <span><<span>a</span><span>href</span>=<span>"file.php?PHPSESSID=xxx&var=value"</span>></span>link<span></<span>a</span>></span><span><<span>a</span><span>href</span>=<span>"file.php"</span>></span>link<span></<span>a</span>></span></span></code>
3 Prevent Session Customization
<code><span><span><?php</span> ini_set(<span>'session.use_only_cookie'</span>, <span>true</span>); session_start(); <span>if</span>(!<span>isset</span>(<span>$_SESSION</span>[<span>'generated'</span>]) || <span>$_SESSION</span>[<span>'generated'</span>] < (time() - <span>30</span>)) { session_regenerate_id(); <span>$_SESSION</span>[<span>'generated'</span>] = time(); } <span>echo</span><span>$_COOKIE</span>[<span>'PHPSESSID'</span>]</span></code>
The above has introduced 11 Session and data retention, including aspects of it. I hope it will be helpful to friends who are interested in PHP tutorials.