Skip to content
Tutorials Center
My learning

Topics

Lesson 64 of 68 ยท Real-World Projects

Project: A Secure Contact Form Plugin

Build a contact form plugin the safe way: shortcode form, nonce, honeypot, sanitizing, validation, wp_mail, stored submissions and an admin list.

A contact form looks like the simplest feature on a website, and it is one of the most attacked. Spammers fill it with links, attackers try to inject extra email headers so your server sends their mail, and a careless admin screen can turn a visitor's message into a script that runs in the owner's browser. In this project you will build a plugin called Acme Contact that handles all of those problems properly.

The plugin shows a form with the shortcode [acme_contact], protects it with a nonce and a honeypot, cleans and validates every field, saves each message as a private record, emails the site owner and gives the admin a list of submissions. You will use ideas from forms and nonces, sanitizing and validating, escaping output, shortcodes and capabilities.

Sending real email and talking to the database need a WordPress site, so the plugin code is read-only. The two runnable stand-ins rebuild the whole submission pipeline and the admin list in plain PHP. They are simplified: the "nonce" is a toy and "mail" is captured as text. Never copy the stand-in's security code into a real site; use the WordPress functions.

The security checklist

Every submission passes through the same gates, in this order. A request that fails any gate stops immediately:

flowchart TD
    A["POST to admin-post.php"] --> B{"Valid nonce?"}
    B -- no --> X["Reject"]
    B -- yes --> C{"Honeypot empty?"}
    C -- no --> Y["Pretend success,<br/>save nothing"]
    C -- yes --> D{"Rate limit ok?"}
    D -- no --> X
    D -- yes --> E["Sanitize each field"]
    E --> F{"Valid?"}
    F -- no --> G["Redirect back<br/>with errors"]
    F -- yes --> H["Save message"]
    H --> I["wp_mail to owner"]
    I --> J["Redirect with<br/>success flag"]

Cheap checks come first, so junk never reaches the database or the mail server.

The principles behind it:

  • Never trust input. Everything in $_POST is chosen by the sender. Sanitize it to a known shape and validate it against your rules.
  • Escape on output, in the right context, every time.
  • Do not let input into email headers. A newline in a header value lets an attacker add headers such as extra recipients.
  • Make spam expensive, not impossible. A honeypot and a rate limit stop most bots; add a captcha service if you still have trouble.

Step 1: the form shortcode

The form posts to admin-post.php, WordPress's standard entry point for form handlers (see forms and nonces). The hidden action field chooses the handler.

PHP
<?php
add_shortcode( 'acme_contact', function () {
    $status = isset( $_GET['acme_status'] ) ? sanitize_key( wp_unslash( $_GET['acme_status'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification

    ob_start();

    if ( 'sent' === $status ) {
        echo '<p class="acme-notice acme-ok">' . esc_html__( 'Thank you, your message was sent.', 'acme-contact' ) . '</p>';
    } elseif ( 'error' === $status ) {
        echo '<p class="acme-notice acme-error">' . esc_html__( 'Please check your name, email and message.', 'acme-contact' ) . '</p>';
    }
    ?>
    <form class="acme-contact" method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
        <input type="hidden" name="action" value="acme_contact">
        <?php wp_nonce_field( 'acme_contact_send', 'acme_nonce' ); ?>

        <p>
            <label for="acme-name"><?php esc_html_e( 'Name', 'acme-contact' ); ?></label>
            <input type="text" id="acme-name" name="acme_name" maxlength="100" required>
        </p>
        <p>
            <label for="acme-email"><?php esc_html_e( 'Email', 'acme-contact' ); ?></label>
            <input type="email" id="acme-email" name="acme_email" maxlength="100" required>
        </p>
        <p>
            <label for="acme-message"><?php esc_html_e( 'Message', 'acme-contact' ); ?></label>
            <textarea id="acme-message" name="acme_message" rows="6" maxlength="5000" required></textarea>
        </p>

        <div class="acme-hp" aria-hidden="true">
            <label for="acme-website">Leave this field empty</label>
            <input type="text" id="acme-website" name="acme_website" tabindex="-1" autocomplete="off">
        </div>

        <p><button type="submit"><?php esc_html_e( 'Send message', 'acme-contact' ); ?></button></p>
    </form>
    <?php
    return ob_get_clean();
} );

The required and maxlength attributes help honest visitors, but they are only convenience: the server must check everything again. The honeypot is a field real people never see, hidden with CSS (.acme-hp { position: absolute; left: -9999px; }). Bots that fill every field give themselves away. Do not use display: none alone as the only hiding trick for accessibility reasons; the aria-hidden wrapper and tabindex="-1" keep screen-reader and keyboard users out of it.

One caution about nonces and caching: a nonce is valid for a limited time (see forms and nonces), so a page cache that stores the form for a day will serve expired nonces. Exclude pages with the form from full-page caching, or load the form through JavaScript.

Step 2: the handler

Two hooks register the handler: admin_post_nopriv_acme_contact for visitors who are not logged in, and admin_post_acme_contact for logged-in users.

PHP
<?php
add_action( 'admin_post_nopriv_acme_contact', 'acme_handle_contact' );
add_action( 'admin_post_acme_contact', 'acme_handle_contact' );

function acme_redirect_back( string $status ): void {
    $url = wp_get_referer() ? wp_get_referer() : home_url( '/' );
    wp_safe_redirect( add_query_arg( 'acme_status', $status, $url ) );
    exit;
}

function acme_handle_contact(): void {
    // 1. Nonce.
    $nonce = isset( $_POST['acme_nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['acme_nonce'] ) ) : '';
    if ( ! wp_verify_nonce( $nonce, 'acme_contact_send' ) ) {
        wp_die( esc_html__( 'The form has expired. Please go back and try again.', 'acme-contact' ), '', [ 'response' => 403 ] );
    }

    // 2. Honeypot: bots fill it, people never see it.
    if ( ! empty( $_POST['acme_website'] ) ) {
        acme_redirect_back( 'sent' ); // Look successful, save nothing.
    }

    // 3. Rate limit: one message per visitor every 30 seconds.
    $key = 'acme_rl_' . md5( acme_client_ip() );
    if ( get_transient( $key ) ) {
        wp_die( esc_html__( 'Please wait a moment before sending another message.', 'acme-contact' ), '', [ 'response' => 429 ] );
    }

    // 4. Sanitize.
    $name    = isset( $_POST['acme_name'] ) ? sanitize_text_field( wp_unslash( $_POST['acme_name'] ) ) : '';
    $email   = isset( $_POST['acme_email'] ) ? sanitize_email( wp_unslash( $_POST['acme_email'] ) ) : '';
    $message = isset( $_POST['acme_message'] ) ? sanitize_textarea_field( wp_unslash( $_POST['acme_message'] ) ) : '';

    // 5. Validate.
    if ( '' === $name || mb_strlen( $name ) > 100
        || ! is_email( $email )
        || mb_strlen( $message ) < 10 || mb_strlen( $message ) > 5000 ) {
        acme_redirect_back( 'error' );
    }

    // 6. Store, then 7. email.
    $post_id = wp_insert_post( [
        'post_type'    => 'acme_message',
        'post_status'  => 'private',
        'post_title'   => $name,
        'post_content' => $message,
        'meta_input'   => [ '_acme_email' => $email ],
    ] );

    set_transient( $key, 1, 30 );

    $subject = sprintf( '[%s] New message from %s', wp_specialchars_decode( get_bloginfo( 'name' ) ), $name );
    $headers = [ 'Reply-To: ' . $name . ' <' . $email . '>' ];
    wp_mail( get_option( 'admin_email' ), $subject, $message, $headers );

    acme_redirect_back( 'sent' );
}

A few details deserve attention:

  • Order matters. The nonce check is cheap and comes first; the database write comes last.
  • wp_unslash() before sanitizing. WordPress adds slashes to superglobals for historical reasons; remove them first.
  • Header injection. sanitize_text_field() removes line breaks from the name, and sanitize_email() strips anything that is not allowed in an address, so neither can add a new header line. The message goes in the body, which is not a header. Never put raw $_POST text in a header or subject.
  • The honeypot answer. Returning "sent" gives a bot no signal about what failed.
  • Rate limiting with a transient is a light protection. Behind a proxy, REMOTE_ADDR may be the proxy's address, so write acme_client_ip() carefully and do not trust headers like X-Forwarded-For unless your host sets them.
  • wp_safe_redirect() only redirects to allowed hosts, which avoids open-redirect bugs, and the code stops with exit right after.
  • wp_mail() can fail (many hosts block PHP mail). Because the message is stored first, nothing is lost. For production, send through an SMTP plugin or a transactional email service.

Step 3: storing submissions privately

Register a post type that visitors can never see, but admins can browse:

PHP
<?php
add_action( 'init', function () {
    register_post_type( 'acme_message', [
        'labels'              => [
            'name'          => __( 'Messages', 'acme-contact' ),
            'singular_name' => __( 'Message', 'acme-contact' ),
        ],
        'public'              => false,
        'show_ui'             => true,
        'show_in_rest'        => false,
        'exclude_from_search' => true,
        'menu_icon'           => 'dashicons-email',
        'supports'            => [ 'title', 'editor' ],
        'capability_type'     => 'post',
        'capabilities'        => [ 'create_posts' => 'do_not_allow' ], // No "Add New".
        'map_meta_cap'        => true,
    ] );
} );

public => false keeps the messages off the front end and out of the REST API, so they have no URL and no public query path. Using a post type instead of a custom table is a good fit here, because the volume is small and you get an admin screen, search and trash for free. A site receiving thousands of messages a day would use a custom table (see $wpdb and custom tables). Remember that stored messages are personal data: think about how long you keep them, and use WordPress's privacy tools to export and erase them on request.

Step 4: the admin list

The default list shows titles. Add columns for the email and a short excerpt. This is where output escaping matters most: the message text came from a stranger and now appears in an administrator's browser.

PHP
<?php
add_filter( 'manage_acme_message_posts_columns', function ( array $columns ): array {
    return [
        'cb'    => $columns['cb'],
        'title' => __( 'Name', 'acme-contact' ),
        'email' => __( 'Email', 'acme-contact' ),
        'msg'   => __( 'Message', 'acme-contact' ),
        'date'  => $columns['date'],
    ];
} );

add_action( 'manage_acme_message_posts_custom_column', function ( string $column, int $post_id ) {
    if ( 'email' === $column ) {
        $email = get_post_meta( $post_id, '_acme_email', true );
        printf( '<a href="mailto:%s">%s</a>', esc_attr( $email ), esc_html( $email ) );
    }
    if ( 'msg' === $column ) {
        echo esc_html( wp_trim_words( get_post_field( 'post_content', $post_id ), 20 ) );
    }
}, 10, 2 );

Even though you sanitized on input, escape on output. Sanitizing makes data tidy; escaping makes it safe for a specific context. Both are needed, and the output side is the one that stops cross-site scripting.

The whole pipeline, runnable

This stand-in follows the same gates in the same order using plain PHP and SQLite: nonce, honeypot, rate limit, sanitize, validate, store, mail. The mail is captured as text so you can read the exact headers, including what happens when someone tries header injection.

PHP The full submission pipeline (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Look at the mail from the injection attempt: the attacker's Bcc: text ended up as harmless words inside the subject because the line breaks were removed, so no extra header exists. In the email field the same trick failed differently: sanitizing stripped the spaces and colon, which left something that is not a valid address, and validation refused it. That is why sanitize_email() followed by is_email() is a good pair: sanitize, then validate.

The admin view, runnable

The second stand-in renders a list of stored messages as an HTML table. One message contains a script tag. First you see the unsafe rendering, then the escaped one. In a real admin screen only esc_html() and friends stand between that script and an administrator's logged-in session.

PHP Why admin output must be escaped (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

In the unsafe version the browser would run the script. In the safe version the angle brackets become &lt; and &gt;, and the text is displayed, not executed.

Hardening and next steps

  • Add a setting for the recipient address with the Settings API instead of always using the admin email.
  • Add Akismet or a captcha service when a honeypot is no longer enough.
  • Add a privacy notice and a consent checkbox if the law where you operate requires it.
  • Delete old messages with a scheduled event (see caching and WP-Cron).
  • Log failed attempts without storing the message itself, and review them occasionally.
  • Test the handler with PHPUnit (see testing and deployment).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does the handler remove line breaks from the name before it is used in an email subject or Reply-To header?

    Email headers are separated by line breaks, so a newline inside a value can start a new header. This is called header injection.
  2. 2. What is the purpose of the honeypot field?

    Real visitors never see or fill the hidden field. A bot that does fill it is treated as spam.
  3. 3. Why escape the message when showing it in the admin list even though it was sanitized when saved?

    Sanitizing tidies input; escaping on output prevents the browser from interpreting stored text as markup or script. Both layers are used.
  4. 4. Why does the plugin register the message post type with public set to false?

    Private messages must not be reachable by visitors. A non-public type has no public pages, and show_in_rest is off as well.
  5. 5. Which hook handles the form post for visitors who are not logged in?

    admin-post.php calls admin_post_nopriv_{action} for logged-out users and admin_post_{action} for logged-in users.

Summary

  • Run every submission through gates in order: nonce, honeypot, rate limit, sanitize, validate, then store and mail.
  • Use wp_unslash() and the matching sanitizer for each field, and validate with is_email() and length checks.
  • Keep user input out of email headers; use Reply-To with a sanitized, validated address.
  • Store submissions in a non-public post type, and escape everything in the admin list.
  • Use wp_safe_redirect() after posting, and expect wp_mail() to fail on some hosts.
  • Full-page caches can serve expired nonces, so exclude the form page from them.
  • The runnable code is a plain-PHP stand-in, not real WordPress.

Next: Project: A Reading List with REST and Blocks