I am trying to add recaptcha into my custom PHP form and am confused about how to do so. Recaptcha requires adding recaptchalib.php into the form, but if I add verify.php then my form will not process, as I am using my PHP file to process my form.
<form method="POST" action="process.php" id="form-ok">
The documentation is a bit confusing. My question is, what do I need to do to process two actions?
Any idea how can I get this working?
Process.php
<?php
$redirectTo = '/thankyou.html';
$subject = 'New message from site'; // Email SUBJECT field
$receive = array(
'example#example.com'
);
if($_POST['email_check'] == '') {
if (isset($_POST['first_name'])){
$message = '<table width="100%" border="0" cellspacing="0" cellpadding="8" style="border:1px solid #f3f3f3">
<tr>
<td colspan="3" height="30" style="font-size:20px"><strong>' . $subject . '</strong></td>
</tr>
<tr>
<td width="100" bgcolor="#f3f3f3"><strong>First Name: </strong></td>
<td width="14" height="30" bgcolor="#f3f3f3"> </td>
<td width="305" bgcolor="#f3f3f3">' . $_POST ['first_name'] . '</td>
</tr>
<tr>
<td><strong>Last Name: </strong></td>
<td width="14" height="30"> </td>
<td>' . $_POST ['last_name'] . '</td>
</tr>
<tr>
<td bgcolor="#f3f3f3"><strong>Email: </strong></td>
<td bgcolor="#f3f3f3" width="14" height="30"> </td>
<td bgcolor="#f3f3f3">' . $_POST ['email'] . '</td>
</tr>
<tr>
<td><strong>Phone Number: </strong></td>
<td width="14" height="30"> </td>
<td>' . $_POST ['phone'] . '</td>
</tr>
<tr>
<td bgcolor="#f3f3f3"><strong>Check: </strong></td>
<td bgcolor="#f3f3f3" width="14" height="30"> </td>
<td bgcolor="#f3f3f3">';
foreach($_POST['role'] as $value)
{
$message.=$value.'<br>';
}
$message.='</td>
</tr>
<tr>
<td><strong>Message: </strong></td>
<td width="14" height="30"> </td>
<td>' . $_POST ['message'] . '</td>
</tr>
<tr>
<td><strong>Referer:</strong></td>
<td width="14" height="30"> </td>
<td>' . $_SERVER ['HTTP_REFERER'] . '</td>
</tr>
<tr>
</table>';
for ($i = 0; $i < count($receive); $i++){
$to = $receive[$i];
$headers = 'MIME-Version: 1.0' . "\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\n";
$headers .= 'From: ' . $_POST['email'] . "\n" . 'Reply-To: ' . $_POST['email'] . "\n";
mail($to, $subject, $message,$headers);
}
header('Location: '.$redirectTo);
}
}
else{
header('Location:'.$_SERVER['HTTP_REFERER']); die();
}
?>
Add your recaptchalib.php in your dir.
YOUR PROCESS.PHP:
require_once "../recaptchalib.php"; // where you store recaptchalib.php
$secret = "6Le2g_sSxxxxxxxxxxxxxxxxxxxxxxxx"; //your secret key
$resp = null;
$error = null;
$reCaptcha = new ReCaptcha($secret);
if ($_POST["g-recaptcha-response"]) {
$resp = $reCaptcha->verifyResponse($_SERVER["REMOTE_ADDR"],
$_POST["g-recaptcha-response"]);
}
if (isset($_POST['cmdlogin'])){
if ($resp != null && $resp->success) {
echo "<script>alert('Success Verifying Recaptcha!');</script>";
echo "<meta http-equiv='refresh' content='0; url=login.php'>";
exit();
}
<form method="post" action="process.php">
.....other codes---
<div class="g-recaptcha" data-
sitekey="6Le2g_sSxxxxxxxxxxxxxxxxxxxxxxxx">
</div>
.....other codes---
</form>
Full Tutorial, check here:
https://github.com/google/ReCAPTCHA/tree/master/php
Client Side (How to make the CAPTCHA image show up)
<form method="post" action="process.php">
<?php
require_once('recaptchalib.php');
$publickey = "YOUR_PUBLIC_KEY"; // you got this from the signup page
echo recaptcha_get_html($publickey);
?>
<input type="submit" />
</form><br>
<!-- more of your HTML content -->
Server Side
The following code should be placed at the top of the process.php file:
<?php
require_once('recaptchalib.php');
$privatekey = "YOUR_PRIVATE_KEY";
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
if (!$resp->is_valid) {
// What happens when the CAPTCHA was entered incorrectly
die ("The reCAPTCHA wasn't entered correctly. Go back and try it again." .
"(reCAPTCHA said: " . $resp->error . ")");
} else {
// Your code here to handle a successful verification
}
?>
Related
I trying to make contact person book from PHP,
this website for my School, I'm a teacher in junior high school
but I can't make PHP code / Sorry
Index.php
<?php
if(!empty($errorMessage))
{
echo("<p>There was an error with your form:</p>\n");
echo("<ul>" . $errorMessage . "</ul>\n");
}
?>
<form action="file.php" method="post">
<p>
Name<br>
<input type="text" name="aa" maxlength="50" />
</p>
<p>
Contact <br>
<input type="text" name="ab" maxlength="50" />
</p>
<p>
Books<br>
<input type="text" name="ac" maxlength="50" />
</p>
<input type="submit" name="formSubmit" value="Submit" />
</form>
here.html
<head>
<title>Thank you!</title>
</head>
<body>
Data Telah di Input.<br>
CEk Disini <a href="data.html" >Data</a>
</body>
file.php
<?php
if($_POST['formSubmit'] == "Submit")
{
$errorMessage = "";
if(empty($_POST['aa']))
{
$errorMessage .= "<li>You forgot to enter a name</li>";
}
if(empty($_POST['ab']))
{
$errorMessage .= "<li>You forgot to enter a contact</li>";
}
if(empty($_POST['ac']))
{
$errorMessage .= "<li>You forgot to enter a book</li>";
}
$varaa = $_POST['aa'];
$varab = $_POST['ab'];
$varac = $_POST['ac'];
if(empty($errorMessage))
{
$fs = fopen("data.html","ab");
echo "<table > <tr><th>No</th> <th>Name</th> <th>Contact</th> <th>Books</th></tr>";
fwrite($fs,"
<tr>
<td> ".$varaa. "</td>
<td>" .$varab. "</td>
<td>" .$varac. "</td>
</tr>");
echo "</table >";
fclose($fs);
header("Location: here.html");
exit;
}
}
?>
then, why I got output like
<tr>
<td> Andreas</td>
<td>64898722</td>
<td>Test Book1</td>
</tr>
<tr>
<td> Yuyun</td>
<td>64898444</td>
<td>Book4</td>
</tr>
I trying to make output like this, but why I get alawys fails I don't know how to make other php, sory.
I need output table, and add number in first table.
<table>
<tr><th>No</th> <th>Name</th> <th>Contact</th> <th>Books</th></tr>
<tr>
<td>1</td>
<td> Andreas</td>
<td>64898722</td>
<td>Test Book1</td>
</tr>
<tr>
<td>2</td>
<td> Yuyun</td>
<td>64898444</td>
<td>Book4</td>
</tr>
</table>
remove echo for table and use fwrite
if(empty($errorMessage))
{
$fs = fopen("data.html","w");
fwrite($fs, "<table > <tr><th>No</th> <th>Name</th> <th>Contact</th> <th>Books</th></tr>");
fwrite($fs,"
<tr>
<td> ".$varaa. "</td>
<td>" .$varab. "</td>
<td>" .$varac. "</td>
</tr>");
fwrite($fs, "</table >");
fclose($fs);
header("Location: here.html");
exit;
}
I am trying to send a couple of variables via HTML form to another PHP page,
I am no expert in PHP but know enough to get me by most days,
and have had this working with no issues in other situations,
But alas PHP is just not my thing so I am here to ask the Gurus of the coding world for a pearl of wisdom,
Ok so let me break it down for you,
I have a PHP IPN (PayPal) page that is executed when a customer makes a purchase, the original code just checks for successful sale and then sends out some email to myself and the user accordingly,
I also have a licensing script that auto-generates a license,
I use a HTML form within the page so that when the sale is marked as successful a license is generated and sent to the user at the same time the emails are sent,
All pretty basic stuff, and have had this working in 3 other scripts with no problems, but for some reason i just cant get my head around it this time, and cant seem to get this to work,
I contacted the author of my store script to make sure i was using the correct variables in the form, he said that the variables needed are :
$usr->username
$usr->email
$crow->title
Here is the IPN page :
<?php
define("_VALID_PHP", true);
define("_PIPN", true);
ini_set('log_errors', true);
ini_set('error_log', dirname(__file__) . '/ipn_errors.log');
if (isset($_POST['payment_status'])) {
require_once ("../../init.php");
include (BASEPATH . 'lib/class_pp.php');
$demo = getValue("demo", Content::gTable, "name = 'paypal'");
$listener = new IpnListener();
$listener->use_live = $demo;
$listener->use_ssl = false;
$listener->use_curl = true;
try {
$listener->requirePostMethod();
$ppver = $listener->processIpn();
}
catch (exception $e) {
error_log($e->getMessage());
exit(0);
}
$payment_status = $_POST['payment_status'];
$receiver_email = $_POST['receiver_email'];
$payer_email = $_POST['payer_email'];
$payer_status = $_POST['payer_status'];
$mc_currency = $_POST['mc_currency'];
$mc_fee = isset($_POST['mc_fee']) ? floatval($_POST['mc_fee']) : 0.00;
list($user_id, $sesid) = explode('_', $_POST['custom']);
$mc_gross = $_POST['mc_gross'];
$txn_id = $_POST['txn_id'];
$getxn_id = $core->verifyTxnId($txn_id);
$cartrow = $content->getCartContent($sesid);
$totalrow = Content::getCart($sesid);
$v1 = compareFloatNumbers($mc_gross, $totalrow->totalprice, "=");
$items = array();
$pp_email = getValue("extra", Content::gTable, "name = 'paypal'");
if ($ppver) {
if ($_POST['payment_status'] == 'Completed') {
if ($receiver_email == $pp_email && $v1 == true && $getxn_id == true) {
if ($cartrow) {
foreach ($cartrow as $crow) {
$data = array(
'txn_id' => sanitize($txn_id),
'pid' => $crow->pid,
'uid' => intval($user_id),
'downloads' => 0,
'file_date' => time(),
'ip' => sanitize($_SERVER['REMOTE_ADDR']),
'created' => "NOW()",
'payer_email' => sanitize($payer_email),
'payer_status' => sanitize($payer_status),
'item_qty' => $crow->total,
'price' => $crow->total * $crow->price,
'coupon' => $totalrow->coupon,
'tax' => $totalrow->totaltax,
'mc_fee' => $mc_fee,
'currency' => sanitize($mc_currency),
'pp' => "PayPal",
'status' => 1,
'active' => 1);
$items[$crow->price] = $crow->title;
$db->insert(Products::tTable, $data);
}
unset($crow);
$xdata = array(
'invid' => date('Ymd').$db->insertid(),
'user_id' => intval($user_id),
'items' => serialize($items),
'coupon' => $totalrow->coupon,
'originalprice' => $totalrow->originalprice,
'tax' => $totalrow->tax,
'totaltax' => $totalrow->totaltax,
'total' => $totalrow->total,
'totalprice' => $totalrow->totalprice,
'currency' => sanitize($_POST['currency_code']),
'created' => "NOW()",
);
$db->insert(Content::inTable, $xdata); }
/* == Notify Administrator == */
require_once (BASEPATH . "lib/class_mailer.php");
$row2 = Core::getRowById(Content::eTable, 5);
$usr = Core::getRowById(Users::uTable, $user_id);
$body = str_replace(array(
'[USERNAME]',
'[STATUS]',
'[PRODUCT]',
'[TOTAL]',
'[PP]',
'[IP]'), array(
$usr->username,
"Completed",
$crow->title,
$totalrow->totalprice,
"PayPal",
$_SERVER['REMOTE_ADDR']), $row2->body);
$newbody = cleanOut($body);
$mailer = Mailer::sendMail();
$message = Swift_Message::newInstance()
->setSubject($row2->subject)
->setTo(array($core->site_email => $core->site_name))
->setFrom(array($core->site_email => $core->site_name))
->setBody($newbody, 'text/html');
$mailer->send($message);
/* == Notify User == */
$row3 = Core::getRowById(Content::eTable, 8);
$val = '
<table border="0" cellpadding="4" cellspacing="2">';
$val .= '
<thead>
<tr>
<td width="20"><strong>#</strong></td>
<td class="header">' . Lang::$word->PRD_NAME . '</td>
<td class="header">' . Lang::$word->PRD_PRICE . '</td>
<td class="header">' . Lang::$word->TXN_QTY . '</td>
<td class="header">' . Lang::$word->CKO_TPRICE . '</td>
</tr>
</thead>
<tbody>
';
$i = 0;
foreach ($cartrow as $ccrow) {
$i++;
$val .= '
<tr>
<td style="border-bottom-width:1px; border-bottom-color:#bbb; border-bottom-style:dashed">' . $i . '.</td>
<td style="border-bottom-width:1px; border-bottom-color:#bbb; border-bottom-style:dashed">' . sanitize($ccrow->title, 30, false) .
'</td>
<td style="border-bottom-width:1px; border-bottom-color:#bbb; border-bottom-style:dashed">' . $core->formatMoney($ccrow->price) .
'</td>
<td align="center" style="border-bottom-width:1px; border-bottom-color:#bbb; border-bottom-style:dashed">' . $ccrow->total . '</td>
<td align="right" style="border-bottom-width:1px; border-bottom-color:#bbb; border-bottom-style:dashed">' . $core->formatMoney($ccrow-
>total * $ccrow->price) . '</td>
</tr>
';
}
unset($ccrow);
$val .= '
<tr>
<td colspan="4" align="right" valign="top" style="border-bottom-width:1px; border-bottom-color:#bbb; border-bottom-
style:dashed"><strong>';
$val .= Lang::$word->CKO_SUBT . ':<br />';
$val .= Lang::$word->CKO_DISC . ':<br />';
$val .= Lang::$word->VAT . ':<br />
</strong></td>
<td align="right" valign="top" style="border-bottom-width:1px; border-bottom-color:#bbb; border-bottom-style:dashed"><strong>';
$val .= $core->formatMoney($totalrow->originalprice) . '<br />';
$val .= '- ' . $core->formatMoney($totalrow->coupon) . '<br />';
$val .= '+ ' . $core->formatMoney($totalrow->total * $totalrow->tax) . '<br />
</strong>';
$val .= ' </td>
</tr>
<tr>
<td colspan="4" align="right" valign="top"><strong style="color:#F00">' . Lang::$word->CKO_GTOTAL . ':</strong></td>
<td align="right" valign="top"><strong style="color:#F00">' . $core->formatMoney($totalrow->tax * $totalrow->total + $totalrow->total)
. '</strong></td>
</tr>
</tbody>
</table>';
$body3 = str_replace(array(
'[USERNAME]',
'[ITEMS]',
'[SITE_NAME]',
'[URL]'), array(
$usr->username,
$val,
$core->site_name,
SITEURL), $row3->body);
$newbody2 = cleanOut($body3);
$mailer2 = Mailer::sendMail();
$message2 = Swift_Message::newInstance()
->setSubject($row3->subject)
->setTo(array($usr->email => $usr->username))
->setFrom(array($core->site_email => $core->site_name))
->setBody($newbody2, 'text/html');
$mailer2->send($message2);
$db->delete(Content::crTable, "user_id='" . $sesid . "'");
$db->delete(Content::exTable, "user_id='" . $sesid . "'");
$db->delete(Products::rTable, "user_id='" . $sesid . "'");
?>
<!doctype html>
<html>
<head></head>
<body onload="document.createElement('form').submit.call(document.getElementById('Form'))">
<form id='Form' name='form' action='http://www.****************.php' method='post'>
<input type='hidden' name='name' value='<?php echo $_POST['usr->username'];?>'>
<input type='hidden' name='email' value='<?php echo $_POST['usr->email'];?>'>
<input type='hidden' name='original_url' value='http://www.****************ipn.php'>
<input type='hidden' name='projname' value='<?php echo $_POST['crow->title'];?>'>
<input type=hidden name="submit" id="submit" value="Continue"/>
</form>
</body>
</html>
<?php
$sale_amount = '$totalrow->totalprice';
$product = '$crow->title';
include('/home/**********************************.php');
}
} else {
/* == Failed Transaction= = */
require_once (BASEPATH . "lib/class_mailer.php");
$row = Core::getRowById(Content::eTable, 6);
$usr = Core::getRowById(Users::uTable, $user_id);
$body = str_replace(array('[USERNAME]','[STATUS]','[TOTAL]','[PP]','[IP]'), array(
$usr->username,"Failed",$core->formatMoney($gross),"PayPal",$_SERVER['REMOTE_ADDR']), $row->body);
$newbody = cleanOut($body);
$mailer = Mailer::sendMail();
$message = Swift_Message::newInstance()
->setSubject($row->subject)
->setTo(array($core->site_email => $core->site_name))
->setFrom(array($core->site_email => $core->site_name))
->setBody($newbody, 'text/html');
$mailer->send($message);
}
}
}
?>
and here is the FORM code im using :
<!doctype html>
<html>
<head></head>
<body onload="document.createElement('form').submit.call(document.getElementById('Form'))">
<form id='Form' name='form' action='http://www.****************.php' method='post'>
<input type='hidden' name='name' value='<?php echo $_POST['usr->username'];?>'>
<input type='hidden' name='email' value='<?php echo $_POST['usr->email'];?>'>
<input type='hidden' name='original_url' value='http://www.****************ipn.php'>
<input type='hidden' name='projname' value='<?php echo $_POST['crow->title'];?>'>
<input type=hidden name="submit" id="submit" value="Continue"/>
</form>
</body>
</html>
I am also aware that I may need to use a foreach() loop but ill cross that bridge when i get there, I really need to figure this out first.
So there we are, i think i have left enough info, details and code,
If i have missed anything out that might help just let me know
When you use
<input type="hidden" name="name" value="<?php echo $_POST['usr->username'];?>">
you are calling a POST variable 'usr->username' which does not exist, as far as I see in your script. Instead, use this:
<input type="hidden" name="name" value="<?php echo $usr->username;?>">
That would set the value of the input to the property 'username' of the 'usr' object you define on the line:
$usr = Core::getRowById(Users::uTable, $user_id);
The same applies to the other fields.
Hope it helps :)
Regards
I am trying to send emails using php
<HTML>
<HEAD><TITLE>E-mailer</TITLE></HEAD>
<BODY background="bricks.jpg">
<?php
//adv_mailer.php
function mailer_header()
{
?>
<p>
<?php
}
function mailer_footer()
{
?>
<p>
<?php
}
function error_message($msg)
{
mailer_header();
echo "<SCRIPT>alert(\"Error: $msg\");history.go(-1)</SCRIPT>";
mailer_footer();
exit;
}
function user_message($msg)
{
mailer_header();
echo "<SCRIPT>alert(\"$msg\");history.go(-1)</SCRIPT>";
mailer_footer();
exit;
}
function mail_form() {
global $PHP_SELF;
?>
<FORM METHOD="POST" ENCTYPE="MULTIPART/FORM-DATA" ACTION="<?php echo $PHP_SELF ?>">
<INPUT TYPE="HIDDEN" NAME="action" VALUE="send_mail">
<DIV ALIGN="CENTER ">
<TABLE CELLSPACING="2" CELLPADDING="5" WIDTH="79%" BORDER="0">
<TR>
<TH ALIGN="right" WIDTH="16%"><font color="#FFFF00">To</font></TH>
<TD WIDTH="84%" colspan="2"><font color="#FFFF00"><INPUT NAME="mail_to" SIZE="81"></font></TD>
</TR>
<TR>
<TH ALIGN="right" WIDTH="16%"><font color="#FFFF00">Cc</font></TH>
<TD WIDTH="84%" colspan="2"><font color="#FFFF00"><INPUT NAME="mail_cc" SIZE="81"></font></TD>
</TR>
<TR>
<TH ALIGN="right" WIDTH="16%"><font color="#FFFF00">Bcc</font></TH>
<TD WIDTH="84%" colspan="2"><font color="#FFFF00"><INPUT NAME="mail_bcc" SIZE="81"></font></TD>
</TR>
<TR>
<TH ALIGN="right" WIDTH="16%"><font color="#FFFF00">From</font></TH>
<TD WIDTH="84%" colspan="2"><font color="#FFFF00"><INPUT SIZE="81" NAME="mail_from"></font></TD>
</TR>
<TR>
<TH ALIGN="right" WIDTH="16%"><font color="#FFFF00">Reply-to</font></TH>
<TD WIDTH="84%" colspan="2"><font color="#FFFF00"><INPUT SIZE="81" NAME="mail_reply_to"></font></TD>
</TR>
<TR>
<TH ALIGN="right" WIDTH="16%"><font color="#FFFF00">Attachment</font></TH>
<TD WIDTH="84%" colspan="2"><font color="#FFFF00"><INPUT TYPE="FILE" NAME="userfile"></font></TD>
</TR>
<TR>
<TH ALIGN="right" WIDTH="16%"><font color="#FFFF00">Type</font></TH>
<TD WIDTH="23%">
<font color="#FFFF00">
<INPUT TYPE="RADIO" VALUE="text" NAME="mail_type" CHECKED>TEXT</font></TD>
<TD WIDTH="61%">
<font color="#FFFF00">
<INPUT TYPE="RADIO" VALUE="html" NAME="mail_type">HTML</font></TD>
</TR>
<TR>
<TH ALIGN="right" WIDTH="16%"><font color="#FFFF00">Encoding</font></TH>
<TD WIDTH="23%">
<font color="#FFFF00">
<INPUT TYPE="RADIO" VALUE="7bit" NAME="mail_encoding" CHECKED>7BIT</font></TD>
<TD WIDTH="61%">
<font color="#FFFF00">
<INPUT TYPE="RADIO" VALUE="8bit" NAME="mail_encoding">8BIT</font></TD>
</TR>
<TR>
<TH ALIGN="right" WIDTH="16%"><font color="#FFFF00">Character Set</font></TH>
<TD WIDTH="23%">
<font color="#FFFF00">
<INPUT TYPE="RADIO" VALUE="us-ascii" NAME="mail_charset" CHECKED>US-ASCII </font></TD>
<TD WIDTH="61%">
<font color="#FFFF00"><INPUT TYPE="RADIO" VALUE="euc-kr" NAME="mail_charset">EUC-KR</font></TD>
</TR>
<TR>
<TH ALIGN="right" WIDTH="16%"><font color="#FFFF00">Subject</font></TH>
<TD WIDTH="84%" colspan="2"><font color="#FFFF00"><INPUT SIZE="81" NAME="mail_subject"></font></TD>
</TR>
<TR>
<TH ALIGN="right" WIDTH="16%" valign="top"><font color="#FFFF00">Body</font></TH>
<TD WIDTH="84%" colspan="2"><TEXTAREA NAME="mail_body" ROWS="16"
COLS="62"></TEXTAREA></TD>
</TR>
<TR>
<TH WIDTH="100%" COLSPAN="3" ALIGN="CENTER">
<INPUT TYPE="SUBMIT" VALUE="Send" NAME="SUBMIT">
<INPUT TYPE="RESET" VALUE="Reset" NAME="RESET">
</TH>
</TR>
</TABLE>
</DIV>
</FORM>
<?php
}
function send_mail()
{
global $mail_to, $mail_cc, $mail_bcc, $mail_from, $mail_reply_to;
global $mail_body, $mail_subject;
global $userfile, $userfile_type, $userfile_name, $userfile_size;
global $mail_type, $mail_charset, $mail_encoding;
$mail_parts["mail_type"] = $mail_type;
$mail_parts["mail_charset"] = $mail_charset;
$mail_parts["mail_encoding"] = $mail_encoding;
$mail_parts["userfile"] = $userfile;
$mail_parts["userfile_type"] = $userfile_type;
$mail_parts["userfile_name"] = $userfile_name;
$mail_parts["userfile_size"] = $userfile_size;
$mail_parts["mail_to"] = $mail_to;
$mail_parts["mail_from"] = $mail_from;
$mail_parts["mail_reply_to"] = $mail_reply_to;
$mail_parts["mail_cc"] = $mail_cc;
$mail_parts["mail_bcc"] = $mail_bcc;
$mail_parts["mail_subject"] = trim($mail_subject);
$mail_parts["mail_body"] = $mail_body;
if(my_mail($mail_parts))
user_message("Successfully sent an e-mail titled '$mail_subject'.");
else error_message("An unknown error occurred while attempting to
send an e-mail titled '$mail_subject'.");
}
function my_mail($mail_parts)
{
$mail_to = $mail_parts["mail_to"];
$mail_from = $mail_parts["mail_from"];
$mail_reply_to = $mail_parts["mail_reply_to"];
$mail_cc = $mail_parts["mail_cc"];
$mail_bcc = $mail_parts["mail_bcc"];
$mail_subject = $mail_parts["mail_subject"];
$mail_body = $mail_parts["mail_body"];
$mail_type = $mail_parts["mail_type"];
$mail_charset = $mail_parts["mail_charset"];
$mail_encoding = $mail_parts["mail_encoding"];
$userfile = $mail_parts["userfile"];
$userfile_type = $mail_parts["userfile_type"];
$userfile_name = $mail_parts["userfile_name"];
$userfile_size = $mail_parts["userfile_size"];
if(empty($mail_to)) error_message("Empty to field!");
if(empty($mail_subject)) error_message("Empty subject!");
if(empty($mail_body)) error_message("Empty body! ");
$mail_to = str_replace(";", ",", $mail_to);
$mail_headers = '';
if(!empty($mail_from)) $mail_headers .= "From: $mail_from\n";
if(!empty($mail_reply_to)) $mail_headers .= "Reply-to: $mail_reply_to\n";
if(!empty($mail_cc))
$mail_headers .= "Cc: " . str_replace(";", ",", $mail_cc) . "\n";
if(!empty($mail_bcc))
$mail_headers .= "Bcc: " . str_replace(";", ",", $mail_bcc) . "\n";
$mail_subject = stripslashes($mail_subject);
$mail_body = stripslashes($mail_body);
if($userfile_size > 0)
{
$mail_boundary = md5(uniqid(time()));
$mail_headers .= "MIME-Version: 1.0\r\n";
$mail_headers .= "Content-type: multipart/mixed;
boundary=\"$mail_boundary\"\r\n\r\n";
$mail_headers .= "This is a multi-part message in MIME format.\r\n\r\n";
$fp = fopen($userfile, "r");
$file = fread($fp, filesize($userfile));
$file = chunk_split(base64_encode($file));
$new_mail_body = "--$mail_boundary\r\n";
$new_mail_body .= "Content-type:text/plain;charset=$mail_charset\r\n";
$new_mail_body .= "Content-transfer-encoding:$mail_encoding\r\n\r\n";
$new_mail_body .= "$mail_body\r\n";
$new_mail_body .= "--$mail_boundary\r\n";
if(!empty($userfile_type)) $mime_type = $userfile_type;
else $mime_type = "application/octet-stream";
$new_mail_body .= "Content-type:$mime_type;name=$userfile_name\r\n";
$new_mail_body .= "Content-transfer-encoding:base64\r\n\r\n";
$new_mail_body .= $file . "\r\n\r\n";
$new_mail_body .= "--$mail_boundary--";
$mail_body = $new_mail_body;
}
else if($mail_type == 'html')
{
$mail_headers .= "Content-type: text/html; charset=$mail_charset\r\n";
$mail_headers .= "Content-transfer-encoding:$mail_encoding\r\n\r\n";
}
else
{
$mail_headers .= "Content-type: text/plain; charset=$mail_charset\r\n";
$mail_headers .= "Content-transfer-encoding:$mail_encoding\r\n\r\n";
}
return mail($mail_to,$mail_subject,$mail_body,$mail_headers);
}
switch ($action)
{
case "send_mail":
mailer_header();
send_mail();
mailer_footer();
break;
case "mail_form":
mailer_header();
mail_form();
mailer_footer();
break;
default:
mailer_header();
mail_form();
mailer_footer();
break;
}
?>
</BODY>
</HTML>
I keep getting this errors
Notice: Undefined variable: action in C:\wamp\www\5\adv_mail.php on line 226
Notice: Undefined variable: action in C:\wamp\www\5\adv_mail.php on line 231
any help would be appreciated
$action is surely undefined. From your code it appears like you expect that to be the HTML hidden field named action that you've defined in your form. That error is simply saying you are trying to run a switch statement on something that doesn't exist. For that you should initialize it first.
if(isset($_POST['action']))
$action = $_POST['action']; // This is missing
else
die("No action defined");
switch ($action)
{
....
}
I know there is a simpler way to do this. What I'm trying to do is group fields by number and use isset to test if $_POST['item#'] value is empty. If that item# is not empty, I want to send corresponding color, quantity, and price. If there is more than one item submitted, I want to send multiples.
Here are my post variables:
$item1 = $_POST['item1'];
$color1 = $_POST['color1'];
$quantity1 = $_POST['quantity1'];
$price1 = $_POST['price1'];
$item2 = $_POST['item2'];
$color2 = $_POST['color2'];
$quantity2 = $_POST['quantity2'];
$price2 = $_POST['price2'];
$item3 = $_POST['item3'];
$color3 = $_POST['color3'];
$quantity3 = $_POST['quantity3'];
$price3 = $_POST['price3'];
$item4 = $_POST['item4'];
$color4 = $_POST['color4'];
$quantity4 = $_POST['quantity4'];
$price4 = $_POST['price4'];
$item5 = $_POST['item5'];
$color5 = $_POST['color5'];
$quantity5 = $_POST['quantity5'];
$price5 = $_POST['price5'];
$item6 = $_POST['item6'];
$color6 = $_POST['color6'];
$quantity6 = $_POST['quantity6'];
$price6 = $_POST['price6'];
$item7 = $_POST['item7'];
$color7 = $_POST['color7'];
$quantity7 = $_POST['quantity7'];
$price7 = $_POST['price7'];
$item8 = $_POST['item8'];
$color8 = $_POST['color8'];
$quantity8 = $_POST['quantity8'];
$price8 = $_POST['price8'];
I'm using isset to test if $_POST[] values are empty:
if( isset($_POST['item1']) )
{
$message = 'Item: '.$item1." \nColor: ".$color1." \nQuantity: ".$quantity1." \nPrice: ".$price1;
}
if( isset($_POST['item2']) )
{
$message = 'Item: '.$item2." \nColor: ".$color2." \nQuantity: ".$quantity2." \nPrice: ".$price2;
}
if( isset($_POST['item3']) )
{
$message = 'Item: '.$item3." \nColor: ".$color3." \nQuantity: ".$quantity3." \nPrice: ".$price3;
}
if( isset($_POST['item4']) )
{
$message = 'Item: '.$item4." \nColor: ".$color4." \nQuantity: ".$quantity4." \nPrice: ".$price4;
}
if( isset($_POST['item5']) )
{
$message = 'Item: '.$item5." \nColor: ".$color5." \nQuantity: ".$quantity5." \nPrice: ".$price5;
}
if( isset($_POST['item6']) )
{
$message = 'Item: '.$item6." \nColor: ".$color6." \nQuantity: ".$quantity6." \nPrice: ".$price6;
}
if( isset($_POST['item7']) )
{
$message = 'Item: '.$item7." \nColor: ".$color6." \nQuantity: ".$quantity7." \nPrice: ".$price7;
}
if( isset($_POST['item7']) )
{
$message = 'Item: '.$item8." \nColor: ".$color7." \nQuantity: ".$quantity8." \nPrice: ".$price8;
}
$items = $_POST['item'];
for ($i = 0; $i < count($items); $i++) {
if ($items[$i])){ //not necessarily the best way to check if it has a value
//do what you want with $items[$i], $color[$i], $quantity[$i], and $price[$]
}
}
For your HTML form inputs use:
<input type="text" name="item[]" />
Here is the requested HTML. I'm just learning so I'm sure there is a more efficient way to name inputs. I'm trying to group item-color-quantity-price, so that when the form is emailed, the relevant data is in a paragraph or table for each item.
<td align="center"><p><span>Item Name</span><br><input id="item1" type="text" name="item1"></p></td>
<td align="center"><p><span>Color</span><br><input id="color1" type="text" name="color1"></td>
<td align="center"><p><span>Quantity</span><br><input id="quantity1" type="text" name="quantity1"></td>
<td align="center"><p><span>Wholesale Price</span><br><input id="price1" type="text" name="price1"></td>
</tr>
<tr>
<td align="center"><p><input id="item2" type="text" name="item2"></p></td>
<td align="center"><p><input id="color2" type="text" name="color2"></p></td>
<td align="center"><p><input id="quantity2" type="text" name="quantity2"></p></td>
<td align="center"><p><input id="price2" type="text" name="price2"></p></td>
</tr>
<tr>
<td align="center"><p><input id="item3" type="text" name="item3"></p></td>
<td align="center"><p><input id="color3" type="text" name="color3"></p></td>
<td align="center"><p><input id="quantity3" type="text" name="quantity3"></p></td>
<td align="center"><p><input id="price3" type="text" name="price3"></p></td>
</tr>
<tr>
<td align="center"><p><input id="item4" type="text" name="item4"></p></td>
<td align="center"><p><input id="color4" type="text" name="color4"></p></td>
<td align="center"><p><input id="quantity4" type="text" name="quantity4"></p></td>
<td align="center"><p><input id="price4" type="text" name="price4"></p></td>
</tr>
<tr>
<td align="center"><p><input id="item5" type="text" name="item5"></p></td>
<td align="center"><p><input id="color5" type="text" name="color5"></p></td>
<td align="center"><p><input id="quantity5" type="text" name="quantity5"></p></td>
<td align="center"><p><input id="price5" type="text" name="price5"></p></td>
</tr>
<tr>
<td align="center"><p><input id="item6" type="text" name="item6"></p></td>
<td align="center"><p><input id="color6" type="text" name="color6"></p></td>
<td align="center"><p><input id="quantity6" type="text" name="quantity6"></p></td>
<td align="center"><p><input id="price6" type="text" name="price6"></p></td>
</tr>
<tr>
<td align="center"><p><input id="item7" type="text" name="item7"></p></td>
<td align="center"><input id="color7" type="text" name="color7"></p></td>
<td align="center"><input id="quantity7" type="text" name="quantity7"></p></td>
<td align="center"><p><input id="price7" type="text" name="price7"></p></td>
</tr>
<tr>
<td align="center"><p><input id="item8" type="text" name="item8"></p></td>
<td align="center"><p><input id="color8" type="text" name="color8"></p></td>
<td align="center"><p><input id="quantity8" type="text" name="quantity8"></p></td>
<td align="center"><p><input id="price8"type="text" name="price8"></p></td>
</tr>
<tr>
<td align="center"><p><input id="item9" type="text" name="item9"></p></td>
<td align="center"><p><input id="color9" type="text" name="color9"></p></td>
<td align="center"><p><input id="quantity9" type="text" name="quantity9"></p></td>
<td align="center"><p><input id="price9" type="text" name="price9"></p></td>
</tr>
I converted all my input names to arrays and I have working loop. However, I need to format the foreach to produce an HTML email with table. It was working perfectly when echo-ing the data but once I formatted it to send as $message, it only sends the last $item.
Here is the foreach loop that works perfectly:
foreach ( $_POST['item'] as $items) {
{
echo '<table>';
echo '<tr>';
echo ' <td>', $items['name'], '</td>';
echo ' <td>', $items['color'], '</td>';
echo ' <td>', $items['size'], '</td>';
echo ' <td>', $items['quantity'], '</td>';
echo ' <td>', $items['price'], '</td>';
echo '</tr>';
}
echo '</table>';
}
HTMl email using the PHP mail function:
foreach ( $_POST['item'] as $items) {
$message = "
<html>
<body>
<table>
<tr>
<th>Name</th>
<th>Color</th>
<th>Size</th>
<th>Quantity</th>
<th>Price</th>
</tr>
<tr>
<td>" . $items['name'] . "</td>
<td>" . $items['color'] . "</td>
<td>" . $items['size'] . "</td>
<td>" . $items['quantity'] . "</td>
<td>" . $items['price'] . "</td>
</tr>
</table>
</body>
</html>
";
}
I wonder is it possible to keep the user input inside form field after form submitted, so that the user can update the entry. I've a html registration form [with some JS validation], then a php file to insert data to sql & meanwhile display back the inserted data in a table view. i also include the form's html code in php file so i can see the form after being submitted. but i couldn't keep the data in the field after form submitted! here is the form:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript">
<!--
function validateNum(evt) {
var theEvent = evt;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode( key );
var regex = /[0-9]/;
if( !regex.test(key) ) {
theEvent.returnValue = false;
if(theEvent.preventDefault) theEvent.preventDefault();
}
}
function validate(evt){
if( document.myForm.ic.value == ""){
alert( "IC Number cann't be empty!" );
document.myForm.ic.focus() ;
return false;}
else if(isNaN( document.myForm.ic.value ) || document.myForm.ic.value.length != 12){
evt.preventDefault();
alert( "Please provide your correct IC Number!" );
document.myForm.ic.focus() ;
return false;}
if( document.myForm.name.value == "") {
alert( "Name cann't be empty!" );
document.myForm.name.focus() ;
return false;
}
if( document.myForm.contact.value == ""){
alert( "Contact number cann't be empty!");
document.myForm.contact.focus() ;
return false;
} else if(isNaN( document.myForm.contact.value ))
{
evt.preventDefault();
alert( "Please provide your correct Contact Number!" );
document.myForm.contact.focus() ;
return false;
}
if( document.myForm.address.value == "" ){
alert( "Please provide your Address!" );
document.myForm.address.focus() ;
return false;
}
}
//-->
</script>
</head>
<style type="text/css">
h2 {
color: #06C;
}
body {
background-color: #FFC;
}
</style>
<body>
<form name="myForm" method="post" action="insert.php" onsubmit="return(validate(event));">
<div align="center"><br>
<table width="453" border="0">
<tr>
<th colspan="4" bgcolor="#99FFFF" scope="col">
<h3>Workshop Name: PHP! </h3></th>
</tr>
<tr bgcolor="#99FF99">
<td width="142"> IC Number</td>
<td width="15"><div align="center">:</div></td>
<td colspan="2"><div align="right">
<input
name="ic" type="text" id="ic" maxlength="12" size="45" onkeypress='validateNum(event)'/>
</div></td>
</tr>
<tr bgcolor="#99FFFF">
<td>Full Name</td>
<td><div align="center">:</div></td>
<td colspan="2"><div align="right">
<input
name="name" type="text" id="name" size="45"/>
</div></td>
</tr>
<tr bgcolor="#99FF99">
<td>Contact No.</td>
<td><div align="center">:</div></td>
<td colspan="2"><div align="right">
<input
name="contact" type="text" id="contact" size="45" onkeypress='validateNum(event)' />
</div></td>
</tr>
<tr bgcolor="#99FFFF">
<td>Email</td>
<td><div align="center">:</div></td>
<td colspan="2"><div align="right">
<input
name="mail" type="text" id="mail" size="45"/>
</div></td>
</tr>
<tr bgcolor="#99FF99">
<td height="60">Address</td>
<td><div align="center">:</div></td>
<td colspan="2">
<div align="right">
<textarea name="address" id="address" cols="35" rows="3"></textarea>
</div>
</td>
</tr>
<tr bgcolor="#99FFFF">
<td colspan="2"> </td>
<td width="231"><input type="reset" value="Clear" /></td>
<td width="47"><div align="right">
<input type="submit" value="Submit" />
</div></td>
</tr>
</table>
<br>
</div>
</form>
</body>
</html>
here is the insert.php file:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript">
<!--
function validateNum(evt) {
var theEvent = evt;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode( key );
var regex = /[0-9]/;
if( !regex.test(key) ) {
theEvent.returnValue = false;
if(theEvent.preventDefault) theEvent.preventDefault();
}
}
function validate(evt){
if( document.myForm.ic.value == ""){
alert( "IC Number cann't be empty!" );
document.myForm.ic.focus() ;
return false;}
else if(isNaN( document.myForm.ic.value ) || document.myForm.ic.value.length != 12){
evt.preventDefault();
alert( "Please provide your correct IC Number!" );
document.myForm.ic.focus() ;
return false;}
if( document.myForm.name.value == "") {
alert( "Name cann't be empty!" );
document.myForm.name.focus() ;
return false;
}
if( document.myForm.contact.value == ""){
alert( "Contact number cann't be empty!");
document.myForm.contact.focus() ;
return false;
} else if(isNaN( document.myForm.contact.value ))
{
evt.preventDefault();
alert( "Please provide your correct Contact Number!" );
document.myForm.contact.focus() ;
return false;
}
if( document.myForm.address.value == "" ){
alert( "Please provide your Address!" );
document.myForm.address.focus() ;
return false;
}
}
//-->
</script>
</head>
<style type="text/css">
h2 {
color: #06C;
}
body {
background-color: #FFC;
}
</style>
<body>
<form name="myForm" method="post" action="update.php" onsubmit="return(validate(event));">
<div align="center"><br>
<table width="453" border="0">
<tr>
<th colspan="4" bgcolor="#99FFFF" scope="col">
<h3>Workshop Name: PHP! </h3></th>
</tr>
<tr bgcolor="#99FF99">
<td width="142"> IC Number</td>
<td width="15"><div align="center">:</div></td>
<td colspan="2"><div align="right">
<input
name="ic" type="text" id="ic" maxlength="12" size="45" onkeypress='validateNum(event)'/>
</div></td>
</tr>
<tr bgcolor="#99FFFF">
<td>Full Name</td>
<td><div align="center">:</div></td>
<td colspan="2"><div align="right">
<input
name="name" type="text" id="name" size="45"/>
</div></td>
</tr>
<tr bgcolor="#99FF99">
<td>Contact No.</td>
<td><div align="center">:</div></td>
<td colspan="2"><div align="right">
<input
name="contact" type="text" id="contact" size="45" onkeypress='validateNum(event)' />
</div></td>
</tr>
<tr bgcolor="#99FFFF">
<td>Email</td>
<td><div align="center">:</div></td>
<td colspan="2"><div align="right">
<input
name="mail" type="text" id="mail" size="45"/>
</div></td>
</tr>
<tr bgcolor="#99FF99">
<td height="60">Address</td>
<td><div align="center">:</div></td>
<td colspan="2">
<div align="right">
<textarea name="address" id="address" cols="35" rows="3"></textarea>
</div>
</td>
</tr>
<tr bgcolor="#99FFFF">
<td colspan="2"> </td>
<td width="231"><input type="reset" value="Clear" /></td>
<td width="47"><div align="right">
<input type="submit" value="Update" />
</div></td>
</tr>
</table>
<br>
</div>
</form>
<br>
</div>
</form>
<div align="center">
<?php
if (!mysql_connect('localhost', 'root', '')) {
echo "Connected";
}
mysql_select_db("workshop");
// Get values from form
$ic = mysql_real_escape_string($_POST['ic']);
$name = mysql_real_escape_string($_POST['name']);
$contact = mysql_real_escape_string($_POST['contact']);
$mail = mysql_real_escape_string($_POST['mail']);
$address = mysql_real_escape_string($_POST['address']);
if (staff_detail_exist($ic) == "available") {
insert_staff_detail($ic, $name, $contact, $mail, $address, $paytype);
echo "<p style='text-align:center; color:green;'>" . "Workshop application successful! You will be notified shortly via E-mail after confirmation! Thank You!";
} else if (staff_detail_exist($ic) == "exist") {
echo "<p style='text-align:center; color:red;'>" . "Record already exists! Please enter another Staff ID. Thank You!" . "</p>";
}
function insert_staff_detail($ic, $name, $contact, $mail, $address, $paytype) {
$sql = "INSERT INTO apply (staffid, staffname, staffno, staffemail, staffaddress, paytype) VALUES ('$ic', '$name', '$contact', '$mail', '$address','$paytype')";
mysql_query($sql);
}
function staff_detail_exist($ic) {
$result = null;
$sql = "SELECT * FROM apply WHERE staffid = '$ic'";
$data = mysql_query($sql);
if (mysql_num_rows($data) == 0) {
$result = "available";
} else {
$result = "exist";
}
return $result;
}
$staffid = $_POST['ic'];
$con = mysql_connect("localhost", "root", "");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("workshop", $con);
$result = mysql_query("SELECT * FROM apply where staffid = '$ic'");
echo "<table width=400 border=1 cellpadding=0 align=center>";
while ($row = mysql_fetch_array($result)) {
echo "<tr>";
echo "<th>Staff/IC Number: </th><td>" . "<center>" . $row['staffid'] . "</center>" . "</td>";
echo "</tr>";
echo "<th>Name: </th><td>" . "<center>" . $row['staffname'] . "</center>" . "</td>";
echo "</tr>";
echo "<th>Email: </th><td>" . "<center>" . $row['staffemail'] . "</center>" . "</td>";
echo "</tr>";
echo "<th>Contact No.: </th><td>" . "<center>" . $row['staffno'] . "</center>" . "</td>";
echo "</tr>";
echo "<th>Address: </th><td>" . "<center>" . $row['staffaddress'] . "</center>" . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
</body>
</html>
I've tried to add like value="<? echo "$row['staffid']"?>" in the form's field at php file but no luck! I've only basic in php. So, any help? thank you!
thanks all, its finally working :) i've used value="<?php echo isset($_POST['myField']) ? $_POST['myField'] : 'myField_db' ?>" inside the input tag. so, its like: <input type="text" name="myField" value="<?php echo isset($_POST['myField']) ? $_POST['myField'] : 'myField_db' ?>" /> where myField is input name & myField_db is the column name from database.
Take the form posted values just above your html code like this
<?php
if (isset($_POST["submit"]) && $_POST["submit"]=='Submit') {
$name=$_POST["name"];
}
?>
And echo it in your html form.
<input name="name" type="text" id="name" size="45" value="<? echo $name?>"/>
I've used this function a few times; quite handy
function getPost($field){
return (isset($_POST[$field]) && $_POST[$field] != "" ? $_POST[$field] : "");
}
Usage
<input type="text" name="contact" value="<?php echo getPost("contact"); ?>" />
This is for the cases where a user submits information and is for some reason sent back to the form again - perhaps their entries didn't pass PHP validation, for example.