Need help to troubleshoot php (Warning: Missing argument 11 ...) - php

I have had to modify some php code to suit my needs and my forms page is now spitting out this
"Warning: Missing argument 11 for cash_payment(), called in
/.../wp-content/plugins/inkappointmentpro/ink-admin/apt-form.php
on line 66 and defined in
/.../wp-content/plugins/inkappointmentpro/ink-admin/appointments-form/getway/paypal-page.php
on line 26"
when submitting the form.
Here are the two files in question. Can someone please help? I'm not a programmer, just a guy who manages to fuddle his way through this stuff usually.
paypal-page.php
<?php
/**
* Paypal Transaction
* # gateway_sandbox
* */
function gateway_sandbox() {
if (isset($_POST['submit'])) {
$db_obj = new Apt_DB();
if (file_exists($db_obj->dir . "ink-admin/appointments-form/getway/paypal/paypal_sandbox.php")) {
include_once($db_obj->dir . "ink-admin/appointments-form/getway/paypal/paypal_sandbox.php");
}
}
}
/**
* Paypal Transaction
* # gateway_paypal
* */
function gateway_paypal() {
if (isset($_POST['submit'])) {
$db_obj = new Apt_DB();
if (file_exists($db_obj->dir . "ink-admin/appointments-form/getway/paypal/paypal_response.php")) {
include_once($db_obj->dir . "ink-admin/appointments-form/getway/paypal/paypal_response.php");
}
}
}
function cash_payment($sr_apt_id, $sr_apt_time, $sr_apt_date, $sr_apt_persion_name, $sr_apt_email, $sr_apt_phone, $sr_msg, $sr_apt_message, $sr_apt_ugs, $sr_apt_lawnarea, $sr_data_rand) {
global $wpdb;
$db_obj = new Apt_DB();
$apt_service = $db_obj->tbl_service;
$appointment_data = $db_obj->tbl_appointment_data;
$sql_srdata = $wpdb->get_row("SELECT * FROM $apt_service Where service_id='$sr_apt_id'", ARRAY_N);
$cr_code = get_option('apt_currency_code');
$price = $sql_srdata[2] . '&nbsp' . $cr_code . '&nbsp- Pay Cash Later';
$priceshow = $sql_srdata[2] . '' . $cr_code;
$apt_txn_booking_date = date("F j, Y, g:i A");
$apt = new AptService();
if (isset($_POST['submit'])) {
$sql_val = $wpdb->get_row("SELECT * FROM $appointment_data Where apt_data_rand='$sr_data_rand'");
if (!$sql_val) {
$apt->insert_data_frontend($sr_apt_id, $sr_apt_date, $sr_apt_persion_name, $sql_srdata[1], $sr_apt_time, $price, $sr_apt_email, $sr_apt_phone, $sr_msg, $sr_apt_message, $sr_apt_ugs, $sr_apt_lawnarea, $sr_data_rand, $apt_txn_booking_date, 'cash');
echo '<p>Your appointment request has be submitted successfully. We will email or phone you with confirmation.</br>Thank you for choosing Saskatoon ProLawn.</p>';
/**
* Send transaction notification to admin or client
*/
$transaction_details = '';
$personname = $sr_apt_persion_name;
$servicename = $sql_srdata[1];
$aptime = $sr_apt_time;
$aptdate = $sr_apt_date;
$aptmessage = $sr_apt_message;
$aptugs = $sr_apt_ugs;
$aptlawnarea =$sr_apt_lawnarea;
$aptemail = $sr_apt_email;
$url = site_url();
$adminurl = str_replace('http://', '', $url);
$transaction_details .= "Hello $personname,\r";
$transaction_details .= "\r";
$transaction_details .= "Your appointment request has been received, below are the details of your request. \r \r";
$transaction_details .= "Service Name: $servicename \r";
$transaction_details .= "Appointment Date: $aptdate\r";
$transaction_details .= "Appointment Time: $aptime\r";
$transaction_details .= "Contact Phone: $aptphone\r";
$transaction_details .= "Address: $aptmessage\r";
$transaction_details .= "Underground Sprinklers Present: $aptugs\r";
$transaction_details .= "Lawn Area to be Done: $aptlawnarea\r \r";
$transaction_details .= "Thanks for choosing Saskatoon ProLawn.\r";
$transaction_details .= "When I confirm the date and time, I will send another email or contact you at the phone number provided. Please add us \r \r";
$transaction_details .= "Warm Regards,\r";
$transaction_details .= "Shane\r \r";
$transaction_details .= "$adminurl\r";
$subject = __("Your Appointment Request Has Been Received", 'appointment');
$filecontent = $transaction_details;
$admin_email = get_option('admin_email');
$headers = 'From: ' . $admin_email . ' <' . $aptemail . '>' . "\r\n" . 'Reply-To: ' . $admin_email;
$header = 'From: ' . $aptemail . ' <' . $admin_email . '>' . "\r\n" . 'Reply-To: ' . $aptemail;
//mail($to_admin, $subject, $filecontent, $headers);
wp_mail($aptemail, $subject, $filecontent, $headers); //email to user
wp_mail($admin_email, $subject, $filecontent, $header); //email to admin
} //refresh value if end
} //submit data if end
}
//function end
apt-form.php
<?php
add_shortcode('ink-appointments-form', 'ink_appoitment');
function ink_appoitment() {
?>
<script>
jQuery.noConflict();
jQuery(function () {
jQuery("#aptcal").datepicker();
jQuery("#aptcal").datepicker("option", "minDate", 0);
});
</script>
<?php
$db_obj = new Apt_DB();
global $wpdb;
$cpt_true = false;
$apt_service = $db_obj->tbl_service;
$check_apt = isset($_POST['chk_apt']) ? $_POST['chk_apt'] : null;
$cpt_apt = isset($_POST['apt_cpt']) ? $_POST['apt_cpt'] : null;
if ($check_apt != $cpt_apt) {
$cpt_true = true;
}
$msg = '';
$captcha_details = '';
$is_captcha_on = get_option('cpt_enable');
if ($_SERVER["REQUEST_METHOD"] == "POST" && $is_captcha_on == 'on') {
$recaptcha = $_POST['g-recaptcha-response'];
if (!empty($recaptcha)) {
$secret = get_option('apt_recaptcha_private');
$secret = empty($secret) ? 'Google secret key' : $secret;
$captcha_data = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=" . $secret . "&response=" . $_POST['g-recaptcha-response']);
$response = json_decode($captcha_data, TRUE);
if ($response['success']) {
$captcha_details = true;
} else {
$captcha_details = false;
$error = array_search("invalid-input-secret", $response['error-codes']);
if ($error == 0) {
$msg = "Please enter correct reCAPTCHA key.";
} else {
$msg = "Please re-enter your reCAPTCHA.";
}
}
} else {
$captcha_details = false;
$msg = "Please re-enter your reCAPTCHA.";
}
}
$blank_data = "";
if ((isset($_POST['submit']) && $is_captcha_on != 'on' && $cpt_true == false ) || (isset($_POST['submit']) && $captcha_details == true)) {
$_POST['time'];
if (($_POST['time'] == 'notavi') || ($_POST['service_select'] == 'notavi')) {
echo "<p>Please Insert All data.</p>";
$blank_data = true;
} else {
$blank_data = false;
echo $badUrl = (isset($_POST['sr_price'])) ? $_POST['sr_price'] : null;
if (get_option('apt_paypal') == "sandbox") {
gateway_sandbox();
} elseif (get_option('apt_paypal') == "paypal") {
gateway_paypal();
} elseif (get_option('apt_paypal') == "cash") {
$datechange = $_POST['aptcal'];
$dateformat = explode('/', $datechange);
$newaptdate = $dateformat[1] . '/' . $dateformat[0] . '/' . $dateformat[2];
cash_payment($_POST['service_select'], $_POST['time'], $newaptdate, $_POST['fname'], $_POST['aptemail'], $_POST['aptphone'], $_POST['aptmessage'], $_POST['aptugs'], $_POST['aptlawnarea'], $_POST['random']);
}
}
}
if (isset($_GET['paypal-trans'])) {
ink_apt_trans_display();
} else {
$ruri = $_SERVER['REQUEST_URI'];
$sname = $_SERVER['SERVER_NAME'];
$fullpath = 'http://' . $sname . $ruri;
update_option('return_apt_url', $fullpath);
$br = new AptService();
$iechk = $br->ink_browser();
if ((!isset($_POST['submit'])) || ($check_apt != $cpt_apt) || ($captcha_details == false) || ($blank_data == true)) {
?>
<div class="ink-container">
<div class="inkappointment_wrapper">
<div class="inkappointment_form_top">
</div>
<div class="inkappointment_form_wrapper">
<form method="post" action="" id="ink-form" name="ink-form" class="ink-form" >
<header id="ink-header" class="ink-info">
</header>
<ul class="inkappform">
<li class="textheading"><h2><span class="msg_text"><?php echo get_option('apt_form_head'); ?></span></h2></li>
<li class="textfname"><input type="text" name="fname" id="fname" class="inktext inklarge inkrequired" placeholder="Name" maxlength="100" />
<label id="apt_error"> </label>
</li>
<li class="textaptemail"><input type="email" name="aptemail" id="aptemail" class="inktext inklarge inkrequired" placeholder="Email" maxlength="100" /></li>
<li class="textaptphone"><input type="text" name="aptphone" id="aptphone" class="inktext inklarge" placeholder="Contact Number" maxlength="12” /></li>
<li class="textfixdate"><span class="fix_date"><?php echo get_option('apt_fix_date'); ?></span></li>
<li class="select_item"><select id="service_select" name="service_select" class="inktext inklarge inkrequired" >
<option value="noavi">Select Service</option>
<?php
$showts = $wpdb->get_results("SELECT * FROM $apt_service ", ARRAY_A);
foreach ($showts as $timerow) {
?>
<option value="<?php echo $timerow['service_id']; ?>"><?php echo $timerow['service_name']; ?></option>
<?php } ?> </select></li>
<li class="textaptcal"><input type="text" name="aptcal" id="aptcal" class="dateField inktext inklarge" placeholder="Select Date" /></li>
<li class="select_item"><select id="time" name="time" class="inktext inklarge inkrequired">
<option value="notavi">Select Time</option> </select></li>
<li class="textfixdate"><span class="fix_date">Do you have underground Sprinklers?</span></li>
<li class="textfixdate"><span class="fix_date"><input type="radio" name="aptugs" id="aptugs" value="yes" checked>Yes <input type="radio" name="aptugs" id="aptugs"” value="no">No</span></li>
<li class="textfixdate"><span class="fix_date">Area Required</span></li>
<li class="textfixdate"><span class="fix_date"><input type="radio" name="aptlawnarea" id="aptlawnarea" value="frontback" checked>Front+Back <br> <input type="radio" name="aptlawnarea" id="aptlawnarea" value="front">Front Only <br> <input type="radio" name="aptlawnarea" id="aptlawnarea" value=“back”>Back Only</span></li>
<li class="textfixdate"><span class="fix_date"><?php echo get_option('apt_custom_msg'); ?></span></li>
<li class="textaptmessage"><textarea name="aptmessage" id="aptmessage" class="inktext inklarge inkrequired" maxlength="255" rows="3" cols="50" placeholder="Address (required)" ></textarea></li>
<?php if ($is_captcha_on === 'on') { ?><li>
<div class="g-recaptcha-div"><div class="g-recaptcha" data-sitekey="<?php
if (get_option('apt_recaptcha_public')) {
echo get_option('apt_recaptcha_public');
} else {
echo 'Google Public Key';
}
?>"></div>
</div>
<span class='msg'><?php echo $msg; ?></span>
</li>
<?php } ?>
<li class="submit_bg">
<input type="hidden" name="random" id="random" value="<?php echo rand(); ?>"/>
<input type="submit" name="submit" id="submit" class='ink-submit inkrequired' value="Book Appointment"/> </li>
</ul>
</form>
</div>
<div class="inkappointment_form_bottom">
</div>
</div>
</div>
<?php
} //submit not set
}
}

you have missing one parameter for the following function: cash_payment()
Function Definition having 11 parameters:
function cash_payment($sr_apt_id, $sr_apt_time, $sr_apt_date, $sr_apt_persion_name, $sr_apt_email, $sr_apt_phone, $sr_msg, $sr_apt_message, $sr_apt_ugs, $sr_apt_lawnarea, $sr_data_rand) {}
Function calling 10 parameters:
cash_payment($_POST['service_select'], $_POST['time'], $newaptdate, $_POST['fname'], $_POST['aptemail'], $_POST['aptphone'], $_POST['aptmessage'], $_POST['aptugs'], $_POST['aptlawnarea'], $_POST['random']);
If you don't have any 11th parameters of any values against parameters than pass the empty string but no of parameters in definition is always equal to no of parameters of calling a function.

I think this error comes due to missing argument in cash_payment function, please check all fields of this function.
cash_payment($_POST['service_select'], $_POST['time'], $newaptdate, $_POST['fname'], $_POST['aptemail'], $_POST['aptphone'], $_POST['aptmessage'], $_POST['aptugs'], $_POST['aptlawnarea'], $_POST['random']);
}
Please try to echo all fields and check if you found any of null value.

Related

Change "FROM" mailadress in a function

I installed a plugin called Message 2 Auther and its doing the job that i request. But, i dont want the "FROM" adress to be the Wordpress default mail, i want it to be from the user that wrote the message.
I've changed so that the subject is what i want it to be, but i dont know where to find the default mail.
Here is the code:
<?php defined('ABSPATH') or die('No script kiddies please!'); ?>
<?php
function m2a_getMessageBoxHTML() {
$messagebox = '<script src="https://www.google.com/recaptcha/api.js">
</script><form class="form" method="post" action="' .
esc_url(admin_url('admin-post.php')) . '"><input style="margin-bottom:15px;"
type="text" name="subject" placeholder="Subject">';
if (!is_user_logged_in()) {
$messagebox .= '<input style="margin-bottom:15px;" type="email"
name="user_email" placeholder="Email">';
}
$messagebox .= '<textarea style="margin-bottom:15px;" name="message"
placeholder="Message"></textarea>
<input type="hidden" name="action" value="m2a_new_message"
/>
<input type="hidden" name="post_id" value="' . get_the_ID()
. '" />';
$options = get_option('m2a_setting');
if ($options['googlecaptcha'] && $options['googlecaptchapublickey']) {
$messagebox .= '<div class="g-recaptcha" data-sitekey="' .
$options['googlecaptchapublickey'] . '"></div>';
}
$messagebox .= '<input type="submit" class="button btn"
name="submit_message" value="submit" />
</form>';
return $messagebox;
}
function m2a_getPopupHTML() {
add_thickbox();
$messagebox = '<div id = "my-content-id" style = "display:none;">
<form class = "form" method = "post" action = "' . esc_url(admin_url('admin-
post.php')) . '" style = "text-align:center;">';
if (!is_user_logged_in()) {
$messagebox .= '<p class="mail_rubrik">Mail:</p><input
class="ruta_rubrik" style = "margin-bottom:15px;" type = "email" name =
"user_email" placeholder = ""><br/><br/>';
}
$messagebox .= '<p class="meddelande_text">Meddelande:</p><textarea
class="meddelande_ruta" style = "margin-bottom:15px;" name = "message"
placeholder = "" rows = "5"></textarea>
<input type = "hidden" name = "action" value = "m2a_new_message" />
<input type = "hidden" name = "post_id" value = "' . get_the_ID() . '" />';
$options = get_option('m2a_setting');
if ($options['googlecaptcha']) {
$messagebox .= '<div class="g-recaptcha" data-sitekey="' .
$options['googlecaptchapublickey'] . '"></div>';
}
$messagebox .= '<br/><br/><input type = "submit" class = "button btn" name =
"submit_message" value = "Skicka" />
</form></div>
<a href = "#TB_inline?width=auto&height=auto&inlineId=my-content-id" class =
"thickbox btn button">Skicka ett meddelande</a>';
return $messagebox;
}
function m2a_sendemail($to, $subject, $message, $usermail = 0, $post_id) {
$post_title = get_the_title($post_id);
$site_name = get_bloginfo('url');
if ($type == 'author') {
$message = "Du har ett nytt meddelande från {$usermail}<br/>Meddelande:
{$message} </a>";
} else {
$message = "Du har ett nytt meddelande från {$usermail}<br/>Meddelande:
{$message}<br/></a>";
}
$subject = "Nytt meddelande på 4 Happy Pets";
wp_mail($to, $subject, $message, array('Content-Type: text/html;
charset=UTF-8'));
}
function m2a_aftercontent() {
$m2a_setting = get_option('m2a_setting');
if (isset($m2a_setting['aftercontent']) && $m2a_setting['aftercontent'] ==
1) {
if ((!isset($m2a_setting['nonuser'])) || ($m2a_setting['nonuser'] == 1
&& is_user_logged_in())) {
function m2a_messagebox($content) {
$m2a_setting = get_option('m2a_setting');
if (is_single()) {
if ($m2a_setting['showas'] == 'messagebox')
return $content . m2a_getMessageBoxHTML();
else
return $content . m2a_getPopupHTML();
}
}
add_filter('the_content', 'm2a_messagebox');
}
}
}
add_action('init', 'm2a_aftercontent');
/*
* Saving Data to database
*/
function m2a_message_db_store() {
global $wpdb;
// global $post;
$postid = $_REQUEST['post_id'];
$authorid = get_post_field('post_author', $postid);
$subject = $_REQUEST['subject'];
$message = $_REQUEST['message'];
$options = get_option('m2a_setting');
if ($options['googlecaptcha']) {
$captcha = $_REQUEST['g-recaptcha-response'];
$response = json_decode(file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$options['googlecaptchasecretkey']."&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']), true);
if ($response['success'] == false) {
wp_safe_redirect(wp_get_referer());
}
}
if (!is_user_logged_in()) {
$userid = $_REQUEST['user_email'];
$usermail = $userid;
} else {
$userid = get_current_user_id();
$usermail = get_userdata($userid)->user_email;
}
$tableName = $wpdb->prefix . 'm2a_message';
$wpdb->insert($tableName, array('user_id' => $userid, 'author_id' =>
$authorid, 'post_id' => $postid, 'subject' => $subject, 'message' =>
$message));
$options = get_option('m2a_setting');
if (isset($options['emailtoauthor']) && $options['emailtoauthor'] == 1)
{
$to = get_userdata($authorid)->user_email;
m2a_sendemail($to, $subject, $message, $usermail, $postid);
}
if (isset($options['emailtouser']) && $options['emailtouser'] == 1) {
m2a_sendemail($usermail, $subject, $message, 0, $postid);
}
wp_safe_redirect(wp_get_referer());
}
add_action('admin_post_nopriv_m2a_new_message', 'm2a_message_db_store');
add_action('admin_post_m2a_new_message', 'm2a_message_db_store');
// Create shortcode
function messagebox($atts = array()) {
$a = get_option('m2a_setting');
$atts = shortcode_atts(array(
'style' => 'default',
), $atts, 'message2author');
if ((!isset($a['nonuser'])) || ($a['nonuser'] == 1 &&
is_user_logged_in())) {
if ($atts['style'] == 'messagebox') {
return m2a_getMessageBoxHTML();
} elseif ($atts['style'] == 'popup') {
return m2a_getPopupHTML();
} elseif ($atts['style'] == 'default') {
if ($a['showas'] == 'messagebox') {
return m2a_getMessageBoxHTML();
} elseif ($a['showas'] == 'popup') {
return m2a_getPopupHTML();
}
}
}
}
add_shortcode('message2author', 'messagebox');
?>

PHP Focus on input

I am trying to create a PHP validation FORM.
Validation errors are displaying correctly for me every time. My only problems is that I am not able to set the focus on the input with error if an error came.
For example, I am using $rut_error, $first_name_error, $last_name_error, $email_error, $address_error and I want to set focus on the corresponding input if any error came.
I tried using javascript but I am not cleared where should I put that code, Could anyone guide me how to solve it? Can I fix this only with PHP? Please help.
I tried entering here but no success:
//First name Validation
if (empty($_POST["first_name"]) and $rut_error == '')
{
$first_name_error = "First name is required";
echo "<script>document.registration.first_name.focus();</script>";
}
My code is below:
addStudent.php
<html>
<head>
<title>Add Client</title>
</head>
<body>
Show Client
<?php include('form_processStudent.php'); ?>
<div id="divAgenda">
<form id="contact" action="<?= htmlspecialchars($_SERVER["PHP_SELF"]) ?>" method="post" name = "registration">
<fieldset>
<span class="error"><?= $rut_error ?></span><br>
<input placeholder="Rut..." id="rut" type="text" name="rut" value="<?= $rut ?>" tabindex="1" size="8" maxlength="8"> - <input type="text" name="dv" value="<?= $dv ?>" size="1" tabindex="2" maxlength="1"> Ejemplo: 12345678-1<br>
</fieldset>
<fieldset>
<span class="error"><?= $first_name_error ?></span><br>
<input placeholder="Primer Nombre..." id="first_name" type="text" id="first_name" name="first_name" value="<?= $first_name ?>" maxlength="50" tabindex="3"><br>
</fieldset>
<fieldset>
<span class="error"><?= $last_name_error ?></span><br>
<input placeholder="Segundo Nombre..." id="last_name" type="text" id="last_name" name="last_name" value="<?= $last_name ?>" maxlength="50" tabindex="4"><br>
</fieldset>
<fieldset>
<span class="error"><?= $email_error ?></span><br>
<input placeholder="Correo Electrónico..." id="email" type="text" name="email" value="<?= $email ?>" maxlength="100" tabindex="5"><br>
</fieldset>
<fieldset>
<span class="error"><?= $address_error ?></span><br>
<input placeholder="Dirección..." id="address" type="text" name="address" value="<?= $address ?>" maxlength="200" tabindex="5"><br>
</fieldset>
<fieldset>
<button name="submit" type="submit" id="contact-submit" data-submit="...Sending">Enviar</button>
</fieldset>
</form>
</body>
</html>
form_processStudent.php
<?php
// define variables and set to empty values
echo"<script>
document.registration.last_name.focus();
return false;
</script>";
$rut_error = $first_name_error = $last_name_error = $email_error = $address_error = "";
$rut = $dv = $first_name = $last_name = $email = $address = "";
if(isset($_POST['submit']))
{
//RUT Validation
$rut = test_input($_POST["rut"]);
$dv = ($_POST["dv"]);
if ( empty($_POST["rut"]))
{
$rut_error = "RUT is required";
}
else if ( $dv=='' )
{
$rut_error = "Verification digit is required";
}
else if (!is_numeric($rut))
{
$rut_error = "Entered RUT is not numeric";
}
else if (!((strlen($rut) == 7) or (strlen($rut) == 8)))
{
$rut_error = "Number of digits of RUT not valid";
}
else
{
$x = 2; $s = 0; $dv2 = 0;
for($i = (strlen($rut) - 1); $i >= 0; $i--)
{
if($x > 7)
$x = 2;
$s += ($rut[$i] * $x);
$x++;
}
$dv2=11-($s % 11);
if($dv2 == 10)
$dv2 = 'K';
if($dv2 == 11)
$dv2 = '0';
if($dv2 == $dv)
{
//echo "<br>". "rut={" . $rut . "}";
//echo "<br>". "dv ={" . $dv . "}";
}
else
$rut_error = "invalid RUT";
}
//First name Validation
if (empty($_POST["first_name"]) and $rut_error == '')
{
$first_name_error = "First name is required";
echo "<script>document.registration.first_name.focus();</script>";
}
else
{
if ($rut_error == '')
{
$first_name = test_input($_POST["first_name"]);
//echo "<br>". "first_name={" . $first_name . "}";
}
}
//Last name Validation
if (empty($_POST["last_name"]) and $rut_error == '' and $first_name_error == '')
{
$last_name_error = "Second name is required";
echo "<script>function validateform()
{
document.registration.last_name.focus();
return false;
}
</script>";
}
else
{
if ($rut_error == '' and $first_name_error == '')
{
$last_name = test_input($_POST["last_name"]);
//echo "<br>". "last_name={" . $last_name . "}";
}
}
//Email Validation
if (empty($_POST["email"]) and $rut_error == '' and $first_name_error == '' and $last_name_error == '')
{
$email_error = "Email is required";
}
else
{
if ($rut_error == '' and $first_name_error == '' and $last_name_error == '')
{
$email = test_input($_POST["email"]);
//echo "<br>". "email={" . $email . "}";
// check if e-mail address is well-formed
if ((!filter_var($email, FILTER_VALIDATE_EMAIL)) and $rut_error == '' and $first_name_error == '' and $last_name_error == '')
{
$email_error = "Invalid email";
}
}
}
//Adress Validation
if (empty($_POST["address"]) and $rut_error == '' and $first_name_error == '' and $last_name_error == '' and $email_error == '')
{
$address_error = "Address is required";
}
else
{
if ($rut_error == '' and $first_name_error == '' and $last_name_error == '' and $email_error == '')
{
$address = test_input($_POST["address"]);
//echo "<br>". "address={" . $address . "}";
}
}
if ($rut_error == '' and $first_name_error == '' and $last_name_error == '' and $email_error == '' and $address_error == '')
{
//echo "<br>". "Dentro de IF";echo "<br>";
require_once('mysqli_connect.php');
$query = "INSERT INTO students (rut, dv, first_name, last_name, email, address) VALUES (?,?,?,?,?,?)";
$stmt = mysqli_prepare($dbc, $query);
mysqli_stmt_bind_param($stmt, "ssssss", $rut, $dv, $first_name, $last_name, $email, $address);
mysqli_stmt_execute($stmt);
$affected_rows = mysqli_stmt_affected_rows($stmt);
echo 'affected_rows=<' . $affected_rows . '>';
if($affected_rows == 1)
{
$rut = $dv = $first_name = $last_name = $email = $address = '';
echo "<br>"."Client Entered";
mysqli_stmt_close($stmt);
mysqli_close($dbc);
}
else
{
echo 'Error Occurred<br />';
echo mysqli_error();
mysqli_stmt_close($stmt);
mysqli_close($dbc);
}
}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
getStudentInfo.php
Add Client
<?php
// Get a connection for the database
require_once('mysqli_connect.php');
// Create a query for the database
$query = "SELECT serie, rut, dv, first_name, last_name, email, address FROM students ORDER BY serie desc";
// Get a response from the database by sending the connection
// and the query
$response = #mysqli_query($dbc, $query);
// If the query executed properly proceed
if($response)
{
echo '<table align="left" cellspacing="5" cellpadding="8">
<tr><td align="left"><b>Serie </b></td>
<td align="left"><b>Rut </b></td>
<td align="left"><b>Dígito Verificador </b></td>
<td align="left"><b>Primer Nombre </b></td>
<td align="left"><b>Segundo Nombre </b></td>
<td align="left"><b>Email </b></td>
<td align="left"><b>Dirección </b></td>
</tr>';
// mysqli_fetch_array will return a row of data from the query
// until no further data is available
while($row = mysqli_fetch_array($response))
{
echo '<tr><td align="left">' . $row['serie'] . '</td>
<td align="left">' . $row['rut'] . '</td>
<td align="left">' . $row['dv'] . '</dv>
<td align="left">' . $row['first_name'] . '</td>
<td align="left">' . $row['last_name'] . '</td>
<td align="left">' . $row['email'] . '</td>
<td align="left">' . $row['address'] . '</td>'
;
echo '</tr>';
}
echo '</table>';
}
else
{
echo "Couldn't issue database query<br />";
echo mysqli_error($dbc);
}
// Close connection to the database
mysqli_close($dbc);
?>
mysqli_connect.php
<?php
// Defined as constants so that they can't be changed
DEFINE ('DB_USER', 'studentweb');
DEFINE ('DB_PASSWORD', '123');
DEFINE ('DB_HOST', 'localhost');
DEFINE ('DB_NAME', 'dbTest');
// $dbc will contain a resource link to the database
// # keeps the error from showing in the browser
$dbc = #mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME)
OR die('Could not connect to MySQL: ' . mysqli_connect_error());
//echo "Connected...\n\n";
?>
You can do it via javascript.
You put a script that would work once the page is fully loaded.
The script will checkout the content of each <span class="error">. If some non empty one is found, it shall put the focus on it.
In your html:
<body>
...
<script type="text/javascript">
window.onload = function(){
var errors = document.querySelectorAll('.error');
for(var i = 0, l = errors.length; i < l; i++){
var error = errors[i],
shouldForcus = error.textContent.trim().length !== 0;
if(shouldFocus){
var input = error.parentNode.querySelector('input');
input.focus();
break;
}
}
}
</script>
</body>

How to debug a form that is not saving data? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have made a signup page in PHP, I've made it ask for a name, username, email, password (and confirm), gender and country. I can make it all go through except the first and last name, which are not posting to my database.
I think it won't post to the database because the names are not going through. I have tried a lot and I'm now completely stuck. I've tried google, youtube etc and I can't find anything.
<?php
session_start();
include_once("php_includes/check_login_status.php");
if($user_ok == true){
header("location: profile.php?u=".$_SESSION["username"]);
exit();
}
?>
<?php
// Ajax calls this NAME CHECK code to execute
if(isset($_POST["usernamecheck"])){
include_once("php_includes/db_connect.php");
$username = preg_replace('#[^a-z0-9]#i', '', $_POST['usernamecheck']);
$sql = "SELECT id FROM users WHERE username='$username' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$uname_check = mysqli_num_rows($query);
if (strlen($username) < 3 || strlen($username) > 16) {
echo '<strong style="color:#FFF;">3 - 16 characters please</strong>';
exit();
}
if (is_numeric($username[0])) {
echo '<strong style="color:#F00;">Usernames must begin with a letter</strong>';
exit();
}
if ($uname_check < 1) {
echo '<strong style="color:#009900;">' . $username . ' is OK</strong>';
exit();
} else {
echo '<strong style="color:#F00;">' . $username . ' is taken</strong>';
exit();
}
}
?>
<?php
// Ajax calls this REGISTRATION code to execute
if(isset($_POST["u"])){
// CONNECT TO THE DATABASE
include_once("php_includes/db_connect.php");
// GATHER THE POSTED DATA INTO LOCAL VARIABLES\
$f = $_POST['firstname'];
$l = $_POST['lastname'];
$u = preg_replace('#[^a-z0-9]#i', '', $_POST['u']);
$e = mysqli_real_escape_string($db_conx, $_POST['e']);
$p = $_POST['p'];
$g = preg_replace('#[^a-z]#', '', $_POST['g']);
$c = preg_replace('#[^a-z ]#i', '', $_POST['c']);
// GET USER IP ADDRESS
$ip = preg_replace('#[^0-9.]#', '', getenv('REMOTE_ADDR'));
// DUPLICATE DATA CHECKS FOR USERNAME AND EMAIL
$sql = "SELECT id FROM users WHERE username='$u' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$u_check = mysqli_num_rows($query);
// -------------------------------------------
$sql = "SELECT id FROM users WHERE email='$e' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$e_check = mysqli_num_rows($query);
// FORM DATA ERROR HANDLING
if($f = "" || $l = "" || $u == "" || $e == "" || $p == "" || $g == "" || $c == ""){
echo "The form submission is missing values.";
exit();
} else if ($u_check > 0){
echo "The username you entered is alreay taken";
exit();
} else if (strlen($u) < 3 || strlen($u) > 16) {
echo "Username must be between 3 and 16 characters";
exit();
} else if (is_numeric($u[0])) {
echo 'Username cannot begin with a number';
exit();
} else if (strlen($p) < 8) {
echo 'Your password must be 8 characters';
exit();
} else if ($e_check > 0){
echo "That email address is already in use in the system";
exit();
} else {
// END FORM DATA ERROR HANDLING
// Begin Insertion of data into the database
// Hash the password and apply your own mysterious unique salt
$p_md5 = md5($p);
$p_hash = hash('sha512', $p_md5);
// Add user info into the database table for the main site table
$sql = "INSERT INTO users (firstname, lastname, username, email, password, gender, country, ip, signup, lastlogin, notescheck)
VALUES('$f', '$l', '$u','$e','$p_hash','$g','$c,'$ip',now(),now(),now())";
$query = mysqli_query($db_conx, $sql);
$uid = mysqli_insert_id($db_conx);
if(!$query) {
echo "DB1, FAIL<br>";
} else {
echo "DB1, Success<br>";
}
// Establish their row in the useroptions table
$sql = 'INSERT INTO useroptions (id, username, background)
VALUES ("$uid", "$u", "original")';
$query = mysqli_query($db_conx, $sql);
if(!$query) {
echo "DB2, FAIL<br>";
} else {
echo "DB2, Success<br>";
}
// Establish their row in the links table
$url = "www.elefind.x10.bz/profile.php?u=$u";
$sql = "INSERT INTO links (link_id, site_id, url, title, subtitle, description, fulltxt, indexdate, size, md5sum, visible, level)
VALUES('', '', '$url', '$u', '$f $l', '', now(), '', '', '', '')";
$query = mysqli_query($db_conx, $sql);
if(!$query) {
echo "DB3, FAIL<br>";
} else {
echo "DB2, Success<br>";
}
echo "Fname: ".$f."<br>";
echo "Lname: ".$l."<br>";
echo "Uname: ".$u."<br>";
echo "pwd: ".$p_hash."<br>";
echo "Gender: ".$g."<br>";
echo "Country: ".$c."<br>";
echo "ip: ".$ip."<br>";
// Create directory(folder) to hold each user's files(pics, MP3s, etc.)
if (!file_exists("user/")) {
mkdir("user/", 0755);
echo "User folder created.<br>";
}
if (!file_exists("user/$u")) {
mkdir("user/$u", 0755);
echo "profile folder created.<br>";
}
// Email the user their activation link
$to = "$e";
$from = "noreply#elefind.x10.bz";
$subject = 'Elefind Account Activation';
$message = ' <!DOCTYPE html>';
$message .= ' <html>';
$message .= ' <head>';
$message .= ' <meta charset="UTF-8">';
$message .= ' <title>Elefind Message</title>';
$message .= ' </head>';
$message .= ' <body style="margin:0px; font-family:Tahoma, Geneva, sans-serif;">';
$message .= ' <table style="background:#343642;padding:40px;border:1px solid #DDD;margin:0 auto;font-family:calibri;">';
$message .= ' <tr>';
$message .= ' <td>';
$message .= ' <table style="background:#505260;width:100%;border:1px solid #CCC;padding:0;margin:0;border-collapse:collapse;max-width:100%;width:550px;border-radius:10px;">';
$message .= ' <!-- Logo -->';
$message .= ' <tr>';
$message .= ' <td style="padding:10px 30px;text-align:center;margin:0">';
$message .= ' <p>';
$message .= ' <img src="http://www.elefind.x10.bz/img/logo.png" width="100">';
$message .= ' </p>';
$message .= ' </td>';
$message .= ' </tr>';
$message .= ' <!-- Welcome Salutation -->';
$message .= ' <tr>';
$message .= ' <td style="padding:10px 30px;margin:0;font-size:2.5em;color:#4A7BA5;text-align:center;">';
$message .= ' Welcome to Elefind!';
$message .= ' </td>';
$message .= ' </tr>';
$message .= ' <!-- User Msg -->';
$message .= ' <tr>';
$message .= ' <td style="padding:10px 30px;margin:0;text-align:left;color:FFF;">';
$message .= ' <p>Hey there '.$u.',</p>';
$message .= ' <p>To activate your profile please follow link on the below link,</p>';
$message .= ' </td>';
$message .= ' </tr>';
$message .= ' <!-- Link Button -->';
$message .= ' <tr>';
$message .= ' <td style="padding:10px 30px;text-align:center;">';
$message .= ' <a href="http://elefind.x10.bz/activation.php?id='.$uid.'&u='.$u.'&e='.$e.'&p='.$p_hash.'" title="Activate Profile">';
$message .= ' <img src="http://elefind.x10.bz/img/activate.png" width="300" height="auto">';
$message .= ' </img>';
$message .= ' </a>';
$message .= ' </td>';
$message .= ' </tr>';
$message .= ' <!-- Seperator -->';
$message .= ' <tr>';
$message .= ' <td style="padding:10px 30px;">';
$message .= ' </td>';
$message .= ' </tr>';
$message .= ' <!-- Footer Content -->';
$message .= ' <tr>';
$message .= ' <td style="padding:10px 30px;margin:0;background:#555;color:#CCC;border-top:1px solid #CCC;">';
$message .= ' <p>Once your account is active you can sign in with your email adress.</p>';
$message .= ' <p>Didn\'t request this? If you didn\'t request a to make an account with us, please let us know.</p>';
$message .= ' <p>This email is sent from an unmonitored address. Please do not reply.<!-- Please use links inline to get additional information or help.--></p>';
$message .= ' <!--<p>If you no longer wish to receive these emails, click here to Unsubscribe</p>-->';
$message .= ' </td>';
$message .= ' </tr>';
$message .= ' </table>';
$message .= ' <!-- Some more content -->';
$message .= ' <tr>';
$message .= ' <td style="padding:10px 30px;margin:0;font-size:10px;">';
$message .= ' <p> Click on the link above to activate your account, If the button does not work please use the following link,</br>';
$message .= ' <a href="http://elefind.x10.bz/activation.php?id='.$uid.'&u='.$u.'&e='.$e.'&p='.$p_hash.'">';
$message .= ' http://elefind.x10.bz/activation.php?id='.$uid.'&u='.$u.'&e='.$e.'&p='.$p_hash;
$message .= ' </a>';
$message .= ' </p>';
$message .= ' </td>';
$message .= ' </tr>';
$message .= ' </td>';
$message .= ' </tr>';
$message .= ' </table>';
$message .= ' </body>';
$message .= ' </html>';
$headers = "From: $from\n";
$headers .= "MIME-Version: 1.0\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\n";
mail($to, $subject, $message, $headers);
echo "ACCOUNT_CREATED_SUCCESSFULLY";
exit();
}
exit();
}
?>
<!DOCTYPE html>
<html>
<head>
<head name="Default">
<link rel="icon" href="favicon.ico" type="image/x-icon">
<meta charset="UTF-8">
<title>Sign Up</title>
</head>
<head name="CSS">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="css/pages/signup.css">
<link rel="stylesheet" href="css/header.css">
<link rel="stylesheet" href="css/footer.css">
<link rel="stylesheet" href="css/fonts.css">
</head>
<head name="JS">
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script src="js/pages/signup.js"></script>
<script src="js/header.js"></script>
<script src="js/main.js"></script>
<script src="js/ajax.js"></script>
<script>
$('.send').click(function(e){
$(".send").addClass("sending");
})
function restrict(elem){
var tf = document.getElementById(elem);
var rx = new RegExp;
if(elem == "email"){
rx = /[' "]/gi;
} else if(elem == "username"){
rx = /[^a-z0-9]/gi;
} else if(elem == "name"){
rx = /[^a-z]/gi;
} else if(elem == "name"){
rx = /[^a-z]/gi;
}
tf.value = tf.value.replace(rx, "");
}
function emptyElement(x){
document.getElementById(x).innerHTML = "";
}
function checkusername(){
var u = document.getElementById("username").value;
if(u != ""){
document.getElementById("unamestatus").innerHTML = 'checking ...';
var ajax = ajaxObj("POST", "signup.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
document.getElementById("unamestatus").innerHTML = ajax.responseText;
}
}
ajax.send("usernamecheck="+u);
}
}
function signup(){
var fn = document.getElementById("firstname").value;
var ln = document.getElementById("lastname").value;
var u = document.getElementById("username").value;
var e = document.getElementById("email").value;
var p1 = document.getElementById("pass1").value;
var p2 = document.getElementById("pass2").value;
var c = document.getElementById("country").value;
var g = document.getElementById("gender").value;
var status = document.getElementById("status");
if(fn == "" || ln == ""|| u == "" || e == "" || p1 == "" || p2 == "" || c == "" || g == ""){
status.innerHTML = "Some of the form data is missing, Please fill it all out.<br>first name: "+fn+"<br>Last name: "+ln;
$(".send").removeClass("sending");
} else if(p1 != p2){
status.innerHTML = "Your password fields do not match";
$(".send").removeClass("sending");
} else {
var ajax = ajaxObj("POST", "signup.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText != "ACCOUNT_CREATED_SUCCESSFULLY"){
status.innerHTML = ajax.responseText;
$(".send").removeClass("sending");
} else {
window.scrollTo(0,0);
$(".send").removeClass("sending");
document.getElementById("signupform").innerHTML = "OK "+u+", check your email inbox and junk mail box at <u>"+e+"</u> in a moment to complete the sign up process by activating your account. You will not be able to do anything on the site until you successfully activate your account. <br><br>fname: "+fn+"<br>lname: "+ln+"<br> username: "+u+"<br>email: "+e+"<br>password: "+p1+ "<br><br>Correct?";
}
}
}
ajax.send("fn="+fn+"&ln="+ln+"&u="+u+"&e="+e+"&p="+p1+"&c="+c+"&g="+g);
}
}
</script>
</head>
</head>
<body>
<?php include_once("header.php"); ?>
<div class="content">
<div class="cont">
<form name="signupform" id="signupform" action="signup()">
<div class="demo">
<div class="signup">
<div class="signup__check"></div>
<div class="signup__form">
<div class="signup__row">
<input type="text" placeholder="First name" class="signup__input name" id="firstname" name="firstname" onfocus="emptyElement('status')" onkeyup="restrict('name')" maxlength="32">
<br>
</div>
<div class="signup__row">
<input type="text" placeholder="Last name" class="signup__input name" id="lastname" name="lastname" onfocus="emptyElement('status')" onkeyup="restrict('name')" maxlength="32">
<br>
</div>
<div class="signup__row">
<input type="text" placeholder="Username" class="signup__input name" id="username" onfocus="emptyElement('status')" onblur="checkusername()" onkeyup="restrict('username')" maxlength="16">
<br>
<span id="unamestatus"></span>
</div>
<div class="signup__row">
<input type="text" placeholder="Email" class="signup__input name" id="email" onfocus="emptyElement('status')" onkeyup="restrict('email')" maxlength="88">
</div>
<div class="signup__row">
<input type="password" placeholder="Password" class="signup__input pass" id="pass1" onfocus="emptyElement('status')" maxlength="16">
</div>
<div class="signup__row">
<input type="password" placeholder="Confirm password" class="signup__input pass" id="pass2" onfocus="emptyElement('status')" maxlength="16">
</div>
<div class="signup__row">
<select id="gender" onfocus="emptyElement('status')" placeholder="Gender" class="signup__input">
<option value="">Please select a gender</option>
<option value="m">Male</option>
<option value="f">Female</option>
</select>
</div>
<div class="signup__row">
<select id="country" onfocus="emptyElement('status')" placeholder="Country" class="signup__input">
<?php include_once("inc/countries.php"); ?>
</select>
</div>
<div>
<p class="signup__terms"> By creating an account you accept the terms of service </p>
</div>
<p id="status"></p>
<button id="signupbtn" onclick="signup()" class="send"name="Submit">Sign up</button>
</div>
</div>
</div>
</form>
</div>
</div>
<?php include_once("footer.php"); ?>
</body>
</html>
In your code besides what was mentioned in the comments you have an if statement that is assigning variables.
if($f = "" || $l = "" || $u == "" || $e == "" || $p == "" || $g == "" || $c == ""){}
Notice the = and not == after $f and $l, it should be:
if($f == "" || $l == "" || $u == "" || $e == "" || $p == "" || $g == "" || $c == ""){}
This way you aren't replacing the original contents and are now checking the contents.
And for future an empty() check will check for "" or even unset POST variables, allowing you to check missing POST values and empty strings in 1 go.
trap for the weary who have gazed at the screen for way, way tool long
if($f = "" || $l = "" || $u == "" || $e == "" || $p == "" || $g == "" || $c == ""){
In the line above you use a single = for $f and $l which gives them new values, in this case "".
Change it to
if($f == "" || $l == "" || $u == "" || $e == "" || $p == "" || $g == "" || $c == ""){
and you'll be back in business!

Wrong Securimage verification code still sends the form

First time poster, be gentle.
I have a form with a .php processing script that worked fine for the longest time except for the fact that I started to receive spam. I did some research on Captcha's and came across Securimage which was (supposedly) one of the easiest to implement. I downloaded the files and installed it into my script. I came across two problems.
The form was still sending if the captcha was left blank (it still notified me that it was blank).
The form was still sending if the captcha was wrong (it still notified me that it was wrong).
You can see it in action here: http://216.119.71.44/contact/
I "patched" issue 1 just by making the field a required field. I need some help fixing number 2. Below is my code and you can find the documentation for securimage here:
contact.php:
<?php
$thisPage = "Contact";
$errors = array();
$missing = array();
$date = date('F j, Y');
// check if the form has been submitted
if (isset($_POST['send'])) {
// sends the message to recipient
ini_set("SMTP","mail.abcprintingink.com");
// Please specify an SMTP Number 25 and 8889 are valid SMTP Ports.
ini_set("smtp_port","587");
// Please specify the return address to use
$to = 'paulr#abcprintingink.com'; //recipient's email address
$from = $_POST['email']; // this is the sender's Email address
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$subject = 'Online Form Submission';
$expected = array('fname','lname','email','phone','comments','captcha_code');
$required = array('fname','lname','email','phone','comments','captcha_code','');
$headers = "From: Technical Staffing Solutions";
// sends a copy of the message to the sender
$receiptHeader = "From: Technical Staffing Solutions";
$receiptSubject = "Copy of your form submission";
$receipt = "Hello " . $fname . "," . "\n" . "Below is a copy of the message you sent to us on " . $date . ". We will contact you as soon as possible. Thank you!" . "\n\n" . $_POST['comments'];
mail($from,$receiptSubject,$receipt,$receiptHeader);
// detailed processing script (checks for errors)
require('../include/processmail.php');
}
?>
<h1>CONTACT US</h1>
<?php
// Various on submit mail messages
if ($mailSent) {
echo "<div id=\"form-success\"><div>✓</div><p>Thank you " . $fname . ", your message has been sent.</p></div>";
}
elseif (($_POST && $suspect) || ($_POST && isset($errors['mailfail']))) {
echo "<div id=\"form-error\"><div>!</div><p>Your message could not be sent. Please try again.</p></div>";
}
elseif ($missing || $errors) {
echo "<div id=\"form-error\"><div>!</div><p>Please fill out the required fields and try again.</p></div>";
}
?>
<form id="getquote" method="post" action="" style="float:left;">
<input type="text" id="fname" name="fname" placeholder="First Name"
<?php if ($missing && in_array('fname', $missing)) { ?>style="border: 1px solid #cc0000;"
<?php } if ($missing || $errors) { echo 'value="' . htmlentities($fname, ENT_COMPAT, 'UTF-8') . '"'; } ?>>
<input type="text" id="lname" name="lname" placeholder="Last Name"
<?php if ($missing && in_array('lname', $missing)) { ?>style="border: 1px solid #cc0000;"
<?php } if ($missing || $errors) { echo 'value="' . htmlentities($lname, ENT_COMPAT, 'UTF-8') . '"'; } ?>>
<input type="email" id="email" name="email" placeholder="Email Address"
<?php if ($missing && in_array('email', $missing)) { ?>style="border: 1px solid #cc0000;"
<?php } if ($missing || $errors) { echo 'value="' . htmlentities($email, ENT_COMPAT, 'UTF-8') . '"'; } ?>>
<input type="text" id="phone" name="phone" placeholder="Phone Number"
<?php if ($missing && in_array('phone', $missing)) { ?>style="border: 1px solid #cc0000;"
<?php } if ($missing || $errors) { echo 'value="' . htmlentities($phone, ENT_COMPAT, 'UTF-8') . '"'; } ?>>
<textarea placeholder="How can I help you?" id="comments" name="comments"
<?php if ($missing && in_array('comments', $missing)) { ?>style="border: 1px solid #cc0000;"
<?php } if ($missing || $errors) { echo 'value="' . htmlentities($comments, ENT_COMPAT, 'UTF-8') . '"'; } ?>> </textarea><br>
<!-- Captcha -->
<img id="captcha" src="/securimage/securimage_show.php" alt="CAPTCHA Image" />
↻
<input type="text" id="captcha_code" name="captcha_code" size="10" maxlength="6"
<?php if ($missing && in_array('captcha_code', $missing)) { ?>style="border: 1px solid #cc0000;"
<?php } if ($missing || $errors) { echo 'value="' . htmlentities($captcha_code, ENT_COMPAT, 'UTF-8') . '"'; } ?>>
<!-- Submit -->
<div style="width:292px;"><input type="submit" id="send" name="send" value="SUBMIT"></div>
</form>
processmail.php:
<?php
session_start();
$suspect = false; //assume nothing is suspect
$pattern = '/Content-Type:|Bcc:|Cc:/i'; //create a pattern to locate suspect phrases
function isSuspect($val, $pattern, &$suspect) { //function to check for suspect phrases
if (is_array($val)) { //if the variable is an array, loop thorugh each element and pass it recursively back to the same function
foreach ($val as $item) {
isSuspect($item, $pattern, $suspect);
}
} else {
if(preg_match($pattern, $val)) {
$suspect = true;
}
}
}
if (!$suspect) {
foreach ($_POST as $key => $value) {
$temp = is_array($value) ? $value : trim($value); //assign to temporary variable and strip whitespace if not an array
if (empty($temp) && in_array($key, $required)) { //if empty and requires, add to $missing array
$missing[] = $key;
} elseif (in_array($key, $expected)) {
${$key} = $temp; //otherwise, assign to a variable of the same name as $key
}
}
}
if (!$suspect && !empty($email)) {
$validemail = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
if ($validemail) {
$headers .= "\r\nReply-To: $validemail";
} else {
$errors['email'] = true;
}
}
$mailSent = false;
if (!$suspect && !$missing && !$errors) { //go ahead only if not suspect and all required fields are ok
$message = "";
foreach($expected as $item) { //loop through the $expected array
if (isset(${$item}) && !empty(${$item})) {
$val = ${$item};
} else {
$val = 'Not Selected'; //if it has no value, assign 'not selected'
}
if (is_array($val)) { //if an array, expand as comma-separated string
$val = implode(', ', $val);
}
$item = str_replace(array('_', '-'), ' ', $item); //replace underscores and hyphens in the label with spaces
$message .= ucfirst($item).": $val\r\n\r\n"; //add label and value to the message body
}
$message = wordwrap($message, 70); //limit the line length to 70 characters
$mailSent = mail($to, $subject, $message, $headers);
if (!$mailSent) {
$errors['mailfail'] = true;
}
}
include_once $_SERVER['DOCUMENT_ROOT'] . '/securimage/securimage.php';
$securimage = new Securimage();
if ($securimage->check($_POST['captcha_code']) == false) {
// the code was incorrect
// you should handle the error so that the form processor doesn't continue
// or you can use the following code if there is no validation or you do not know how
echo "The security code entered was incorrect.<br /><br />";
echo "Please go <a href='javascript:history.go(-1)'>back</a> and try again.";
exit;
}

Ajax/PHP contact form not able to send mail

The funny thing is it did work for one evening. I contacted my host, and they are saying there's no reason it should not be working. I have also attempted to test it in Firebug, but it seemed to be sending. And I specifically put the email address (hosted in my domain) on my email safe list, so that is not the culprit either.
Would anyone here take a look at it for me? I'd be so grateful.
In the header I have:
<script type="text/javascript">
$(document).ready(function () {
var options = {
target: '#alert'
};
$('#contactForm').ajaxForm(options);
});
$.fn.clearForm = function () {
return this.each(function () {
var type = this.type,
tag = this.tagName.toLowerCase();
if (tag == 'form')
return $(':input', this).clearForm();
if (type == 'text' || type == 'password' || tag == 'textarea')
this.value = '';
else if (type == 'checkbox' || type == 'radio')
this.checked = false;
else if (tag == 'select')
this.selectedIndex = -1;
});
};
</script>
Here is the actual form:
<form id="contactForm" method="post" action="sendmail.php">
<fieldset>
<p>Email Me</p>
<div id="fieldset_container">
<label for="name">Your Name:</label>
<input type="text" name="name" id="name" /><br /><br />
<label for="email">Email:</label>
<input type="text" name="email" id="email" /><br /><br />
<span style="display:none;">
<label for="last">Honeypot:</label>
<input type="text" name="last" value="" id="last" />
</span><br /><br />
<label for="message">Comments & Inquiries:</label>
<textarea name="message" id="message" cols="" rows=""></textarea><br/>
</div>
<div id="submit_button">
<input type="submit" name="submit" id="submit" value="Send It" />
</div>
</fieldset>
</form>
<div class="message"><div id="alert"></div></div>
Here is the code from my validating page, sendmail.php:
<?php
// Who you want to recieve the emails from the form. (Hint: generally you.)
$sendto = 'my#emailaddress.com';
// The subject you'll see in your inbox
$subject = 'SH Contact Form';
// Message for the user when he/she doesn't fill in the form correctly.
$errormessage = 'There seems to have been a problem. May I suggest...';
// Message for the user when he/she fills in the form correctly.
$thanks = "Thanks for the email!";
// Message for the bot when it fills in in at all.
$honeypot = "You filled in the honeypot! If you're human, try again!";
// Various messages displayed when the fields are empty.
$emptyname = 'Entering your name?';
$emptyemail = 'Entering your email address?';
$emptymessage = 'Entering a message?';
// Various messages displayed when the fields are incorrectly formatted.
$alertname = 'Entering your name using only the standard alphabet?';
$alertemail = 'Entering your email in this format: <i>name#example.com</i>?';
$alertmessage = "Making sure you aren't using any parenthesis or other escaping characters in the message? Most URLS are fine though!";
//Setting used variables.
$alert = '';
$pass = 0;
// Sanitizing the data, kind of done via error messages first. Twice is better! ;-)
function clean_var($variable) {
$variable = strip_tags(stripslashes(trim(rtrim($variable))));
return $variable;
}
//The first if for honeypot.
if ( empty($_REQUEST['last']) ) {
// A bunch of if's for all the fields and the error messages.
if ( empty($_REQUEST['name']) ) {
$pass = 1;
$alert .= "<li>" . $emptyname . "</li>";
} elseif ( ereg( "[][{}()*+?.\\^$|]", $_REQUEST['name'] ) ) {
$pass = 1;
$alert .= "<li>" . $alertname . "</li>";
}
if ( empty($_REQUEST['email']) ) {
$pass = 1;
$alert .= "<li>" . $emptyemail . "</li>";
} elseif ( !eregi("^[_a-z0-9-]+(.[_a-z0-9-]+)*#[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z]{2,3})$", $_REQUEST['email']) ) {
$pass = 1;
$alert .= "<li>" . $alertemail . "</li>";
}
if ( empty($_REQUEST['message']) ) {
$pass = 1;
$alert .= "<li>" . $emptymessage . "</li>";
} elseif ( ereg( "[][{}()*+?\\^$|]", $_REQUEST['message'] ) ) {
$pass = 1;
$alert .= "<li>" . $alertmessage . "</li>";
}
//If the user err'd, print the error messages.
if ( $pass==1 ) {
//This first line is for ajax/javascript, comment it or delete it if this isn't your cup o' tea.
echo "<script>$(\".message\").hide(\"slow\").show(\"slow\"); </script>";
echo "<b>" . $errormessage . "</b>";
echo "<ul>";
echo $alert;
echo "</ul>";
// If the user didn't err and there is in fact a message, time to email it.
} elseif (isset($_REQUEST['message'])) {
//Construct the message.
$message = "From: " . clean_var($_REQUEST['name']) . "\n";
$message .= "Email: " . clean_var($_REQUEST['email']) . "\n";
$message .= "Message: \n" . clean_var($_REQUEST['message']);
$header = 'From:'. clean_var($_REQUEST['email']);
//Mail the message - for production
mail($sendto, $subject, $message, $header, "-fstephanie#stephaniehenderson.com");
//This is for javascript,
echo "<script>$(\".message\").hide(\"slow\").show(\"slow\").animate({opacity: 1.0}, 4000).hide(\"slow\"); $(':input').clearForm() </script>";
echo $thanks;
die();
//Echo the email message - for development
echo "<br/><br/>" . $message;
}
//If honeypot is filled, trigger the message that bot likely won't see.
} else {
echo "<script>$(\".message\").hide(\"slow\").show(\"slow\"); </script>";
echo $honeypot;
}
?>
If the message is echoing then it's not a problem with your javascript or html. I would suggest making a fresh PHP file with only the 1 line that attempts to send mail:
mail('youremailaddress#example.com', 'My Subject', 'This is a message');
Hardcode everything. If that works, then you know that it's probably not a problem with your host, and you need to examine that line and the variables to are passing to mail()

Categories