0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Wordpress】 wp_nonce_fieldの使用方法

Last updated at Posted at 2025-01-15

説明
wp_nonce_field関数は、フォームからのリクエストの正当性を確認するために、nonce(セキュリティトークン)を生成し、フォームに埋め込みます。フォームが送信されると、nonceも一緒にサーバーへ送信され、サーバー側でその検証が行われる。
nonceは一度だけ使用できるトークンで、CSRF(クロスサイトリクエストフォージェリ)攻撃の防止に役立ち、セッションの乗っ取りや不正利用からユーザーを保護する。

特徴
生成したnonceは以下の特性を持つ:

  • 一定時間後に無効化される
  • ユーザーごとに異なる
  • 特定のアクション(例: submit_nonce_action)と紐づけられる

使用方法

<button type="submit" id="submit-button" name="submit" value="request">送信</button>
<?php wp_nonce_field( 'submit_nonce_action', 'submit_nonce_name' );  //nonceフィールドの設置 ?>

ユーザーが送信ボタンを押すと、nonceが含まれたデータはサーバーに送信される。サーバーはそのnonceを検証し、問題がなければ指定された関数(例: my_function())を実行する。

function my_function() {
    // いろいろな処理
}

add_action('after_setup_theme', function() {
    //フォームからの送信があるか確認
    if ( isset( $_POST['submit'] ) && $_POST['submit'] === 'request' ) {
        //nonceチェック、無効なら処理を中断
        if ( !isset( $_POST['submit_nonce_name'] ) ) return;
        if ( !wp_verify_nonce( $_POST['submit_nonce_name'], 'submit_nonce_action' ) ) return;

        //処理を実行
        my_function();
    }
});

このように、nonceを使うことでリクエストの正当性を確認し、セキュリティを強化できる。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?