简体   繁体   中英

Secure a contact form from scratch in Wordpress

I am currently creating a website with Wordpress, I am creating my theme and I am not using jQuery. I need to introduce a simple contact form, which sends an email on submission and all plugins need jquery to work.

Is it safe to create a contact form that sends an email? Is there a risk of SQL injection since I do not query the database on submission?

I have very little security skill, any information or clarification will be welcome

If you're not familiar with creating a "secure" php form I would advice you to use a plugin for this.

If your "allowed" to install plugins, then have a look "form plugins" like:

This is just a few of the form plugins that are available. Depending on your need/budget you should then make a decision which plugin fits the best (some are free, freemium, premium etc.).

So for example something like:

$name = "{$_POST['message_name']} {$_POST['message_lastname']}"; // I like to combine first and lastname in to 1 variable.

$email = $_POST['message_email'];
$website = $_POST['message_url'];
$message = $_POST['message_description'];

if ( ! filter_var( $email, FILTER_VALIDATE_EMAIL ) ) { 
 $response = form_validation_response( 'error', $email_invalid );
} else {
 if ( empty( $name ) || empty( $message) ) {
  $response = form_validation_response( 'error', $missing_content );
 }
}

// The most simple check you can do is make sre that the fields are NOT empty. 

The form_validation_response method is a simple function which you can use to return error message:

$not_human       = "Human verification incorrect.";
$missing_content = "Please supply all information.";
$email_invalid   = "Email Address Invalid.";
$message_unsent  = "Message was not sent. Try Again.";
$message_sent    = "Thanks! Your message has been sent.";

function form_validation_response( $type, $message ) {
 $class = 'px-2 py-1 mb-6 rounded-md' // These are tailwind classes, but it could be bootstrap
 if ( $type == 'success' ) {
    $class .= "border border-green-800 text-green-700";
 } else {
    $class .= "border border-redish text-redish";
 }

 return "<div class='{$class}'>{$message}</div>";
}

The example above is used to validate the email, but you can also make sure that the fields are actually submitted, before even starting the validation process:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM