0

I have an issue with a PHP contact form I am trying to create for WordPress. I have an error on the $headers line that says syntax error, unexpected '' but I'm not sure why as it looks correct to me. I also think that function my_form_message(){ is not closed properly. Any help would be great. Thanks

// Form markup
 function html_form_code() { ?>

 <form action="<?php esc_url( $_SERVER['REQUEST_URI'] ); ?>" method="post">
   <p>Your Name (required)<br />
     <input type="text" name="cf-name" pattern="[a-zA-Z0-9 ]+" value="<?php isset( $_POST["cf-name"] ) ? esc_attr( $_POST["cf-name"] ) : ''; ?>" size="40" />
   </p>
   <p>Your Email (required)<br />
     <input type="email" name="cf-email" value="<?php isset( $_POST["cf-email"] ) ? esc_attr( $_POST["cf-email"] ) : ''; ?>" size="40" />
   </p>
   <p>Your Message (required)<br />
     <textarea rows="10" cols="35" name="cf-message"><?php isset( $_POST["cf-message"] ) ? esc_attr( $_POST["cf-message"] ) : ''; ?></textarea>
   </p>
   <p><input type="submit" name="cf-submitted" value="Send"/></p>
 </form>

 <?php }

// Form validation
 function my_validate_form() {

  $errors = new WP_Error();

  if ( isset( $_POST[ 'content' ] ) && $_POST[ 'content' ] !== '' ) {
    $errors->add( 'cheater', 'Sorry, this field should not be filled. Are you trying to cheat?' );
  }

  if ( isset( $_POST[ 'cf-name' ] ) && $_POST[ 'cf-name' ] == '' ) {
    $errors->add('name_error', 'Please fill in a valid name.' );
  }

  if ( isset( $_POST[ 'cf-email' ] ) && $_POST[ 'cf-email' ] == '' ) {
    $errors->add('email_error', 'Please fill in a valid email.' );
  }

  if ( isset( $_POST[ 'cf-message' ] ) && $_POST[ 'cf-message' ] == '' ) {
    $errors->add('message_error', 'Please fill in a valid message.' );
  }

  return $errors;
}

// Form delivery
 function deliver_mail( $args = array() ) {

  // This $default array is a way to initialize some default values that will be overwritten by our $args array.
  // We could add more keys as we see fit and it's a nice way to see what parameter we are using in our function.
  // It will only be overwritten with the values of our $args array if the keys are present in $args.
  // This uses WP wp_parse_args() function.
  $defaults = array(
    'name'    => '',
    'email'   => '',
    'message' => '',
    'to'      => get_option( 'admin_email' ), // get the administrator's email address
  );

  $args = wp_parse_args( $args, $defaults );

  $headers = "From: $args['name'] <$args['email']>" . "\r\n";

  // Send email returns true on success, false otherwise
  if( wp_mail( $args['to'], $args['message'], $headers ) ) {
    return;
  }
  else {
    return false;
  }
}

// Form sanitize
function my_sanitize_field( $input ){

  return trim( stripslashes( sanitize_text_field ( $input ) ) );

}

// Form succsess message
function my_form_message(){

  global $errors;
  if( is_wp_errors( $errors ) && empty( $errors->errors ) ){

    echo '<div class="cf-success">';
    echo '<p>Thank you for contacting us '. $_POST['cf-name'] .', a member of our team will be in touch with you shortly.</p>';
    echo '</div>';

    //Empty $_POST because we already sent email
    $_POST = '';

  }
  else {

  if( is_wp_errors( $errors ) && ! empty( $errors->errors ) ){

    $error_messages = $errors->get_error_messages();
    foreach( $error_messages as $k => $message ){
        echo '<div class="cf-error ' . $k . '">';
        echo '<p>' . $message . '</p>';
        echo '</div>';

    }

  }

}

// Form shortcode
add_shortcode( 'contact_form', 'cf_contact_form' );
function cf_contact_form() {

  ob_start();

  my_form_message();
  html_form_code();

  return ob_get_clean();
}

// Error validation
add_action( 'init', 'my_cf_form');
function my_cf_form(){

  if( isset( $_POST['cf-submitted'] ) ) {

    global $errors;
    $errors = my_validate_form();
    if( empty( $errors->errors ) ){

       $args = array(
         'name'    => my_sanitize_field( $_POST['cf-name'] ),
         'email'   => my_sanitize_field( $_POST['cf-email'] ),
         'message' => my_sanitize_field( $_POST['cf-message'] ),
       );
       deliver_mail( $args );
    }
    else {
      return $errors;
    }
  }
}
  • Whats with the down vote? – user53340 Aug 24 '16 at 12:39
  • Why not use a plugin as Contact Form 7? – Rubatharisan Thirumathyam Aug 24 '16 at 13:47
  • For a number of reasons really. A) I want to learn and understand the code. B) I don't like ramming my sites full of plugins, when things can be built from scratch. C) I think certain plugins introduce more security risks to sites so it's best to keep plugin use to a minimum. D) Plugins create extra server requests, their code isn't always optimised as often they are designed to cater for a range of needs and as a result can slow the site down. So I would rather streamline my sites as much as possible. – user53340 Aug 24 '16 at 14:34
  • A) Good way to learn the code :) B) Understandable, plugins can be cluttered and needs to be updated - often is over-engineered to a simple purpose. C) I agree, keep it to a minimum. D) True, in most cases. Point taken :) – Rubatharisan Thirumathyam Aug 25 '16 at 8:37
  • 1
    Hopefully the above code will help someone else in the future too. So win win. :) – user53340 Aug 25 '16 at 8:38
1

To access array values within a double quoted string use the form:

 $headers = "From: {$args['name']}  <{$args['email']}>" . "\r\n";

You are right: your function needs one more } to close it correctly.

  • Do you mean like this? $headers = "From: {$args['name'] <$args['email']>}" . "\r\n"; – user53340 Aug 24 '16 at 13:06
  • @user53340 no. Braces around each variable. – Andy Macaulay-Brook Aug 24 '16 at 13:07
  • I've edited the question to show the full line. Typing code on a phone isn't the easiest :-) – Andy Macaulay-Brook Aug 24 '16 at 13:09
  • I get the same error unless I remove the <> from around the email variable. Will it still work okay? – user53340 Aug 24 '16 at 13:09
  • ahh that makes sense! Thanks for that. Okay so now I have a fatal error Fatal error: Uncaught Error: Call to undefined function is_wp_errors() PHP isn't my strong point at all. Do you know what this could be referring to? Thanks again – user53340 Aug 24 '16 at 13:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.