Fügen Sie einen Dateiupload mit validation zum benutzerdefinierten Formular hinzu

Ich habe eine benutzerdefinierte Kontaktformularseite, der ich ein Upload-Feld hinzufügen möchte, das Dateigröße und Dateityp überprüft. Vor dem Hinzufügen der validation hat alles funktioniert.

<?php /* Template Name: Contact-Page-with-upload * * A Custom PHP Contact us page. Add or change form fields on line 28 and in the form itself. * Jquery is used to add/remove Bootstrap has-error class to invalid fields. */ /** * Get Error Class * * @return string; */ function getErrorClass($failedKeys, $key) { if(isset($failedKeys) && is_array($failedKeys) && in_array($key, $failedKeys)) { return 'has-error'; } return ''; } if(isset($_POST) && !empty($_POST)) { // New Line Tag $nL = "
"; // Response generation function $response = ""; // Fuction to generate response function my_contact_form_generate_response($type, $message) { global $response; if($type == "success") $response = ""; else $response = ""; } // Response messages $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."; // Define the fields we use, title => field name // This can be used to add fields into auto-validation below. $userVariables = [ 'First Name' => 'first_name', 'Last Name' => 'last_name', 'Phone' => 'phone', 'Email' => 'email', 'Comment' => 'comment' ]; // Instantiate variables for failed, successful validated fields $failedFields = []; $validFields = []; $failedKeys = []; //$errors = []; // Loop through each variable defined above, and check it's validity as a non-blank string. // If successful, add it to the message array and strip all tags for security, and trim whitespace if(!empty($_POST)) { foreach($userVariables as $title => $userField) { // If our field did not pass validation, we push to failedFields array if(!isset($_POST[$userField]) || !is_string($_POST[$userField]) || $_POST[$userField] == '') { $failedFields[] = $title; $failedKeys[] = $userField; } // If successful, add this to validFields array and trim/clean the content else { $validFields[$title] = trim(strip_tags(($_POST[$userField]))); } } } // If we have > 0 failed fields, we will send a error response to the form if(!empty($failedFields)) { // Concatenate message with failed fields in the message $failureMessage = "The following fields are required: " . implode(', ', $failedFields); my_contact_form_generate_response("error", $failureMessage); } // Create HTML message $message = ''; // define the Google Font used in the message $message .='@import url("https://fonts.googleapis.com/css?family=Open+Sans:400,600");'; $message .=''; $message .=''; $message .= "

Message from contact form on" .get_bloginfo('name') ."

"; $message .= ''; // If we have valid fields listed above, we will concatenate a message for the email body then close the table, body, and html tags if(!empty($validFields)) { foreach($validFields as $title => $value) { $message .= ""; } } $message .= '
" . $title . ":" . $value . "
'; // end message /** * * Handle file attachment * */ if ( ! function_exists( 'wp_handle_upload' ) ) { require_once( ABSPATH . 'wp-admin/includes/file.php' ); } $uploadedFile = false; $movefile = false; if(isset($_FILES['attachmentFile'])) { $uploadedFile = $_FILES['attachmentFile']; //Get the uploaded file information $name_of_uploaded_file = basename($uploadedFile['name']); //get the file extension of the file $type_of_uploaded_file = substr($name_of_uploaded_file, strrpos($name_of_uploaded_file, '.') + 1); $size_of_uploaded_file = $uploadedFile["size"] / 1024; //size in KBs //Settings $max_allowed_file_size = 2000; // size in KB $allowed_extensions = array("jpg", "jpeg", "png", "pdf"); $upload_overrides = array( 'test_form' => false ); //Validations if($size_of_uploaded_file > $max_allowed_file_size ) { $failedKeys[] = 'attachmentFile'; my_contact_form_generate_response("error", "Size of file should be less than $max_allowed_file_size"); } //------ Validate the file extension $allowed_ext = false; for($i = 0; $i

Contact Us

<form class="form-horizontal well" action="" method="post" id="contact_form" enctype="multipart/form-data">
Do you have questions, interested in a product or would like to inquire about delivery options?

Please fill out the contact form and we will get back to you ASAP!

<div class="form-group ">
<input name="first_name" placeholder="First Name" class="form-control" type="text" value="" required>
<div class="form-group ">
<input name="last_name" placeholder="Last Name" class="form-control" type="text" value="" required>
<div class="form-group ">
<input name="email" placeholder="E-Mail Address" class="form-control" type="email" value="" required>
<div class="form-group ">
<input name="phone" placeholder="(855)555-1212" class="form-control" type="text" value="" required>
<div class="form-group ">
<div class="form-group ">
// Add/Remove Bootstrap "has-error" class from invalid fields on key-up and blur jQuery('#contact_form :input').keyup(function () { var formElement = jQuery(this); formGroup = formElement.closest('.form-group'); if(formGroup.hasClass('has-error') && jQuery.trim(formElement.val()).length) { formGroup.removeClass('has-error'); } }); jQuery('#contact_form :input').blur(function () { var formElement = jQuery(this); formGroup = formElement.closest('.form-group'); if(jQuery.trim(formElement.val()).length==0) { formGroup.addClass('has-error'); } });
<article id="post-" role="article">

Solutions Collecting From Web of "Fügen Sie einen Dateiupload mit validation zum benutzerdefinierten Formular hinzu"

  < ?php /* Template Name: Contact-Page-with-upload * * A Custom PHP Contact us page. Add or change form fields on line 28 and in the form itself. * Jquery is used to add/remove Bootstrap has-error class to invalid fields. */ /** * Get Error Class * * @return string; */ $response = ''; function getErrorClass($failedKeys, $key) { if(isset($failedKeys) && is_array($failedKeys) && in_array($key, $failedKeys)) { return 'has-error'; } return ''; } if(isset($_POST) && !empty($_POST)) { // New Line Tag $nL = "
"; // Response generation function // Fuction to generate response function my_contact_form_generate_response($type, $message) { global $response; if($type == "success") { $response = ""; } else { $response = ""; } } // Response messages $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."; // Define the fields we use, title => field name // This can be used to add fields into auto-validation below. $userVariables = [ 'First Name' => 'first_name', 'Last Name' => 'last_name', 'Phone' => 'phone', 'Email' => 'email', 'Comment' => 'comment' ]; // Instantiate variables for failed, successful validated fields $failedFields = []; $validFields = []; $failedKeys = []; // Loop through each variable defined above, and check it's validity as a non-blank string. // If successful, add it to the message array and strip all tags for security, and trim whitespace if(!empty($_POST)) { foreach($userVariables as $title => $userField) { // If our field did not pass validation, we push to failedFields array if(!isset($_POST[$userField]) || !is_string($_POST[$userField]) || $_POST[$userField] == '') { $failedFields[] = $title; $failedKeys[] = $userField; } // If successful, add this to validFields array and trim/clean the content else { $validFields[$title] = trim(strip_tags(($_POST[$userField]))); } } } // If we have > 0 failed fields, we will send a error response to the form if(!empty($failedFields)) { // Concatenate message with failed fields in the message $failureMessage = "The following fields are required: " . implode(', ', $failedFields); my_contact_form_generate_response("error", $failureMessage); } // Create HTML message $message = ''; // define the Google Font used in the message $message .=''; $message .=''; $message .=''; $message .= "

Message from contact form on" .get_bloginfo('name') ."

"; $message .= ''; // If we have valid fields listed above, we will concatenate a message for the email body then close the table, body, and html tags if(!empty($validFields)) { foreach($validFields as $title => $value) { $message .= ""; } } $message .= '
" . $title . ":" . $value . "
'; // end message /** * * Handle file attachment * */ if ( ! function_exists( 'wp_handle_upload' ) ) { require_once( ABSPATH . 'wp-admin/includes/file.php' ); } $uploadedFile = false; $movefile = false; $failedAttachment = false; if(isset($_FILES['attachmentFile']) && file_exists($_FILES['attachmentFile']['tmp_name'])) { $uploadedFile = $_FILES['attachmentFile']; //Get the uploaded file information $name_of_uploaded_file = basename($uploadedFile['name']); //get the file extension of the file $type_of_uploaded_file = substr($name_of_uploaded_file, strrpos($name_of_uploaded_file, '.') + 1); $size_of_uploaded_file = $uploadedFile["size"] / 1024; //size in KBs //Settings $max_allowed_file_size = 2000; // size in KB $allowed_extensions = array("jpg", "jpeg", "png", "pdf"); $upload_overrides = array( 'test_form' => false ); //Validations if($size_of_uploaded_file > $max_allowed_file_size) { $failedKeys[] = 'attachmentFile'; $failedFields[] = 'Uploaded File'; $failedAttachment = true; my_contact_form_generate_response("error", "Size of uploaded file should be less than ". round($max_allowed_file_size / 1024). "mb "); } //------ Validate the file extension $allowed_ext = false; for($i = 0; $i < ?php get_header(); ?>

Contact Us

< ?php echo $response; ?>
Do you have questions, interested in a product or would like to inquire about delivery options?

Please fill out the contact form and we will get back to you ASAP!

< ?php if (have_posts()) : while (have_posts()) : the_post(); ?>
role="article">
< ?php the_content(); ?>
< ?php endwhile; ?> < ?php else : ?>

< ?php _e("Not Found", "JD_BOOTSTRAP"); ?>

< ?php _e("Sorry, but the requested resource was not found on this site.", "JD_BOOTSTRAP"); ?>

< ?php endif; ?>
< ?php get_footer(); ?>