首页  >  文章  >  后端开发  >  11 Session和数据保持

11 Session和数据保持

WBOY
WBOY原创
2016-07-29 08:55:241152浏览

1 通过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></span></code>

SessionID记录在全局变量_COOKIE中,SessionID的名字是PHPSESSID,PHPSESSID也可以通过session_name()获得。

2 预防Session劫持

<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></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>a</span><span>href</span>=<span>"file.php?PHPSESSID=xxx&var=value"</span>></span>link<span><span>a</span>></span><span>a</span><span>href</span>=<span>"file.php"</span>></span>link<span><span>a</span>></span></code>

3 预防Session定制

  • 不会把session标志符附加到URL上的session cookie.
  • 频繁的生成新的sessionID
<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>] 30</span>))
{
    session_regenerate_id();
    <span>$_SESSION</span>[<span>'generated'</span>] = time();
}
<span>echo</span><span>$_COOKIE</span>[<span>'PHPSESSID'</span>]</span></code>
').addClass('pre-numbering').hide(); $(this).addClass('has-numbering').parent().append($numbering); for (i = 1; i ').text(i)); }; $numbering.fadeIn(1700); }); });

以上就介绍了11 Session和数据保持,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn