Skip to content

Instantly share code, notes, and snippets.

@tjFogarty
Last active February 7, 2018 11:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tjFogarty/7548313 to your computer and use it in GitHub Desktop.
Save tjFogarty/7548313 to your computer and use it in GitHub Desktop.
Targets form fields with prefixes to their name, e.g. <input type="text" name="prefix_name"> it will collect all data will "prefix_" in the name, or any prefix you specify in the example.
<?php
/**
* FormHandler takes care of automatically collecting form data and sending the data to a specified email address
*
* @example:
* $form = new FormHandler($from = 'guess@what.com', $to = 'what@isit.com', $subject = $_POST['form-name'], $post_data_prefix = 'obf_');
*/
class FormHandler {
public $mail;
public $post_data_prefix;
/**
* __construct()
*
* called on creation of an instance, sets up basic values of instance
*
* @param string - from address
* @param string - to address
* @param string - subject of mail
* @param string - prefix of $_POST data to collect
*/
public function __construct($from, $to, $subject, $post_data_prefix) {
$this->mail = new PHPMailer;
$this->mail->IsHTML(true);
$this->mail->From = $from;
$this->mail->Subject = $subject;
$this->mail->Body .= "<h2 style='font-family: sans-serif; margin: 0 0 20px 0; text-align: center;'>$subject</h2>";
$this->mail->AddAddress($to);
$this->post_data_prefix = $post_data_prefix;
$this->set_field_data();
}
/**
* set_field_data()
*
* collects $_POST data with certain string at the beginning
* e.g. obf_ in this
*/
public function set_field_data() {
// collect all the form data
$this->mail->Body .= "<ul style='font-family: sans-serif; list-style: none; padding: 0;'>";
foreach($_POST as $key => $value) {
// check if value starts with $this->post_data_prefix
if (strpos($key, $this->post_data_prefix) === 0) {
$label = $this->generate_readable_label($key);
// don't include if empty value
if (!empty($value)) {
$value = nl2br($value);
$this->mail->Body .= "<li style='margin-bottom: 15px;'><strong>$label</strong>: <br> $value</li>";
}
}
}
$this->mail->Body .= "</ul>";
echo $this->mail->Body;
}
/**
* generate_readable_label()
*
* @param string - label containing dashes and prefix
* @return string - a (hopefully?) readable label
*/
public function generate_readable_label($label) {
$replace = array( $this->post_data_prefix, "-");
$label = str_replace($replace, " ", $label);
$label = trim(ucwords($label));
return $label;
}
/**
* isSent()
*
* @return boolean - result depending if mail is sent or not
*/
public function isSent() {
if ($this->mail->send()) {
return true;
}
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment