Home >Backend Development >PHP Tutorial >这段php代码如何更改?

这段php代码如何更改?

WBOY
WBOYOriginal
2016-06-06 20:21:101298browse

我想生成一个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>
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn