I'm building a PHP registration system. It will send a notification email to me if there's a new user register to my website. But the problem is, if the user doesn't enter anything, it will send a email to me also. How do I overcome this issue?
This is the validation part.
/*Validation Begins*/
if(empty($_POST) === false) {
$required_fields = array('school_name', 'mailing_address', 'postcode', 'courier_address', 'courier_postcode', 'courier_postcode', 'phonenumber', 'faxnumber', 'email', 'website', 'principal_fullname', 'principal_phonenumber', 'principal_email');
foreach($_POST as $key=>$value){
if(empty($value) && in_array($key, $required_fields) === true){
mysql_close();
?>
<script type="text/javascript">
alert("Fields marked with an asterisk are required");
history.back();
</script>
<?php
}
}
Below is the insertion function and the mail function.
function register_school($register_data){
$fields = '`' . implode('`, `', array_keys($register_data)) . '`';
$data = '\'' . implode('\', \'', $register_data) . '\'';
mysql_query("INSERT INTO `schools_info` ($fields) VALUES ($data)");
?>
<script type='text/javascript'>
alert("Registration Successful!"); window.location.href = '/registration-success/';
</script>
<?php
$schoolname = $_POST['school_name'];
$mailing_address = $_POST['mailing_address'];
$postcode = $_POST['postcode'];
$courier_address = $_POST['courier_address'];
$phonenumber = $_POST['courier_postcode'];
$faxnumber = $_POST['faxnumber'];
$email = $_POST['email'];
$website = $_POST['website'];
$principal_fullname = $_POST['principal_fullname'];
$principal_phonenumber = $_POST['principal_phonenumber'];
$principal_email = $_POST['principal_email'];
$to = "example#hotmail.com";
$subject = "New Registered School";
$message = "School Name: $schoolname\r\nSchool Address: $mailing_address\r\nPostcode: $postcode\r\nCourier Address: $courier_address\r\nCourier Postcode: $courier_postcode\r\nPhone Number: $phonenumber\r\nFax Number: $faxnumber\r\nEmail: $email\r\nWebsite: $website\r\nPrincipal Name: $principal_fullname\r\nPrincipal Phone Number: $principal_phonenumber\r\nPrincipal Email: $principal_email";
$from = "testing.com";
$headers = "From:" . $from;
mail($to,$subject,$message,$headers);
}
Register School
if(empty($_POST) === false){
$register_data = array(
'school_name' => $_POST['school_name'],
'mailing_address' => $_POST['mailing_address'],
'postcode' => $_POST['postcode'],
'courier_address' => $_POST['courier_address'],
'courier_postcode' => $_POST['courier_postcode'],
'phonenumber' => $_POST['phonenumber'],
'faxnumber' => $_POST['faxnumber'],
'email' => $_POST['email'],
'website' => $_POST['website'],
'principal_fullname' => $_POST['principal_fullname'],
'principal_phonenumber' => $_POST['principal_phonenumber'],
'principal_email' => $_POST['principal_email'],
'CScoor' => $_POST['CScoor'],
'CS_email' => $_POST['CS_email'],
'CS_phone' => $_POST['CS_phone'],
'Engcoor' => $_POST['Engcoor'],
'Eng_email' => $_POST['Eng_email'],
'Eng_phone' => $_POST['Eng_phone'],
'Mcoor' => $_POST['Mcoor'],
'M_email' => $_POST['M_email'],
'M_phone' => $_POST['M_phone'],
'Sccoor' => $_POST['Sccoor'],
'Sc_email' => $_POST['Sc_email'],
'Sc_phone' => $_POST['Sc_phone']
);
register_school($register_data);
mysql_close();
}
Before the part:
$to = "example#hotmail.com";
$subject = "New Registered School";
$message = "School Name: $schoolname\r\nSchool Address: $mailing_address\r\nPostcode: $postcode\r\nCourier Address: $courier_address\r\nCourier Postcode: $courier_postcode\r\nPhone Number: $phonenumber\r\nFax Number: $faxnumber\r\nEmail: $email\r\nWebsite: $website\r\nPrincipal Name: $principal_fullname\r\nPrincipal Phone Number: $principal_phonenumber\r\nPrincipal Email: $principal_email";
$from = "testing.com";
$headers = "From:" . $from;
mail($to,$subject,$message,$headers);
begins. Check every variable if it is empty or not:
// Edit: Sorry didn't see that you have an array about the values. Then you can make it something like this:
$success = true;
foreach($register_data as $data) {
if (empty($_POST[$data])) {
$success = false;
break;
}
}
if ($success == true) {
//then mail
}
if(empty($_POST) === false) {
$required_fields = array('school_name', 'mailing_address', 'postcode', 'courier_address', 'courier_postcode', 'courier_postcode', 'phonenumber', 'faxnumber', 'email', 'website', 'principal_fullname', 'principal_phonenumber', 'principal_email');
$flag = TRUE;
foreach($_POST as $key=>$value){
if(empty($value) && in_array($key, $required_fields) === true){
mysql_close();
$flag = FALSE;
?>
<script type="text/javascript">
alert("Fields marked with an asterisk are required");
history.back();
</script>
<?php
} // end second if
} //end foreach
if ($flag == TRUE){
$register_data = array(.....); //all $_POST value assign here
register_school($register_data);}
} //end first if
Related
I would like to let the form send a copy to the email address which the visitor entered into 'label' => 'Email'.
3 php files are handling the whole thing and are as fallows:
This is the PHP Form which handles the input of the HTML
<?php
require_once('form_process.php');
$form = array(
'subject' => 'Contact Form',
'heading' => 'Submission',
'success_redirect' => '',
'resources' => array(
'checkbox_checked' => 'Checked',
'checkbox_unchecked' => 'Unchecked',
'submitted_from' => 'Form submitted from website: %s',
'submitted_by' => 'Visitor IP address: %s',
'too_many_submissions' => 'Too many recent submissions from this IP',
'failed_to_send_email' => 'Failed to send email',
'invalid_reCAPTCHA_private_key' => 'Invalid reCAPTCHA private key.',
'invalid_field_type' => 'Unknown field type \'%s\'.',
'invalid_form_config' => 'Field \'%s\' has an invalid configuration.',
'unknown_method' => 'Unknown server request method'
),
'email' => array(
'from' => 'info#myurl.com',
'to' => 'info#myurl.com'
),
'fields' => array(
'custom_U8149' => array(
'order' => 1,
'type' => 'string',
'label' => 'Name',
'required' => true,
'errors' => array(
'required' => 'Field \'Name\' is required.'
)
),
'Email' => array(
'order' => 2,
'type' => 'email',
'label' => 'Email',
'required' => true,
'errors' => array(
'required' => 'Field \'Email\' is required.',
'format' => 'Field \'Email\' has an invalid email.'
)
),
'custom_U8139' => array(
'order' => 3,
'type' => 'string',
'label' => 'Message',
'required' => false,
'errors' => array(
)
)
)
);
process_form($form);
?>
This is the form_process.php
<?php
require_once('form_throttle.php');
function process_form($form) {
if ($_SERVER['REQUEST_METHOD'] != 'POST')
die(get_form_error_response($form['resources']['unknown_method']));
if (formthrottle_too_many_submissions($_SERVER['REMOTE_ADDR']))
die(get_form_error_response($form['resources']['too_many_submissions']));
// will die() if there are any errors
check_required_fields($form);
// will die() if there is a send email problem
email_form_submission($form);
}
function get_form_error_response($error) {
return get_form_response(false, array('error' => $error));
}
function get_form_response($success, $data) {
if (!is_array($data))
die('data must be array');
$status = array();
$status[$success ? 'FormResponse' : 'MusePHPFormResponse'] = array_merge(array('success' => $success), $data);
return json_serialize($status);
}
function check_required_fields($form) {
$errors = array();
foreach ($form['fields'] as $field => $properties) {
if (!$properties['required'])
continue;
if (!array_key_exists($field, $_REQUEST) || empty($_REQUEST[$field]))
array_push($errors, array('field' => $field, 'message' => $properties['errors']['required']));
else if (!check_field_value_format($form, $field, $properties))
array_push($errors, array('field' => $field, 'message' => $properties['errors']['format']));
}
if (!empty($errors))
die(get_form_error_response(array('fields' => $errors)));
}
function check_field_value_format($form, $field, $properties) {
$value = get_form_field_value($field, $properties, $form['resources'], false);
switch($properties['type']) {
case 'checkbox':
case 'string':
case 'captcha':
// no format to validate for those fields
return true;
case 'checkboxgroup':
if (!array_key_exists('optionItems', $properties))
die(get_form_error_response(sprintf($form['resources']['invalid_form_config'], $properties['label'])));
// If the value received is not an array, treat it as invalid format
if (!isset($value))
return false;
// Check each option to see if it is a valid value
foreach($value as $checkboxValue) {
if (!in_array($checkboxValue, $properties['optionItems']))
return false;
}
return true;
case 'radiogroup':
if (!array_key_exists('optionItems', $properties))
die(get_form_error_response(sprintf($form['resources']['invalid_form_config'], $properties['label'])));
//check list of real radio values
return in_array($value, $properties['optionItems']);
case 'recaptcha':
if (!array_key_exists('recaptcha', $form) || !array_key_exists('private_key', $form['recaptcha']) || empty($form['recaptcha']['private_key']))
die(get_form_error_response($form['resources']['invalid_reCAPTCHA_private_key']));
$resp = recaptcha_check_answer($form['recaptcha']['private_key'], $_SERVER["REMOTE_ADDR"], $_POST["recaptcha_challenge_field"], $_POST["recaptcha_response_field"]);
return $resp->is_valid;
case 'email':
return 1 == preg_match('/^[a-z0-9!#$%&\'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&\'*+\/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i', $value);
case 'radio': // never validate the format of a single radio element; only the group gets validated
default:
die(get_form_error_response(sprintf($form['resources']['invalid_field_type'], $properties['type'])));
}
}
function email_form_submission($form) {
if(!defined('PHP_EOL'))
define('PHP_EOL', '\r\n');
$form_email = ((array_key_exists('Email', $_REQUEST) && !empty($_REQUEST['Email'])) ? cleanup_email($_REQUEST['Email']) : '');
$to = $form['email']['to'];
$subject = $form['subject'];
$message = get_email_body($subject, $form['heading'], $form['fields'], $form['resources']);
$headers = get_email_headers($to, $form_email);
$sent = #mail($to, $subject, $message, $headers);
if(!$sent)
die(get_form_error_response($form['resources']['failed_to_send_email']));
$success_data = array(
'redirect' => $form['success_redirect']
);
echo get_form_response(true, $success_data);
}
function get_email_headers($to_email, $form_email) {
$headers = 'From: ' . $to_email . PHP_EOL;
$headers .= 'Reply-To: ' . $form_email . PHP_EOL;
$headers .= 'X-Mailer: Adobe Muse CC 2015.0.2.310 with PHP' . PHP_EOL;
$headers .= 'Content-type: text/html; charset=utf-8' . PHP_EOL;
return $headers;
}
function get_email_body($subject, $heading, $fields, $resources) {
$message = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">';
$message .= '<html xmlns="http://www.w3.org/1999/xhtml">';
$message .= '<head><meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/><title>' . encode_for_form($subject) . '</title></head>';
$message .= '<body style="background-color: #ffffff; color: #000000; font-style: normal; font-variant: normal; font-weight: normal; font-size: 12px; line-height: 18px; font-family: helvetica, arial, verdana, sans-serif;">';
$message .= '<h2 style="background-color: #eeeeee;">' . $heading . '</h2>';
$message .= '<table cellspacing="0" cellpadding="0" width="100%" style="background-color: #ffffff;">';
$sorted_fields = array();
foreach ($fields as $field => $properties) {
// Skip reCAPTCHA from email submission
if ('recaptcha' == $properties['type'])
continue;
array_push($sorted_fields, array('field' => $field, 'properties' => $properties));
}
// sort fields
usort($sorted_fields, 'field_comparer');
foreach ($sorted_fields as $field_wrapper)
$message .= '<tr><td valign="top" style="background-color: #ffffff;"><b>' . encode_for_form($field_wrapper['properties']['label']) . ':</b></td><td>' . get_form_field_value($field_wrapper['field'], $field_wrapper['properties'], $resources, true) . '</td></tr>';
$message .= '</table>';
$message .= '<br/><br/>';
$message .= '<div style="background-color: #eeeeee; font-size: 10px; line-height: 11px;">' . sprintf($resources['submitted_from'], encode_for_form($_SERVER['SERVER_NAME'])) . '</div>';
$message .= '<div style="background-color: #eeeeee; font-size: 10px; line-height: 11px;">' . sprintf($resources['submitted_by'], encode_for_form($_SERVER['REMOTE_ADDR'])) . '</div>';
$message .= '</body></html>';
return cleanup_message($message);
}
function field_comparer($field1, $field2) {
if ($field1['properties']['order'] == $field2['properties']['order'])
return 0;
return (($field1['properties']['order'] < $field2['properties']['order']) ? -1 : 1);
}
function is_assoc_array($arr) {
if (!is_array($arr))
return false;
$keys = array_keys($arr);
foreach (array_keys($arr) as $key)
if (is_string($key)) return true;
return false;
}
function json_serialize($data) {
if (is_assoc_array($data)) {
$json = array();
foreach ($data as $key => $value)
array_push($json, '"' . $key . '": ' . json_serialize($value));
return '{' . implode(', ', $json) . '}';
}
if (is_array($data)) {
$json = array();
foreach ($data as $value)
array_push($json, json_serialize($value));
return '[' . implode(', ', $json) . ']';
}
if (is_int($data) || is_float($data))
return $data;
if (is_bool($data))
return $data ? 'true' : 'false';
return '"' . encode_for_json($data) . '"';
}
function encode_for_json($value) {
return preg_replace(array('/([\'"\\t\\\\])/i', '/\\r/i', '/\\n/i'), array('\\\\$1', '\\r', '\\n'), $value);
}
function encode_for_form($text) {
$text = stripslashes($text);
return htmlentities($text, ENT_QUOTES, 'UTF-8');// need ENT_QUOTES or webpro.js jQuery.parseJSON fails
}
function get_form_field_value($field, $properties, $resources, $forOutput) {
$value = $_REQUEST[$field];
switch($properties['type']) {
case 'checkbox':
return (($value == '1' || $value == 'true') ? $resources['checkbox_checked'] : $resources['checkbox_unchecked']);
case 'checkboxgroup':
if (!is_array($value))
return NULL;
$outputValue = array();
foreach ($value as $checkboxValue)
array_push($outputValue, $forOutput ? encode_for_form($checkboxValue) : stripslashes($checkboxValue));
if ($forOutput)
$outputValue = implode(', ', $outputValue);
return $outputValue;
case 'radiogroup':
return ($forOutput ? encode_for_form($value) : stripslashes($value));
case 'string':
case 'captcha':
case 'recaptcha':
case 'email':
return encode_for_form($value);
case 'radio': // never validate the format of a single radio element; only the group gets validated
default:
die(get_form_error_response(sprintf($resources['invalid_field_type'], $properties['type'])));
}
}
function cleanup_email($email) {
$email = encode_for_form($email);
$email = preg_replace('=((<CR>|<LF>|0x0A/%0A|0x0D/%0D|\\n|\\r)\S).*=i', null, $email);
return $email;
}
function cleanup_message($message) {
$message = wordwrap($message, 70, "\r\n");
return $message;
}
?>
This is the form_throttle.php
<?php
function formthrottle_check()
{
if (!is_writable('.'))
{
return '8';
}
try
{
if (in_array("sqlite",PDO::getAvailableDrivers(),TRUE))
{
$db = new PDO('sqlite:muse-throttle-db.sqlite3');
if ( file_exists('muse-throttle-db') )
{
unlink('muse-throttle-db');
}
}
else if (function_exists("sqlite_open"))
{
$db = new PDO('sqlite2:muse-throttle-db');
if ( file_exists('muse-throttle-db.sqlite3') )
{
unlink('muse-throttle-db.sqlite3');
}
}
}
catch( PDOException $Exception ) {
return '9';
}
$retCode ='5';
if ($db)
{
$res = $db->query("SELECT 1 FROM sqlite_master WHERE type='table' AND name='Submission_History';");
if (!$res or $res->fetchColumn() == 0)
{
$created = $db->exec("CREATE TABLE Submission_History (IP VARCHAR(39), Submission_Date TIMESTAMP)");
if($created == 0)
{
$created = $db->exec("INSERT INTO Submission_History (IP,Submission_Date) VALUES ('256.256.256.256', DATETIME('now'))");
}
if ($created != 1)
{
$retCode = '2';
}
}
if($retCode == '5')
{
$res = $db->query("SELECT COUNT(1) FROM Submission_History;");
if ($res && $res->fetchColumn() > 0)
{
$retCode = '0';
}
else
$retCode = '3';
}
// Close file db connection
$db = null;
}
else
$retCode = '4';
return $retCode;
}
function formthrottle_too_many_submissions($ip)
{
$tooManySubmissions = false;
try
{
if (in_array("sqlite",PDO::getAvailableDrivers(),TRUE))
{
$db = new PDO('sqlite:muse-throttle-db.sqlite3');
}
else if (function_exists("sqlite_open"))
{
$db = new PDO('sqlite2:muse-throttle-db');
}
}
catch( PDOException $Exception ) {
return $tooManySubmissions;
}
if ($db)
{
$res = $db->query("SELECT 1 FROM sqlite_master WHERE type='table' AND name='Submission_History';");
if (!$res or $res->fetchColumn() == 0)
{
$db->exec("CREATE TABLE Submission_History (IP VARCHAR(39), Submission_Date TIMESTAMP)");
}
$db->exec("DELETE FROM Submission_History WHERE Submission_Date < DATETIME('now','-2 hours')");
$stmt = $db->prepare("INSERT INTO Submission_History (IP,Submission_Date) VALUES (:ip, DATETIME('now'))");
$stmt->bindParam(':ip', $ip);
$stmt->execute();
$stmt->closeCursor();
$stmt = $db->prepare("SELECT COUNT(1) FROM Submission_History WHERE IP = :ip;");
$stmt->bindParam(':ip', $ip);
$stmt->execute();
if ($stmt->fetchColumn() > 25)
$tooManySubmissions = true;
// Close file db connection
$db = null;
}
return $tooManySubmissions;
}
?>
I have a form and it's been bugging for a while now, when i have all the information filled up in the forms it seems to insert it very quick, however if one or more fields are empty it doesn't work at all
the query i am using to insert into the database is. i am trying to figure out if i can use Insert_delay and maybe it will solve the problem? any possible solutions or changes i need to do
function student($param1 = '', $param2 = '', $param3 = '')
{
if ($this->session->userdata('admin_login') != 1)
redirect('login', 'refresh');
if ($param1 == 'create') {
$data['name'] = $this->input->post('name');
$data['sex'] = $this->input->post('sex');
$data['address'] = $this->input->post('address');
$data['phone'] = $this->input->post('phone');
$data['email'] = $this->input->post('email');
$data['password'] = $this->input->post('password');
$data['year'] = $this->input->post('year');
$data['rate'] = $this->input->post('rate');
$data['class_id'] = $this->input->post('class_id');
$data['class_id2'] = $this->input->post('class_id2');
$data['class_id3'] = $this->input->post('class_id3');
$data['class_id4'] = $this->input->post('class_id4');
$data['parent_id'] = $this->input->post('parent_id');
$data['roll'] = $this->input->post('roll');
$this->db->insert_('student', $data);
$student_id = $this->db->insert_id();
$this->session->set_flashdata('flash_message' , get_phrase('Student_added_successfully'));
$this->email_model->account_opening_email('student', $data['email']); //SEND EMAIL ACCOUNT OPENING EMAIL
redirect(base_url() . 'index.php?admin/student_add/' . $data['class_id'], 'refresh');
In controller
function student($param1, $param2 $param3 )
{
if ($this->session->userdata('admin_login') != 1)
{
redirect('login', 'refresh');
}
else
{
if($param1 == 'create') {
$result = $this->model_name->insert_data();
if ($result != FALSE) {
$email => $this->input->post('email');
$confirm = $this->email_model->account_opening_email('student', $email); # do same as insert
if ($confirm != FALSE) {
$this->session->set_flashdata('flash_message' , get_phrase('Student_added_successfully'));
redirect(base_url() . 'index.php?admin/student_add/' . $data['class_id'], 'refresh');
}
else
{
echo "Mail send failed";
}
}
else
{
echo "param1 is not create";
}
}
}
}
In Model
public function insert_data()
{
# to isert data, I add them in to one array
$data = array(
'name' => $this->input->post('name'),
'sex' => $this->input->post('sex'),
'address' => $this->input->post('address'),
'phone' => $this->input->post('phone'),
'email' => $this->input->post('email'),
'password' => $this->input->post('password'),
'year' => $this->input->post('year'),
'rate' => $this->input->post('rate'),
'class_id' => $this->input->post('class_id'),
'class_id2' => $this->input->post('class_id2'),
'class_id3' => $this->input->post('class_id3'),
'class_id4' => $this->input->post('class_id4'),
'parent_id' => $this->input->post('parent_id'),
'roll' => $this->input->post('roll')
);
if (!$this->db->insert('student', $data)) {
# insert FAILED
return FALSE;
}
else{
# insert SUCCESS
$slast_id = $this->db->insert_id(); # get last insert ID
return = $slast_id;
}
}
I am trying to clear whitespace and add a '#' character at the beginning when the user inputs a name to post to the database.
I already have a working script to allow users to input data and modify it, but I want to include a script where the whitespace is cleared and a '#' is added before the name.
E.g. If user inputs 'John Whatsmyname' - it will be posted as - #JohnWhatsmyname in the table
I thought it would just be as simple as adding something like this;
$name = ($_POST['name']);
$name = '#'.str_replace(' ', '', $name);
$name = preg_replace('/\s+/', '', $name);
Currently I have the following HTML;
<input type="text" value="<?php echo $user_data['name']; ?>" placeholder="username" name="name"/>
<input type="text" value="<?php echo $user_data['email']; ?>" placeholder="Email" name="email"/>
Full PHP script:
<?php
if (empty($_POST) === false) {
$required_fields = array('name', 'email');
foreach($_POST as $key=>$value) {
if (empty($value) && in_array($key, $required_fields) === true) {
$errors[] = 'Name & email are required';
break 1;
}
}
$name = ($_POST['name']);
$name = '#'.str_replace(' ', '', $name);
$name = preg_replace('/\s+/', '', $name);
<?php
if (isset($_GET['success']) === true && empty($_GET['success']) === true) {
echo 'Your details have been updated!';
} else {
if (empty($_POST) === false && empty($errors) === true) {
$update_data = array(
'info' => $_POST['info'],
'website' => $_POST['website'],
'location' => $_POST['location'],
$name => $_POST['name'],
'email' => $_POST['email'],
);
update_user($session_user_id, $update_data);
header('Location: profile.php?success');
exit();
} else if (empty($errors) === false) {
echo output_errors($errors);
}
}
?>
I think when I am applying the changes I am doing nothing with then therefore the script continues and updates the table with the original data - I have echoed the $name variable and I get the error undefined variable.
The script needs to change the name by putting a '#' at the beginning and removes all whitespace not just the beginning and end before posting to the table. Trying to avoid error messages and have a script to fix the problem.
Thanks (Y)
You are not seeing it work because you do all the work to process $name, and then your $update_data array goes and pulls a fresh copy from the global $_POST array. Instead, you should change it to this:
$name = isset($_POST['name']) ? trim($_POST['name']) : '';
if (empty($name))
{
die('No name provided');
}
// Format name
$name = '#'.str_replace(' ', '', $name);
$update_data = array(
'info' => $_POST['info'],
'website' => $_POST['website'],
'location' => $_POST['location'],
'name' => $name,
'email' => $_POST['email'],
);
I'm relatively new to WordPress and PHP, however I am trying to create my own shortcode plugin, which I have completed and is working.
However if I add more than 1 on the same page in WP, both forms submit and are not exclusive of each other.
I have search around the web, but can't find out how to easily separate the form id's, below is my plugin code:
function wptuts_contact_form_sc($atts, $content = null) {
extract(shortcode_atts(array(
//"email" => get_bloginfo('admin_email'),
"id" => '',
"attachment" => '',
"desc" => '',
"subject" => '',
"label_email" => 'Your E-mail Address',
"label_submit" => 'Submit',
"error_empty" => 'Please fill in all the required fields.',
"error_noemail" => 'Please enter a valid e-mail address.',
"success" => 'Thanks, your voucher has been sent to '
), $atts));
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$error = false;
$required_fields = array("email");
foreach ($_POST as $field => $value) {
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
$form_data[$field] = strip_tags($value);
}
foreach ($required_fields as $required_field) {
$value = trim($form_data[$required_field]);
if(empty($value)) {
$error = true;
$result = $error_empty;
}
}
if(!is_email($form_data['email'])) {
$error = true;
$result = $error_noemail;
}
if ($error == false) {
$email_subject = "Eurest Voucher - " . $desc;
$email_message = "Hi, Your requested voucher/offer is attached to this email.";
$headers = "From: Eurest Vouchers <Vouchers#eurestfood.com>\n";
$headers .= "Content-Type: text/plain; charset=UTF-8\n";
$headers .= "Content-Transfer-Encoding: 8bit\n";
$attachments = array(WP_CONTENT_DIR . $attachment);
$email = $form_data['email'];
wp_mail($email, $email_subject, $email_message, $headers, $attachments);
$result = $success . $form_data['email'];
$sent = true;
}
}
if($result != "") {
$info = '<div class="info">'.$result.'</div>';
}
$email_form = '<form class="contact-form" method="post" id="'.$id.'" action="'.get_permalink().'">
<div>
<label for="cf_email">'.$label_email.':</label>
<input type="text" name="email" id="cf_email" size="50" maxlength="50" value="'.$form_data['email'].'" /><input type="submit" value="'.$label_submit.'" name="send" id="cf_send" />
</div>
</form>';
if($sent == true) {
return $info;
} else {
return $info.$email_form;
}
} add_shortcode('emailattachment', 'wptuts_contact_form_sc');
If someone can help that would be appreciated.
Thanks,
Steve
I am pretty sure you've forgotten the last attribute in the function shortcode_atts, even if it's optionnal, you need to call it.
Also, is there some code missing ?
edit : you need to id your forms otherwise the function will pick up the datas twice. call the second shortcode giving the value 'second' to teh variable $num_f like so [wptuts_contact_form_sc -your bunch of vars here- num_f="second"]
function wptuts_contact_form_sc($atts, $content = null) {
extract(shortcode_atts(array(
//"email" => get_bloginfo('admin_email'),
"id" => '',
"attachment" => '',
"desc" => '',
"subject" => '',
"label_email" => 'Your E-mail Address',
"label_submit" => 'Submit',
"error_empty" => 'Please fill in all the required fields.',
"error_noemail" => 'Please enter a valid e-mail address.',
"success" => 'Thanks, your voucher has been sent to ',
"num_f" => 'first'
), $atts));
if ($_SERVER['REQUEST_METHOD'] == 'POST' && $num_f == 'second') {
$error = false;
$required_fields = array("email");
foreach ($_POST as $field => $value) {
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
$form_data[$field] = strip_tags($value);
}
foreach ($required_fields as $required_field) {
$value = trim($form_data[$required_field]);
if(empty($value)) {
$error = true;
$result = $error_empty;
}
}
if(!is_email($form_data['email'])) {
$error = true;
$result = $error_noemail;
}
if ($error == false) {
$email_subject = "Eurest Voucher - " . $desc;
$email_message = "Hi, Your requested voucher/offer is attached to this email.";
$headers = "From: Eurest Vouchers <Vouchers#eurestfood.com>\n";
$headers .= "Content-Type: text/plain; charset=UTF-8\n";
$headers .= "Content-Transfer-Encoding: 8bit\n";
$attachments = array(WP_CONTENT_DIR . $attachment);
$email = $form_data['email'];
wp_mail($email, $email_subject, $email_message, $headers, $attachments);
$result = $success . $form_data['email'];
$sent = true;
}
}
if($result != "") {
$info = '<div class="info">'.$result.'</div>';
}
$email_form = '<form class="contact-form" method="post" id="'.$id.'" action="'.get_permalink().'">
<div>
<label for="cf_email">'.$label_email.':</label>
<input type="text" name="email" id="cf_email" size="50" maxlength="50" value="'.$form_data['email'].'" /><input type="submit" value="'.$label_submit.'" name="send" id="cf_send" />
</div>
</form>';
if($sent == true) {
return $info;
} else {
return $info.$email_form;
}
} add_shortcode('emailattachment', 'wptuts_contact_form_sc');
To have more than two forms, you can either do it manually by calling the third block 'trird' and so on, but that's not very good practice to be honest...
If I were you I would change your code at the core, create a function that would return the form with a hidden field like so : <input type"hidden" name="hidden" value=" . $nf . "> and then instead of controling $_SERVER['REQUEST_METHOD'], you'd control the value of $_POST['n'] after checking if it's set ofc.
Here's the code I came up with :
<?php
function wptuts_contact_form_sc($atts, $content = null) {
extract(shortcode_atts(array(
//"email" => get_bloginfo('admin_email'),
"id" => '',
"attachment" => '',
"desc" => '',
"subject" => '',
"label_email" => 'Your E-mail Address',
"label_submit" => 'Submit',
"error_empty" => 'Please fill in all the required fields.',
"error_noemail" => 'Please enter a valid e-mail address.',
"success" => 'Thanks, your voucher has been sent to ',
"nf" => '1'
), $atts));
if (isset($_POST['hidden'])) {
$hidden = $_POST['hidden'];
$error = false;
$required_fields = array("email");
foreach ($_POST as $field => $value) {
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
$form_data[$field] = strip_tags($value);
}
foreach ($required_fields as $required_field) {
$value = trim($form_data[$required_field]);
if(empty($value)) {
$error = true;
$result = $error_empty;
}
}
if(!is_email($form_data['email'])) {
$error = true;
$result = $error_noemail;
}
if ($error == false) {
$email_subject = "Eurest Voucher - " . $desc;
$email_message = "Hi, Your requested voucher/offer is attached to this email.";
$headers = "From: Eurest Vouchers <Vouchers#eurestfood.com>\n";
$headers .= "Content-Type: text/plain; charset=UTF-8\n";
$headers .= "Content-Transfer-Encoding: 8bit\n";
$attachments = array(WP_CONTENT_DIR . $attachment);
$email = $form_data['email'];
wp_mail($email, $email_subject, $email_message, $headers, $attachments);
$result = $success . $form_data['email'];
$sent = true;
}
} else {
$hidden = $_POST['hidden'];
}
for ($i = 1; $i <= $nf; $i++) {
if($result != "" && $i == $hidden) {
$info = '<div class="info">'.$result.'</div>';
}
$email_form = '<form class="contact-form" method="post" id="'.$id.'" action="'.get_permalink().'">
<div>
<label for="cf_email">'.$label_email.':</label>
<input type="hidden" name="hidden" value="' . $nf . '">
<input type="text" name="email" id="cf_email" size="50" maxlength="50" value="'.$form_data['email'].'" /><input type="submit" value="'.$label_submit.'" name="send" id="cf_send" />
</div>
</form>';
if($sent == true) {
return $info;
} else {
return $info . $email_form;
}
}
} add_shortcode('emailattachment', 'wptuts_contact_form_sc');
?>
Let me know if it works, (or does not) I obviously couldnt test it so there might be somehting wrong, in which case I just hope you got the whole idea behind it.
Hi i'd like some help please. i'm having a function for validating required fields of forms, in which i pass the req. fields in an array, so if is empty e.g first_name returns an error message: "The first_name is empty." . The problem is that i would like to make the name of the field in the message to look more "friendly" to the user, no camelCases or '_'. How can i achieve this?
p.s. here's my code:
$required_fields = array('first_name', 'last_name', 'email', 'profileInfo', 'message');
$errors = array_merge($errors, check_required_fields($required_fields));
Right now the output error message looks like :
"The first_name is required" or "The profileInfo is required".
The function is this:
function check_required_fields($required_fields) {
$field_errors = array();
foreach($_POST as $field=>$value){
if(empty($value) && in_array($field, $required_fields) === true){
$field_errors[] = "the " . $field . " is required.";
//break 1;
}
}
return $field_errors;
}
You could give each required field a label...
$required_fields = array(
'first_name' => 'First Name',
'last_name' => 'Last name',
'email' => 'Email Address',
'profileInfo' => 'Profile information',
'message' => 'Message'
);
$errors = array_merge($errors, check_required_fields($required_fields));
You will need to alter check_required_fields method to handle the $required_fields array correctly, like this:
function check_required_fields($required_fields)
{
$field_errors = array();
foreach ($_POST as $field => $value)
{
if (empty($value) && array_key_exists($field, $required_fields) === true)
{
$field_errors[] = "the " . $required_fields[$field] . " is required.";
//break 1;
}
}
return $field_errors;
}
Edit: I have just noticed that your loop on $_POST will only work as expected if the fields are set. Try the following:
function check_required_fields($required_fields)
{
$field_errors = array();
foreach ($required_fields as $field => $label)
{
$value = $_POST[$field];
if (empty($value))
{
$field_errors[] = "the " . $label . " is required.";
//break 1;
}
}
return $field_errors;
}