Home >Backend Development >PHP Tutorial >这段php代码如何更改?
我想生成一个token显示出来,页面刷新一次改变一次,下面的代码该怎样修改?
<code><?php session_start(); function set_token() { $_SESSION['token'] = md5(microtime(true)); } function valid_token() { $return = $_REQUEST['token'] === $_SESSION['token'] ? true : false; set_token(); return $return; } if(!isset($_SESSION['token']) || $_SESSION['token']=='') { set_token(); } echo $_SESSION['token'] unset($_SESSION['token']); ?></code>
我想生成一个token显示出来,页面刷新一次改变一次,下面的代码该怎样修改?
<code><?php session_start(); function set_token() { $_SESSION['token'] = md5(microtime(true)); } function valid_token() { $return = $_REQUEST['token'] === $_SESSION['token'] ? true : false; set_token(); return $return; } if(!isset($_SESSION['token']) || $_SESSION['token']=='') { set_token(); } echo $_SESSION['token'] unset($_SESSION['token']); ?></code>
难道你这个页面刷新一次就不能更改一次吗?
如果是我,以下代码是这样子的
<code class="php">session_start(); function set_token() { $key = mt_rand(100000,900000); $token = md5(md5(time()).$key); $_SESSION['token'] = $token; return $token; } function get_token() { if(!isset($_SESSION['token']) || empty($_SESSION['token'])) { return false; } return $_SESSION['token']; } function unset_token() { unset($_SESSION['token']); } function valid_token($token) { if($token !== $_SESSION['token']) { return false; } return true; } $token = $_REQUEST['token']; //客户端提交过来的token if(get_token() === false) { $token = set_token(); echo '验证失败!'; echo '生成的token:'.$token; } else { if(valid_token($token)) { echo '验证成功!'; unset_token(); // 删除token $token = set_token(); echo '生成的新token:'.$token; } }</code>