duanshan1856
2018-02-19 07:07
浏览 61
已采纳

在ajax请求之后重新生成csrf标记

How to regenerate a token's input after ajax request, so i don't need to reload the page, here's my php code to generate a token

<?php 
class Token {   
public static function generate() {
    return $_SESSION['token'] = base64_encode(openssl_random_pseudo_bytes(32));
}
public static function check($token){
    if(isset($_SESSION['token']) && $token === $_SESSION['token']){ 
        unset($_SESSION['token']);                  
        return true;        
    }
    return false;
  }
}
?>

and here's my jQuery code to send an ajax request

function load() {   
    $('#load-data').load('process/karyawan/load.php');  
}


function insert(){
$('form').submit(function(e){
    e.preventDefault();
    var form = $(this);     
    $.ajax({
        type: form.attr('method'),
        url: 'process/karyawan/insert.php',
        data: form.serialize(),
        success: function(result){              
                load();
            }

        }
    });
});
}

and here's my form

<form action="" method="post">          
        <div class="kiri">
            <div class="inp">   
                <input type="text" name="nama_karyawan" placeholder="Nama Karyawan" class="form-control nama_karyawan">
            </div>
            <div class="inp">                   
                <textarea class="form-control" name="alamat_karyawan" rows="5" placeholder="Alamat Karyawan"></textarea>
            </div>
        </div>
        <div class="kanan">
            <div class="inp">   
                <input type="password" name="password" placeholder="Password" class="form-control">
            </div>
            <div class="inp">   
                <input type="text" name="telepon_karyawan" class="form-control" placeholder="Telepon Karyawan">
            </div>
            <div class="inp">   
                <input name="akses" class="form-control" value="Admin" readonly>
                <div class="error-msg err05"></div>
            </div>                              
            <div class="inp">
                <input type="submit" name="insert" value="Simpan" class="btn btn-success col-sm-12">
                <input type="hidden" name="token" value="<?=Token::generate();?>">
            </div>
        </div>              
    </form>

And here's my load.php file

 <?php 

session_start();

require_once('../../classes/Config.php');
require_once('../../classes/Database.php');
require_once('../../classes/Query.php');
require_once '../../classes/ErrorHandler.php';
require_once '../../classes/Validator.php';
require_once '../../classes/Token.php';

$connection = new Database($host, $username, $password, $database);
$main = new Query($connection);

$table = 'karyawan';
$selectData = $main->select($table);

while($fetchData = $selectData->fetch_object()){
    if(@$_SESSION['owner']){
        $delete = '<a href="?page=deleteKaryawan&id_karyawan='.$fetchData->id_karyawan.'"><i class="fa fa-trash"></i></a>';
        $button = '<td class="text-center">'.$delete.'</td>';
    }else{
        $button = null;
    }
    echo '<tr>
            <td class="text-center">'.$fetchData->id_karyawan.'</td>
            <td class="text-center">'.$fetchData->nama_karyawan.'</td>
            <td class="text-center">'.$fetchData->alamat_karyawan.'</td>
            <td class="text-center">'.$fetchData->telepon_karyawan.'</td>
            <td class="text-center">'.$fetchData->akses.'</td>
            '.$button.'     
        </tr>';
}
?>

For first request the code is running well, but for the second request I think it wouldn't be running well anymore because I've unset the token.. can someone give me an advice to regenerate a token after ajax request ? thank you

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • doupao1530 2018-02-19 12:26
    已采纳

    Because you're unset your token, the next validation will fail. You have to regenerate a new one after check and update your HTML token' field.

    First, in your JS insert(), add "json" datatype.

    Then, in your success function, update the field.

    function insert(){
    $('form').submit(function(e){
        e.preventDefault();
        var form = $(this);     
        $.ajax({
            type: form.attr('method'),
            url: 'process/karyawan/insert.php',
            data: form.serialize(),
            dataType: "json", // NEW
            success: function(result){
                   $("input[name=token]").val(result.token); // NEW              
                    load();
                }
    
            }
        });
    });
    }
    

    And in your update.php :

    session_start();
    // check and to stuff...
    // then
    $new_token = Token::generate(); // generate a new token
    
    echo json_encode(['token' => $new_token]); // send to JS
    die;
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题