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');
?>
Related
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>
On my website, when you fill out the donation form at the bottom of the page and click 'Make Donation', you are directed to PayPal and greeted with the following error message:
This recipient does not accept payments denominated in USD. Please contact the seller and ask him to update his payment receiving preferences to accept this currency.
So it seems my website is trying to submit the donation amount in USD and it should be submitting it in GBP... From the code I have, I can't see anything that relates to USD, I see this in code for the donate form:
<div id="donate_form" style="width:465px; text-align:right; margin-left:auto; margin-right:auto;">
<form action="https://www.paypal.com/cgi-bin/webscr" target="_self" method="post" name="form1" id="form1">
<input type="hidden" name="cmd" value="_donations">
<input type="hidden" name="business" value="office#lifechurch.org.uk">
<input type="hidden" name="lc" value="GB">
<input type="hidden" name="item_name" value="CLC">
<input type="hidden" name="currency_code" value="GBP">
<input type="hidden" name="no_note" value="1">
<input type="hidden" name="no_shipping" value="1">
<input type="hidden" name="rm" value="1">
<input type="hidden" name="return" value="http://www.lifechurchgive.org.uk/thanks.php">
<input type="hidden" name="cancel_return" value="http://www.lifechurchgive.org.uk/cancel.php">
<input type="hidden" name="currency_code" value="GBP">
<!--<input type="hidden" name="cmd" value="_s-xclick">
<input type="hidden" name="encrypted" value="-----BEGIN PKCS7-----MIIHNwYJKoZIhvcNAQcEoIIHKDCCByQCAQExggEwMIIBLAIBADCBlDCBjjELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAkNBMRYwFAYDVQQHEw1Nb3VudGFpbiBWaWV3MRQwEgYDVQQKEwtQYXlQYWwgSW5jLjETMBEGA1UECxQKbGl2ZV9jZXJ0czERMA8GA1UEAxQIbGl2ZV9hcGkxHDAaBgkqhkiG9w0BCQEWDXJlQHBheXBhbC5jb20CAQAwDQYJKoZIhvcNAQEBBQAEgYA74FWzLn4DCnIxB4zk6BVnMALPccZk2MtVPpyqhdS73b9KVOplD/EmBSfA7dLaR9hDhrTxjMx4ETwpvBCQv+Zc4QF18NYerp5z9CG4w7u3ub7qdrrMn7Nxt6fck0PhKSCR0Unkw0GYNf4guAJd0qA5M1Ay28/9EKbWRhZ/yT0oOjELMAkGBSsOAwIaBQAwgbQGCSqGSIb3DQEHATAUBggqhkiG9w0DBwQIsI+wvT8gvKCAgZAEJyJIEuHOul3ToE/PBTa7v/1stUZAPWoM6WO/2tNTyFVPNi2CUeH80iQ6iB+E56mJIP2zlzoD2MLQCtQdgU8G7enxyuo48ZKstDoPbWICqmcKsuEJKAZ6O6QZRAzFjQoWQA32LlpYSvS9tj92PLNpjefNH2c2oDCx/jv10GXu+VWxq8733kPHsBAK1z61G4OgggOHMIIDgzCCAuygAwIBAgIBADANBgkqhkiG9w0BAQUFADCBjjELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAkNBMRYwFAYDVQQHEw1Nb3VudGFpbiBWaWV3MRQwEgYDVQQKEwtQYXlQYWwgSW5jLjETMBEGA1UECxQKbGl2ZV9jZXJ0czERMA8GA1UEAxQIbGl2ZV9hcGkxHDAaBgkqhkiG9w0BCQEWDXJlQHBheXBhbC5jb20wHhcNMDQwMjEzMTAxMzE1WhcNMzUwMjEzMTAxMzE1WjCBjjELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAkNBMRYwFAYDVQQHEw1Nb3VudGFpbiBWaWV3MRQwEgYDVQQKEwtQYXlQYWwgSW5jLjETMBEGA1UECxQKbGl2ZV9jZXJ0czERMA8GA1UEAxQIbGl2ZV9hcGkxHDAaBgkqhkiG9w0BCQEWDXJlQHBheXBhbC5jb20wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAMFHTt38RMxLXJyO2SmS+Ndl72T7oKJ4u4uw+6awntALWh03PewmIJuzbALScsTS4sZoS1fKciBGoh11gIfHzylvkdNe/hJl66/RGqrj5rFb08sAABNTzDTiqqNpJeBsYs/c2aiGozptX2RlnBktH+SUNpAajW724Nv2Wvhif6sFAgMBAAGjge4wgeswHQYDVR0OBBYEFJaffLvGbxe9WT9S1wob7BDWZJRrMIG7BgNVHSMEgbMwgbCAFJaffLvGbxe9WT9S1wob7BDWZJRroYGUpIGRMIGOMQswCQYDVQQGEwJVUzELMAkGA1UECBMCQ0ExFjAUBgNVBAcTDU1vdW50YWluIFZpZXcxFDASBgNVBAoTC1BheVBhbCBJbmMuMRMwEQYDVQQLFApsaXZlX2NlcnRzMREwDwYDVQQDFAhsaXZlX2FwaTEcMBoGCSqGSIb3DQEJARYNcmVAcGF5cGFsLmNvbYIBADAMBgNVHRMEBTADAQH/MA0GCSqGSIb3DQEBBQUAA4GBAIFfOlaagFrl71+jq6OKidbWFSE+Q4FqROvdgIONth+8kSK//Y/4ihuE4Ymvzn5ceE3S/iBSQQMjyvb+s2TWbQYDwcp129OPIbD9epdr4tJOUNiSojw7BHwYRiPh58S1xGlFgHFXwrEBb3dgNbMUa+u4qectsMAXpVHnD9wIyfmHMYIBmjCCAZYCAQEwgZQwgY4xCzAJBgNVBAYTAlVTMQswCQYDVQQIEwJDQTEWMBQGA1UEBxMNTW91bnRhaW4gVmlldzEUMBIGA1UEChMLUGF5UGFsIEluYy4xEzARBgNVBAsUCmxpdmVfY2VydHMxETAPBgNVBAMUCGxpdmVfYXBpMRwwGgYJKoZIhvcNAQkBFg1yZUBwYXlwYWwuY29tAgEAMAkGBSsOAwIaBQCgXTAYBgkqhkiG9w0BCQMxCwYJKoZIhvcNAQcBMBwGCSqGSIb3DQEJBTEPFw0xMDAyMTYxNDMwMjZaMCMGCSqGSIb3DQEJBDEWBBRhSOhijH/bIHYvkaiATB9JixUOKTANBgkqhkiG9w0BAQEFAASBgCysjBqxhxIbLnuQ+svn2XPkAIp8Sttix4ScbAi7MEiYYM2hx6Vd67JUGxBzCUlOO8PHzRcrqcR2nl9S8YnVZ+GfWcUZHHmdN6b8tgHPmgYrOSZkkv+UI/GW8q35KzMj58i6ssO8iiTnXngmNN15iOMR2B1EUy9Ll6XShl9Q7d4j-----END PKCS7-----">-->
<span id="ajaxresult" name="ajaxresult"><?PHP include("validate.php"); ?></span>
<?PHP
#$ajax = "loadXMLDoc('/validate.php','ajaxresult','submit2','displaydonation=true&title1='+title1.value+'&first_name='+first_name.value+'&last_name='+last_name.value+'&H_PhoneNumber='+H_PhoneNumber.value+'&email='+email.value+'&amount='+amount.value+'&message='+message.value);document.getElementById('submit2').disabled=true;cursor_wait();";
$ajax = "loadXMLDoc('/validate.php','ajaxresult','submit2','displaydonation=true&title1='+title1.value+'&first_name='+first_name.value+'&last_name='+last_name.value+'&email='+email.value+'&amount='+amount.value+'&message='+message.value+'&giftaid='+giftaid.checked);document.getElementById('submit2').disabled=true;cursor_wait();";
echo '<br /><div class="submitbutton">'.make_form_var('input','button','submit2','submit2','Make Donation','','','','','','','','','',$ajax).'</div>';
?>
</form>
<!--
<img src="https://www.paypal.com/en_US/i/btn/btn_donateCC_LG.gif" alt="PayPal - The safer, easier way to pay online!" /> -->
</div><!-- end of donate_form -->
It does have a lot thats commented out.
I have a validate.php file, but I don't see anything about currency / GBP / USD in there so there must be something that sets it to USD but doesn't use those terms perhaps?
I'll actually post the code thats in the validation.php file sorry about the length...
<?PHP
ini_set( 'display_errors', 0 );
date_default_timezone_set('Europe/London');
#session_start();
function make_form_var($formvar='',$type='',$name='',$id='',$value='',$size='',$maxlength='',$checked='',$src='',$rows='',$columns='',$class='',$title='',$align='',$onclick='',$onblur='') {
if ($formvar == '') { return; }
$object = '<'.$formvar.' '; # 1
if ($type != '') { $object.= 'type="'.$type.'" '; } # 2
if ($name != '') { $object.= 'name="'.$name.'" '; } # 3
if ($id != '') { $object.= 'id="'.$id.'" '; } # 4
if ($value != '') { $object.= 'value="'.$value.'" '; } # 5
if ($size != '') { $object.= 'size="'.$size.'" '; } # 6
if ($maxlength != '') { $object.= 'maxlength="'.$maxlength.'" '; } # 7
if ($checked != '') { $object.= 'checked="'.$checked.'" '; } # 8
if ($src != '') { $object.= 'src="'.$src.'" '; } # 9
if ($rows != '') { $object.= 'rows="'.$rows.'" '; } # 10
if ($columns != '') { $object.= 'cols="'.$columns.'" '; } # 11
if ($class != '') { $object.= 'class="'.$class.'" '; } # 12
if ($title != '') { $object.= 'title="'.$title.'" '; } # 13
if ($align != '') { $object.= 'align="'.$align.'" '; } # 14
if ($onclick != '') { $object.= 'onclick="'.$onclick.'" '; } # 15
if ($onblur != '') { $object.= 'onblur="'.$onblur.'" '; } # 16
if ($formvar == 'textarea') {
$object.='>'.$value.'</'.$formvar.'>';
} else {
$object.=' />';
}
return $object;
}
function valid_email($email)
{
// check an email address is valid
if (preg_match('/^([0-9a-zA-Z]+[-._+&])*[0-9a-zA-Z]+#([-0-9a-zA-Z]+[.])+[a-zA-Z]{2,6}$/', $email))
return true;
else
return false;
}
$newarray = $_POST;
if ($_SERVER['PHP_SELF'] == '/index.php' || isset($_POST['displaydonation'])) {
# place values on the session
if (isset($newarray['title1'])) {
$_SESSION['DONATION']->title1 = $newarray['title1'];
} else {
if (!isset($_SESSION['DONATION']->title1)) { $_SESSION['DONATION']->title1 = ''; }
}
if (isset($newarray['first_name'])) {
$_SESSION['DONATION']->first_name = $newarray['first_name'];
} else {
if (!isset($_SESSION['DONATION']->first_name)) { $_SESSION['DONATION']->first_name = ''; }
}
if (isset($newarray['last_name'])) {
$_SESSION['DONATION']->last_name = $newarray['last_name'];
} else {
if (!isset($_SESSION['DONATION']->last_name)) { $_SESSION['DONATION']->last_name = ''; }
}
if (isset($newarray['email'])) {
$_SESSION['DONATION']->email = $newarray['email'];
} else {
if (!isset($_SESSION['DONATION']->email)) { $_SESSION['DONATION']->email = ''; }
}
if (isset($newarray['amount'])) {
$_SESSION['DONATION']->amount = $newarray['amount'];
} else {
if (!isset($_SESSION['DONATION']->amount)) { $_SESSION['DONATION']->amount = '0.00'; }
}
if (isset($newarray['message'])) {
$_SESSION['DONATION']->message = $newarray['message'];
} else {
if (!isset($_SESSION['DONATION']->message)) { $_SESSION['DONATION']->message = ''; }
}
if (isset($newarray['giftaid'])) {
if ($newarray['giftaid'] == 'true') { $newarray['giftaid'] = 1; } else { $newarray['giftaid'] == 0; }
$_SESSION['DONATION']->giftaid = $newarray['giftaid'];
} else {
if (!isset($_SESSION['DONATION']->giftaid)) { $_SESSION['DONATION']->giftaid = '1'; }
}
$emailvalid = ''; $emailvalid = valid_email($_SESSION['DONATION']->email);
if (isset($_POST['displaydonation']) && $_SESSION['DONATION']->first_name != '' && $_SESSION['DONATION']->last_name != '' && $_SESSION['DONATION']->email != '' && $emailvalid != false && $_SESSION['DONATION']->amount != '' && $_SESSION['DONATION']->amount >= 5.00) {
# email details
$subject = "Website Donation";
$body = $body."The following donation was started on ".date('l dS F').". The user was forwarded to paypal to complete the transaction.\n\n";
$body = $body."Contact Name: ".$_SESSION['DONATION']->title." ".$_SESSION['DONATION']->first_name." ".$_SESSION['DONATION']->last_name."\n\n";
$body = $body."Email: ".$_SESSION['DONATION']->email."\n\n";
$body = $body."Amount: ".$_SESSION['DONATION']->amount."\n\n";
if ( $_SESSION['DONATION']->message != '') { $body = $body."Message: ".$_SESSION['DONATION']->message."\n\n"; }
if ( $_SESSION['DONATION']->giftaid == '1') { $body = $body."Gift aid: Yes\n\n"; }
$to = "office#lifechurch.org.uk";
$from = $_SESSION['DONATION']->email;
$headers = 'From: ' . $from . "\n";
$headers .= 'Return-Path: ' . $from . "\n";
$headers .= 'BCC: gavin.lloyd#sky.com'."\n";
$headers .= 'BCC:'."\n";
$headers .= 'MIME-Version: 1.0' ."\n";
$headers .= 'Content-Type: text/plain; charset=ISO-8859-1' ."\n";
$headers .= 'Content-Transfer-Encoding: 8bit'. "\n\n";
$mailOk=mail($to, $subject, $body, $headers);
# forward form to paypal
echo 'submitform';
} else {
echo '<div class="formlabel">Title: </div>';
echo '<div class="formobject">';
echo make_form_var('input','text','title1','title1',$_SESSION['DONATION']->title1,'5','6','','','','','paypaltextbox');
echo '</div>';
echo '<div class="formclear"></div>';
if (isset($_POST['displaydonation']) && $_SESSION['DONATION']->first_name == '') {
echo '<div class="error">Please enter your first name:</div>';
}
echo '<div class="formlabel"><span class="requiredtext">First name:* </span></div>';
echo '<div class="formobject">';
echo make_form_var('input','text','first_name','first_name',$_SESSION['DONATION']->first_name,'26','100','','','','','paypaltextbox');
echo '</div>';
echo '<div class="formclear"></div>';
if (isset($_POST['displaydonation']) && $_SESSION['DONATION']->last_name == '') {
echo '<div class="error">Please enter your last name:</div>';
}
echo '<div class="formlabel"><span class="requiredtext">Last name:* </span></div>';
echo '<div class="formobject">';
echo make_form_var('input','text','last_name','last_name',$_SESSION['DONATION']->last_name,'26','100','','','','','paypaltextbox');
echo '</div>';
echo '<div class="formclear"></div>';
if (isset($_POST['displaydonation']) && $_SESSION['DONATION']->email == '') {
echo '<div class="error">Please enter your email:</div>';
} else if (isset($_POST['displaydonation']) && $emailvalid == false) {
echo '<div class="error">Please enter a valid email address:</div>';
}
echo '<div class="formlabel"><span class="requiredtext">Email:* </span></div>';
echo '<div class="formobject">';
echo make_form_var('input','text','email','email',$_SESSION['DONATION']->email,'26','100','','','','','paypaltextbox');
echo '</div>';
echo '<div class="formclear"></div>';
if (isset($_POST['displaydonation']) && $_SESSION['DONATION']->amount == '') {
echo '<div class="error">Please enter a donation:</div>';
} else if (isset($_POST['displaydonation']) && $_SESSION['DONATION']->amount < 5.00) {
echo '<div class="error">Please enter a donation of £5.00 or more:</div>';
}
echo '<div class="formlabel"><span class="requiredtext">Donation:* </span></div>';
echo '<div class="formobject">';
echo make_form_var('input','text','amount','amount',$_SESSION['DONATION']->amount,'6','16','','','','','paypaltextboxcost','','right','','MM_changeProp(\'amount\',\'\',\'value\',cent(this.value),\'INPUT/TEXT\')');
echo ' (minimum £5.00)</div>';
echo '<div class="formclear"></div>';
echo '<div class="formlabel">Message: </div>';
echo '<div class="formobject">';
echo make_form_var('textarea','','message','message',$_SESSION['DONATION']->message,'','','','','5','','paypaltextbox');
echo '</div>';
echo '<div class="formclear"></div>';
echo '<div class="formlabel">Gift aid: </div>';
echo '<div class="formobject">';
$checked='';
if ($_SESSION['DONATION']->giftaid == 1) { $checked = 'checked'; }
echo make_form_var('input','checkbox','giftaid','giftaid','1','','',$checked,'','','','');
echo '</div>';
echo '<div class="formclear"><br /><p class="donate_small">I am a UK taxpayer. Please treat the gift I have made to Chesterfield Christian Life Church (CLC) as a Gift Aid Donation. I understand CLC will reclaim income tax at the basic rate on my donations and I must pay an amount of income tax or capital gains tax equal to the amount that will be reclaimed. IE - You are confirming that you are a UK tax payer and that you are happy for us to reclaim the tax - for every £1 you give to CLC we can reclaim 25p from the tax man - which is pretty cool. All donations qualify - large or small, regular or one-off, and whatever the method of payment. </p></div>';
}
}
Can anyone tell me what I should be looking for?
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] . ' ' . $cr_code . ' - 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.
The following flags an error if a form field is empty and also flags an error if anything other than letters are entered in the form input.
if (empty($_POST["feedtitle"])) {
$has_errors = true;
$feedtitleErr = "Enter feed title";
} elseif (preg_match('/[^a-zA-Z]/i',$_POST["feedtitle"])) {
$has_errors = false;
$feedtitleErr = "Enter text only";
} else {
$feedtitle = validate_input($_POST["feedtitle"]);
}
When created the form this works fine. When editing the form data however is the input is left empty the empty field error "Enter feed title" does not fire and if I enter anything other than letters e.g. numbers no value is passed i.e. the variable $feedtitle is blank. If I enter text however it saves.
I don't think the query is the issue.
$Query = "UPDATE ccregisterfeed SET author='$author', category='$category',
copyright='$copyright', feeddescription='$feeddescription', feedtitle='$feedtitle',
websitelink='$websitelink', imagelink='$imagelink', imagetitle='$imagetitle',
subtitle='$subtitle' WHERE id='$feedid' AND username ='$user'";
FULL SCRIPT
<?php
include "connect.php";
require "authenticate.php";
error_reporting(E_ERROR);
$message = $_GET['message'];
$user = $_SESSION['UserName'];
//declare form field and form field error variables
$authorErr = $categoryErr = $copyrightErr = $feeddescriptionErr = $feedlinkErr = $feedtitleErr = $websitelinkErr = $imagelinkErr = $imagetitleErr = $subtitleErr = "";
$author = $category = $copyright = $feeddescription = $feedlink = $feedtitle = $websitelink = $imagelink = $imagetitle = $subtitle = "";
//form field validation
function validate_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if (isset($_POST['Submit']))
{
$has_errors = false;
if (empty($_POST["author"])) {
$has_errors = true;
$authorErr = "Enter your name";
}else{
$author = validate_input($_POST["author"]);
}
if (empty($_POST["category"])) {
$has_errors = true;
$categoryErr = "Enter a category";
}else {
$category = validate_input($_POST["category"]);
}
if (empty($_POST["copyright"])) {
$has_errors = true;
$copyrightErr = "Enter copyright details";
} else {
$copyright = validate_input($_POST["copyright"]);
}
if (empty($_POST["feeddescription"])) {
$has_errors = true;
$feeddescriptionErr = "Enter feed description";
} else {
$feeddescription = validate_input($_POST["feeddescription"]);
}
if (empty($_POST["feedtitle"])) {
$has_errors = true;
$feedtitleErr = "Enter feed title";
} elseif (preg_match('/[^a-zA-Z]/i',$_POST["feedtitle"])) {
$has_errors = true;
$feedtitleErr = "Enter text only";
} else {
$feedtitle = validate_input($_POST["feedtitle"]);
}
if (empty($_POST["websitelink"])) {
$has_errors = true;
$websitelinkErr = "Enter link to website";
} else {
$websitelink = validate_input($_POST["websitelink"]);
}
if (empty($_POST["imagelink"])) {
$has_errors = true;
$imagelinkErr = "Enter link to image";
} else {
$imagelink = validate_input($_POST["imagelink"]);
}
if (empty($_POST["imagetitle"])) {
$has_errors = true;
$imagetitleErr = "Enter image name";
} else {
$imagetitle = validate_input($_POST["imagetitle"]);
}
if (empty($_POST["subtitle"])) {
$has_errors = true;
$subtitleErr = "Enter feed subtitle";
} else {
$subtitle = validate_input($_POST["subtitle"]);
}
// var_dump ($date);
// var_dump ($feedlink);
// var_dump ($feeddescription);
//write edited data into tables matching logged in user with their data
$feedid = mysql_real_escape_string($_POST['feedid']);
$date = date("Y-m-d H:i:s");
$feeddescription = str_replace("_", "", $feeddescription);
$feeddescription = str_replace("-", "", $feeddescription);
$feeddescription = str_replace("!", "", $feeddescription);
$feeddescription = str_replace("#", "", $feeddescription);
$feeddescription = str_replace("'", "", $feeddescription);
$Query = "UPDATE ccregisterfeed SET author='$author', category='$category', copyright='$copyright', feeddescription='$feeddescription', feedtitle='$feedtitle', websitelink='$websitelink', imagelink='$imagelink', imagetitle='$imagetitle', subtitle='$subtitle' WHERE id='$feedid' AND username ='$user'";
if($sql = mysql_query($Query)) {
header("location: rss.php");
// header("location: feededit.php");
} else {
die("Query was: $Query. Error: ".mysql_error());
}
}
//show logged in user their updated data
$user = $_SESSION['UserName'];
$result = mysql_query("SELECT * FROM ccregisterfeed WHERE username = '$user'") or die(mysql_error());
while($row = mysql_fetch_array($result)){
$id=$row['id'];
$author = $row['author'];
$category = $row['category'];
$copyright = $row['copyright'];
$feeddescription = $row['feeddescription'];
$feedtitle = $row['feedtitle'];
$websitelink = $row['websitelink'];
$imagelink = $row['imagelink'];
$imagetitle = $row['imagetitle'];
$subtitle = $row['subtitle'];
}
//delete form and image data when users clicks delete button
if (isset($_POST['Delete'])){
$deleteuser = $_POST['Delete'];
mysql_query("DELETE FROM ccregisterfeed WHERE id = '$deleteuser'");
mysql_query("ALTER TABLE ccregisterfeed AUTO_INCREMENT = 1");
$message = 'Feed Deleted';
header("Location: feededit.php?&message=".urlencode($message));
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<form action="feededit.php" method="post" enctype="multipart/form-data" name="edit" id="editfeed">
<fieldset>
<div class="legendcreate">Feed Edit</div>
<div class="feedcontainer">
<div class="feedcontainerinner">
<div><label class="labelshow">Author</label><input id="author" class="insetfeed" name="author" type="text" placeholder="Author" value="<?PHP print $author ; ?>"/><p class="errorinput"><?php echo $authorErr;?></p></div>
<?php if(isset($_GET['message']) && !empty($message)): ?>
<div class="messagebox">
<?php echo $message ?>
</div>
<?php endif; ?>
<div><label class="labelshow">Category</label><input id="category" class="insetfeed" name="category" type="text" placeholder="Category" value="<?PHP print $category; ?>"/><p class="errorinput"><?php echo $categoryErr;?></p></div>
<div><label class="labelshow">Copyright</label><input id="copyright" class="insetfeed" name="copyright" type="text" placeholder="Copyright" value="<?PHP print $copyright; ?>"/><p class="errorinput"><?php echo $copyrightErr;?></p></div>
<div><label class="labelshow">Feed Title</label><input id="feedtitle" class="insetfeed" name="feedtitle" type="text" placeholder="Feed Title" value="<?PHP print $feedtitle; ?>"/><p class="errorinput"><?php echo $feedtitleErr;?></p></div>
<div><label class="labelshow">Website Link</label><input id="websitelink" class="insetfeed" name="websitelink" type="text" placeholder="Website Link" value="<?PHP print $websitelink; ?>"/><p class="errorinput"><?php echo $websitelinkErr;?></p></div>
<div><label class="labelshow">Image Link</label><input id="imagelink" class="insetfeed" name="imagelink" type="text" placeholder="Image Link" value="<?PHP print $imagelink; ?>"/><p class="errorinput"><?php echo $imagelinkErr;?></p></div>
<div><label class="labelshow">Image Title</label><input id="imagetitle" class="insetfeed" name="imagetitle" type="text" placeholder="Image Title" value="<?PHP print $imagetitle; ?>"/><p class="errorinput"><?php echo $imagetitleErr;?></p></div>
<div><label class="labelshow">Subtitle</label><input id="subtitle" class="insetfeed" name="subtitle" type="text" placeholder="Subtitle" value="<?PHP print $subtitle; ?>"/><p class="errorinput"><?php echo $subtitleErr;?></p></div>
<div><textarea id="description" name="feeddescription" class="textareadescription" placeholder="Enter feed description"><?php
$out = htmlspecialchars_decode($feeddescription);
$out = str_replace( '\n', '<br />', $out );
echo $out;
?></textarea>
<div class="submit"><input name="Submit" type="submit" class="submitbtn" value="Save"/></div>
<div class="delete"><input name="deletebtn" type="submit" class="resetbtn" value="Delete"/></div>
<input type="hidden" name="feedid" value="<?phpecho $id;?>"/>
</div>
</div>
</div>
</form>
</fieldset>
I am trying to:
save the data entered in a form to a CSV file, which gets attached as a CSV file and sent via email and
allow users to upload their own file, which also gets sent via email
I've been able to generate the CSV file and save the data in it, and email the file uploaded in part 2,
However, I'm unable to send the CSV file created in part 2 as attachment.
I am using PHPMailer.
Any help is greatly appreciated.
Here is my formprocess file.
<?PHP
*/
require_once("class.phpmailer.php");
/*
Interface to Captcha handler
*/
class FG_CaptchaHandler
{
function Validate() { return false;}
function GetError(){ return '';}
}
class FGContactForm
{
var $receipients;
var $errors;
var $error_message;
var $name;
var $email;
var $message;
var $from_address;
var $form_random_key;
var $conditional_field;
var $arr_conditional_receipients;
var $fileupload_fields;
var $captcha_handler;
var $mailer;
function FGContactForm()
{
$this->receipients = array();
$this->errors = array();
$this->form_random_key = 'HTgsjhartag';
$this->conditional_field='';
$this->arr_conditional_receipients=array();
$this->fileupload_fields=array();
$this->mailer = new PHPMailer();
$this->mailer->CharSet = 'utf-8';
}
function EnableCaptcha($captcha_handler)
{
$this->captcha_handler = $captcha_handler;
session_start();
}
function AddRecipient($email,$name="")
{
$this->mailer->AddAddress($email,$name);
}
function SetFromAddress($from)
{
$this->from_address = $from;
}
function SetFormRandomKey($key)
{
$this->form_random_key = $key;
}
function GetSpamTrapInputName()
{
return 'sp'.md5('KHGdnbvsgst'.$this->GetKey());
}
function SafeDisplay($value_name)
{
if(empty($_POST[$value_name]))
{
return'';
}
return htmlentities($_POST[$value_name]);
}
function GetFormIDInputName()
{
$rand = md5('TygshRt'.$this->GetKey());
$rand = substr($rand,0,20);
return 'id'.$rand;
}
function GetFormIDInputValue()
{
return md5('jhgahTsajhg'.$this->GetKey());
}
function SetConditionalField($field)
{
$this->conditional_field = $field;
}
function AddConditionalReceipent($value,$email)
{
$this->arr_conditional_receipients[$value] = $email;
}
function AddFileUploadField($file_field_name,$accepted_types,$max_size)
{
$this->fileupload_fields[] =
array("name"=>$file_field_name,
"file_types"=>$accepted_types,
"maxsize"=>$max_size);
}
function ProcessForm()
{
if(!isset($_POST['submitted']))
{
return false;
}
if(!$this->Validate())
{
$this->error_message = implode('<br/>',$this->errors);
return false;
}
$this->CollectData();
$ret = $this->SendFormSubmission();
return $ret;
}
function RedirectToURL($url)
{
header("Location: $url");
exit;
}
function GetErrorMessage()
{
return $this->error_message;
}
function GetSelfScript()
{
return htmlentities($_SERVER['PHP_SELF']);
}
function GetName()
{
return $this->name;
}
function GetEmail()
{
return $this->email;
}
function GetMessage()
{
return htmlentities($this->message,ENT_QUOTES,"UTF-8");
}
/*-------- Private (Internal) Functions -------- */
function SendFormSubmission()
{
$this->CollectConditionalReceipients();
$this->mailer->CharSet = 'utf-8';
$this->mailer->Subject = "Contact form submission from $this->name";
$this->mailer->From = $this->GetFromAddress();
$this->mailer->FromName = $this->name;
$this->mailer->AddReplyTo($this->email);
$message = $this->ComposeFormtoEmail();
$textMsg = trim(strip_tags(preg_replace('/<(head|title|style|script)[^>]*>.*?<\/\\1>/s','',$message)));
$this->mailer->AltBody = #html_entity_decode($textMsg,ENT_QUOTES,"UTF-8");
$this->mailer->MsgHTML($message);
$this->AttachFiles();
if(!$this->mailer->Send())
{
$this->add_error("Failed sending email!");
return false;
}
return true;
}
function CollectConditionalReceipients()
{
if(count($this->arr_conditional_receipients)>0 &&
!empty($this->conditional_field) &&
!empty($_POST[$this->conditional_field]))
{
foreach($this->arr_conditional_receipients as $condn => $rec)
{
if(strcasecmp($condn,$_POST[$this->conditional_field])==0 &&
!empty($rec))
{
$this->AddRecipient($rec);
}
}
}
}
/*
Internal variables, that you donot want to appear in the email
Add those variables in this array.
*/
function IsInternalVariable($varname)
{
$arr_interanl_vars = array('scaptcha',
'submitted',
$this->GetSpamTrapInputName(),
$this->GetFormIDInputName()
);
if(in_array($varname,$arr_interanl_vars))
{
return true;
}
return false;
}
function FormSubmissionToMail()
{
$ret_str='';
foreach($_POST as $key=>$value)
{
if(!$this->IsInternalVariable($key))
{
$value = htmlentities($value,ENT_QUOTES,"UTF-8");
$value = nl2br($value);
$key = ucfirst($key);
$ret_str .= "<div class='label'>$key :</div><div class='value'>$value </div>\n";
}
}
foreach($this->fileupload_fields as $upload_field)
{
$field_name = $upload_field["name"];
if(!$this->IsFileUploaded($field_name))
{
continue;
}
$filename = basename($_FILES[$field_name]['name']);
$ret_str .= "<div class='label'>File upload '$field_name' :</div><div class='value'>$filename </div>\n";
}
return $ret_str;
}
function ExtraInfoToMail()
{
$ret_str='';
$ip = $_SERVER['REMOTE_ADDR'];
$ret_str = "<div class='label'>IP address of the submitter:</div><div class='value'>$ip</div>\n";
return $ret_str;
}
function GetMailStyle()
{
$retstr = "\n<style>".
"body,.label,.value { font-family:Arial,Verdana; } ".
".label {font-weight:bold; margin-top:5px; font-size:1em; color:#333;} ".
".value {margin-bottom:15px;font-size:0.8em;padding-left:5px;} ".
"</style>\n";
return $retstr;
}
function GetHTMLHeaderPart()
{
$retstr = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">'."\n".
'<html><head><title></title>'.
'<meta http-equiv=Content-Type content="text/html; charset=utf-8">';
$retstr .= $this->GetMailStyle();
$retstr .= '</head><body>';
return $retstr;
}
function GetHTMLFooterPart()
{
$retstr ='</body></html>';
return $retstr ;
}
function ComposeFormtoEmail()
{
$header = $this->GetHTMLHeaderPart();
$formsubmission = $this->FormSubmissionToMail();
$extra_info = $this->ExtraInfoToMail();
$footer = $this->GetHTMLFooterPart();
$message = $header."Submission from 'contact us' form:<p>$formsubmission</p><hr/>$extra_info".$footer;
return $message;
}
function AttachFiles()
{
foreach($this->fileupload_fields as $upld_field)
{
$field_name = $upld_field["name"];
if(!$this->IsFileUploaded($field_name))
{
continue;
}
$filename =basename($_FILES[$field_name]['name']);
$this->mailer->AddAttachment($_FILES[$field_name]["tmp_name"],$filename);
}
}
function GetFromAddress()
{
if(!empty($this->from_address))
{
return $this->from_address;
}
$host = $_SERVER['SERVER_NAME'];
$from ="nobody#$host";
return $from;
}
function Validate()
{
$ret = true;
//security validations
if(empty($_POST[$this->GetFormIDInputName()]) ||
$_POST[$this->GetFormIDInputName()] != $this->GetFormIDInputValue() )
{
//The proper error is not given intentionally
$this->add_error("Automated submission prevention: case 1 failed");
$ret = false;
}
//This is a hidden input field. Humans won't fill this field.
if(!empty($_POST[$this->GetSpamTrapInputName()]) )
{
//The proper error is not given intentionally
$this->add_error("Automated submission prevention: case 2 failed");
$ret = false;
}
//name validations
if(empty($_POST['name']))
{
$this->add_error("Please provide your name");
$ret = false;
}
else
if(strlen($_POST['name'])>50)
{
$this->add_error("Name is too big!");
$ret = false;
}
//email validations
if(empty($_POST['email']))
{
$this->add_error("Please provide your email address");
$ret = false;
}
else
if(strlen($_POST['email'])>50)
{
$this->add_error("Email address is too big!");
$ret = false;
}
else
if(!$this->validate_email($_POST['email']))
{
$this->add_error("Please provide a valid email address");
$ret = false;
}
//message validaions
if(strlen($_POST['message'])>2048)
{
$this->add_error("Message is too big!");
$ret = false;
}
//captcha validaions
if(isset($this->captcha_handler))
{
if(!$this->captcha_handler->Validate())
{
$this->add_error($this->captcha_handler->GetError());
$ret = false;
}
}
//file upload validations
if(!empty($this->fileupload_fields))
{
if(!$this->ValidateFileUploads())
{
$ret = false;
}
}
return $ret;
}
function ValidateFileType($field_name,$valid_filetypes)
{
$ret=true;
$info = pathinfo($_FILES[$field_name]['name']);
$extn = $info['extension'];
$extn = strtolower($extn);
$arr_valid_filetypes= explode(',',$valid_filetypes);
if(!in_array($extn,$arr_valid_filetypes))
{
$this->add_error("Valid file types are: $valid_filetypes");
$ret=false;
}
return $ret;
}
function ValidateFileSize($field_name,$max_size)
{
$size_of_uploaded_file =
$_FILES[$field_name]["size"]/1024;//size in KBs
if($size_of_uploaded_file > $max_size)
{
$this->add_error("The file is too big. File size should be less than $max_size KB");
return false;
}
return true;
}
function IsFileUploaded($field_name)
{
if(empty($_FILES[$field_name]['name']))
{
return false;
}
if(!is_uploaded_file($_FILES[$field_name]['tmp_name']))
{
return false;
}
return true;
}
function ValidateFileUploads()
{
$ret=true;
foreach($this->fileupload_fields as $upld_field)
{
$field_name = $upld_field["name"];
$valid_filetypes = $upld_field["file_types"];
if(!$this->IsFileUploaded($field_name))
{
continue;
}
if($_FILES[$field_name]["error"] != 0)
{
$this->add_error("Error in file upload; Error code:".$_FILES[$field_name]["error"]);
$ret=false;
}
if(!empty($valid_filetypes) &&
!$this->ValidateFileType($field_name,$valid_filetypes))
{
$ret=false;
}
if(!empty($upld_field["maxsize"]) &&
$upld_field["maxsize"]>0)
{
if(!$this->ValidateFileSize($field_name,$upld_field["maxsize"]))
{
$ret=false;
}
}
}
return $ret;
}
function StripSlashes($str)
{
if(get_magic_quotes_gpc())
{
$str = stripslashes($str);
}
return $str;
}
/*
Sanitize() function removes any potential threat from the
data submitted. Prevents email injections or any other hacker attempts.
if $remove_nl is true, newline chracters are removed from the input.
*/
function Sanitize($str,$remove_nl=true)
{
$str = $this->StripSlashes($str);
if($remove_nl)
{
$injections = array('/(\n+)/i',
'/(\r+)/i',
'/(\t+)/i',
'/(%0A+)/i',
'/(%0D+)/i',
'/(%08+)/i',
'/(%09+)/i'
);
$str = preg_replace($injections,'',$str);
}
return $str;
}
/*Collects clean data from the $_POST array and keeps in internal variables.*/
function CollectData()
{
$this->name = $this->Sanitize($_POST['name']);
$this->email = $this->Sanitize($_POST['email']);
/*newline is OK in the message.*/
$this->message = $this->StripSlashes($_POST['message']);
}
function add_error($error)
{
array_push($this->errors,$error);
}
function validate_email($email)
{
return eregi("^[_\.0-9a-zA-Z-]+#([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z]{2,6}$", $email);
}
function GetKey()
{
return $this->form_random_key.$_SERVER['SERVER_NAME'].$_SERVER['REMOTE_ADDR'];
}
}
?>
and my form
<?PHP
require_once("./include/formprocess.php");
require_once("./include/captcha-creator.php");
$formproc = new FGContactForm();
$captcha = new FGCaptchaCreator('scaptcha');
$formproc->EnableCaptcha($captcha);
//1. Add your email address here.
//You can add more than one receipients.
$formproc->AddRecipient('email#site.com'); //<<---Put your email address here
//2. For better security.
// and put it here
$formproc->SetFormRandomKey('XsHVufPpgD9Epwl');
$formproc->AddFileUploadField('photo','jpg,gif,png',2024);
$formproc->AddFileUploadField('resume','doc,docx,pdf,txt,xls,xlsx,csv',2024);
if(isset($_POST['submitted']))
// Save as CSV
//The Attachment
$cr = "\n";
$data .= "Name" . ',' . "Email Address" .$cr;
$data .= "$name" . ',' . "email" .$cr;
$fp = fopen('data.csv','a');
fwrite($fp,$data);
fclose($fp);
$attachments[] = Array(
'data' => $data,
'name' => 'data.csv',
'type' => 'application/vnd.ms-excel'
);
//Generate a boundary string
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
//Add the headers for a file attachment
$headers = "MIME-Version: 1.0\n" .
"From: {$from}\n" .
"Content-Type: multipart/mixed;\n" .
" boundary=\"{$mime_boundary}\"";
//Add a multipart boundary above the plain message
$message = "This is a multi-part message in MIME format.\n\n" .
"--{$mime_boundary}\n" .
"Content-Type: text/html; charset=\"iso-8859-1\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" .
$text . "\n\n";
// END of CSV formatting
{
if($formproc->ProcessForm())
{
$formproc->RedirectToURL("thank-you.php");
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
<head>
<meta http-equiv='Content-Type' content='text/html; charset=utf-8'/>
<title>Contact us</title>
<link rel="STYLESHEET" type="text/css" href="contact.css" />
<script type='text/javascript' src='scripts/gen_validatorv31.js'></script>
<script type='text/javascript' src='scripts/fg_captcha_validator.js'></script>
</head>
<body>
<!-- Form Code Start -->
<form id='contactus' action='<?php echo $formproc->GetSelfScript(); ?>' method='post' enctype="multipart/form-data" accept-charset='UTF-8'>
<fieldset >
<legend>Contact us</legend>
<input type='hidden' name='submitted' id='submitted' value='1'/>
<input type='hidden' name='<?php echo $formproc->GetFormIDInputName(); ?>' value='<?php echo $formproc->GetFormIDInputValue(); ?>'/>
<input type='text' class='spmhidip' name='<?php echo $formproc->GetSpamTrapInputName(); ?>' />
<div class='short_explanation'>* required fields</div>
<div><span class='error'><?php echo $formproc->GetErrorMessage(); ?></span></div>
<div class='container'>
<label for='name' >Your Full Name*: </label><br/>
<input type='text' name='name' id='name' value='<?php echo $formproc->SafeDisplay('name') ?>' maxlength="50" /><br/>
<span id='contactus_name_errorloc' class='error'></span>
</div>
<div class='container'>
<label for='email' >Email Address*:</label><br/>
<input type='text' name='email' id='email' value='<?php echo $formproc->SafeDisplay('email') ?>' maxlength="50" /><br/>
<span id='contactus_email_errorloc' class='error'></span>
</div>
<div class='container'>
<label for='message' >Message:</label><br/>
<span id='contactus_message_errorloc' class='error'></span>
<textarea rows="10" cols="50" name='message' id='message'><?php echo $formproc->SafeDisplay('message') ?></textarea>
</div>
<div class='container'>
<label for='photo' >Your photo:</label><br/>
<input type="file" name='photo' id='photo' /><br/>
<span id='contactus_photo_errorloc' class='error'></span>
</div>
<div class='container'>
<label for='photo' >Resume:</label><br/>
<input type="file" name='resume' id='resume' /><br/>
<span id='contactus_resume_errorloc' class='error'></span>
</div>
<div class='container'>
<div><img alt='Captcha image' src='show-captcha.php?rand=1' id='scaptcha_img' /></div>
<label for='scaptcha' >Enter the code above here:</label>
<input type='text' name='scaptcha' id='scaptcha' maxlength="10" /><br/>
<span id='contactus_scaptcha_errorloc' class='error'></span>
<div class='short_explanation'>Can't read the image?
<a href='javascript: refresh_captcha_img();'>Click here to refresh</a>.</div>
</div>
<div class='container'>
<input type='submit' name='Submit' value='Submit' />
</div>
</fieldset>
</form>
<!-- client-side Form Validations:
Uses the excellent form validation script from JavaScript-coder.com-->
</body>
</html>
How to attach and send the data.csv file that has been generated by the from?