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
Related
I am having an issue with my contact form and need help with the code.
Here is an image of the "cart", user can add/remove items from the table.
Once they have selected all the products they want, in this example I have added 2 items, they then click the order form button and a form pops up to the left that displays both items.
My problem is that when the email comes through it only displays the last item and not both items from the form, this is what it looks like in the email
How do I make it so that it pulls through both items or all items from the form on the left into the body of my email.
Below is my code, if someone can look through and advise what I must change or what I am doing wrong.
<section class="order">
<?php
$id = isset($_GET['id']) ? (int) $_GET['id'] : 0;
$sql = $con->prepare("SELECT * FROM products WHERE product_id = ?");
$sql->bind_param("i", $id);
$sql->execute();
$result = $sql->get_result();
$rows = $result->num_rows;
{
while($row = $result->fetch_assoc())
{
?>
<div class="product-info">
<form method="post" action="cart.php?action=add&id=<?php echo $row["product_id"]; ?>">
<img src="images/<?php echo $row["image"]; ?>" class="image" /><br /><br>
<h3 class="name"><?php echo $row["productname"]; ?></h3><br>
<h5 class="desc"><?php echo $row["description"]; ?></h5><br>
<h4 class="code"><?php echo $row["code"]; ?></h4><br>
<input type="text" name="quantity" value="1" class="form-control" /><br>
<input type="hidden" name="hidden_name" value="<?php echo $row["productname"]; ?>" />
<input type="hidden" name="hidden_description" value="<?php echo $row["description"]; ?>" />
<input type="hidden" name="hidden_code" value="<?php echo $row["code"]; ?>" />
<input type="submit" name="add_to_cart" style="margin-top:5px;" class="addtocart" value="Add to Cart" />
</form>
</div>
<?php
}
}
?>
<?php
if(isset($_POST["add_to_cart"]))
{
if(isset($_SESSION["shopping_cart"]))
{
$item_array_id = array_column($_SESSION["shopping_cart"], "item_id");
if(!in_array($_GET["id"], $item_array_id))
{
$count = count($_SESSION["shopping_cart"]);
$item_array = array(
'item_id' => $_GET["id"],
'item_name' => $_POST["hidden_name"],
'item_description' => $_POST["hidden_description"],
'item_code' => $_POST["hidden_code"],
'item_quantity' => $_POST["quantity"]);
$_SESSION["shopping_cart"][$count] = $item_array;
}
else
{
echo ("<br><br><div class='alert alert-danger'>Item already added.</div>");
}
}
else
{
$item_array = array(
'item_id' => $_GET["id"],
'item_name' => $_POST["hidden_name"],
'item_description' => $_POST["hidden_description"],
'item_code' => $_POST["hidden_code"],
'item_quantity' => $_POST["quantity"]);
$_SESSION["shopping_cart"][0] = $item_array;
}
}
if(isset($_GET["action"]))
{
if($_GET["action"] == "delete")
{
foreach($_SESSION["shopping_cart"] as $keys => $values)
{
if($values["item_id"] == $_GET["id"])
{
unset($_SESSION["shopping_cart"][$keys]);
echo ("<br><br><div class='alert alert-success'>Successfully Removed Item</div>");
}
}
}
}
?>
<br />
<h2>Order Details</h2>
<div class="table-responsive">
<table class="table table-bordered">
<tr>
<th width="35%">Item Name</th>
<th width="45%">Description</th>
<th width="18%">Code</th>
<th width="2%">Qty</th>
<th width="5%">Action</th>
</tr>
<?php
if(!empty($_SESSION["shopping_cart"]))
{
foreach($_SESSION["shopping_cart"] as $keys => $values)
{
?>
<tr>
<td><?php echo $values["item_name"]; ?></td>
<td><?php echo $values["item_description"]; ?></td>
<td><?php echo $values["item_code"]; ?></td>
<td><?php echo $values["item_quantity"]; ?></td>
<td><span class="text-danger">Remove</span></td>
</tr>
<?php
}
?>
<?php
}
?>
</table>
</div>
<td><button class="open-button" onclick="openForm()">Open Form</button></td>
</section>
<section>
<div class="form-popup" id="myForm">
<form method="post" action="cart.php">
<input type="text" name="name" placeholder="Name"><br><br>
<input type="text" name="mail" placeholder="Your e-mail"><br><br>
<input type="text" name="number" placeholder="Your contact number"><br><br>
<input type="text" name="subject" placeholder="Subject"><br><br>
<h2>Order Details</h2>
<?php
if(!empty($_SESSION["shopping_cart"]))
{
foreach($_SESSION["shopping_cart"] as $keys => $values)
{
?>
<tr>
<td>Item Name:<input type="text" name="productname" value="<?php echo $values["item_name"]; ?>"></td><br>
<td>Description:<input type="text" name="description" value="<?php echo $values["item_description"]; ?>"></td><br>
<td>Code:<input type="text" name="code" value="<?php echo $values["item_code"]; ?>"></td><br>
<td>Qty:<input type="text" name="qty" value="<?php echo $values["item_quantity"]; ?>"></td><br><br>
</tr>
<?php
}
?>
<?php
}
?>
<button class="button" type="submit" name="submit">SEND</button><br>
<?php
if(isset($_POST['submit'])) {
$name = $_POST['name'];
$subject = $_POST['subject'];
$mailFrom = $_POST['mail'];
$number = $_POST['number'];
$product = $_POST['productname'];
$description = $_POST['description'];
$code = $_POST['code'];
$qty = $_POST['qty'];
$mailTo = "email#example.co.za";
$headers = "From: ".$mailFrom;
$txt = "You have received an e-mail from ".$name.".\n\n"."Email address: ".$mailFrom.".\n\n"."Contact number: ".$number.".\n\n"."Order Details:\n\n".$product.".\n\n"."Description:".$description.".\n\n"."Product Code:".$code.".\n\n"."Quantity Ordered:".$qty;
mail($mailTo, $subject, $txt, $headers);
header("Location: cart.php?mailsend");
}
?>
</form>
</div>
</section>
Your help would be greatly appreciated :)
The fault lies here:
if (isset($_POST['submit'])) {
$name = $_POST['name'];
$subject = $_POST['subject'];
$mailFrom = $_POST['mail'];
$number = $_POST['number'];
$product = $_POST['productname'];
$description = $_POST['description'];
$code = $_POST['code'];
$qty = $_POST['qty'];
$mailTo = "email#example.co.za";
$headers = "From: " . $mailFrom;
$txt = "You have received an e-mail from " . $name . ".\n\n" . "Email address: " . $mailFrom . ".\n\n" . "Contact number: " . $number . ".\n\n" . "Order Details:\n\n" . $product . ".\n\n" . "Description:" . $description . ".\n\n" . "Product Code:" . $code . ".\n\n" . "Quantity Ordered:" . $qty;
mail($mailTo, $subject, $txt, $headers);
header("Location: cart.php?mailsend");
}
The $txt variable is responsible for the text in the Email and you are setting its value to the last order posted via the form. You have to concatenate every order. So, you have to do something like $txt .= "You...." Use the (.) operator to concatenate product details every time
i have function in controller that repeatedly generates a table via ajax request
i want to validate table every time ajax makes request to this function
how can i validate the start date and law reg no of the table when ajax fetches it with click of button.
my code for function:
public function postlawsdata()
{
$lawdata = Input::get('law_type_id');
$sublawdata = Input::get('law_sub_type_id');
$start_date = Input::get('start_date');
$res_div = '';
$sub_law_count = count($sublawdata);
$validate_laws = '';
if (count($sublawdata) > 0) {
for ($i = 0; $i < count($lawdata); $i++) {
$law_details = DB::table('tbl_law_master')->where('id', $lawdata[$i])->select('tbl_law_master.id as law_id', 'tbl_law_master.lm_id', 'tbl_law_master.law_name')->first();
$sublaw_details = DB::table('tbl_law_sub_master')
->where('tbl_law_sub_master.lm_id', $lawdata[$i])
->whereNull('tbl_law_sub_master.deleted_at')
->select('tbl_law_sub_master.id as sublaw_id', 'tbl_law_sub_master.sub_law_name', 'tbl_law_sub_master.lms_id')->get();
if (count($sublaw_details) > 0) {
$res_div .= '<table width="100%" border="0" class="table table-striped table-bordered table-hover">';
$res_div .= '<tr>
<td colspan="2" rowspan="2">
<strong>' . $law_details->lm_id . ' (' . $law_details->law_name . ')</strong>
</td>
<td >
<span class="required" aria-required="true">* </span><input type="text" value="' . $start_date . '" placeholder="DD-MM-YYYY (Start Date)" name="law_start_date[]" id="law_start_date" att_law_id="' . $lawdata[$i] . '" class="date-picker required locationformstyle locationparentsd dynamiclocationparentsd' . $lawdata[$i] . '">
</td></tr><tr><td>
<span class="required" aria-required="true">* </span><input type="text" placeholder="Law Registration No." name="law_reg_no" id="law_reg_no" class="locationformstyle required">
</td>
</tr>';
foreach ($sublaw_details as $sublawdetails) {
if (in_array($sublawdetails->sublaw_id, $sublawdata)) {
$res_div .= '<tr>
<td width="220">Start Date: <input type="text" name="sub_law_start_date[]" placeholder="DD-MM-YYYY" onfocus="this.blur()" class="locationformstyle date-picker dynamiclocationparentsd' . $lawdata[$i] . '" att_law_id="' . $lawdata[$i] . '"> </td>
<td width="220">End Date: <input type="text" name="sub_law_end_date[]" placeholder="DD-MM-YYYY" onfocus="this.blur()" class="locationformstyle date-picker"></td>
<td align="left"><strong>' . $sublawdetails->lms_id . ' (' . $sublawdetails->sub_law_name . ')</strong>
<input type="hidden" class="locationformstyle" name="company_sub_laws[]" value="' . $sublawdetails->sublaw_id . '">
</td>
</tr>
';
}
}
$res_div .= '</table>';
}
}
} else {
$validate_laws = 'Please Select Atleast One Law';
}
$data = array(
'law_info' => $res_div,
'validate_laws' => $validate_laws,
'sub_law_count' => $sub_law_count
);
return json_encode($data);
}
create a new validator like so;
public function postlawsdata()
{
$validator = Validator::make($request->all(), [
'start_date' => 'required',
//add other fields here with custom validation rules
]);
if ($validator->passes()) {
$lawdata = Input::get('law_type_id');
$sublawdata = Input::get('law_sub_type_id');
$start_date = Input::get('start_date');
$res_div = '';
$sub_law_count = count($sublawdata);
$validate_laws = '';
if (count($sublawdata) > 0) {
for ($i = 0; $i < count($lawdata); $i++) {
$law_details = DB::table('tbl_law_master')->where('id', $lawdata[$i])->select('tbl_law_master.id as law_id', 'tbl_law_master.lm_id', 'tbl_law_master.law_name')->first();
$sublaw_details = DB::table('tbl_law_sub_master')
->where('tbl_law_sub_master.lm_id', $lawdata[$i])
->whereNull('tbl_law_sub_master.deleted_at')
->select('tbl_law_sub_master.id as sublaw_id', 'tbl_law_sub_master.sub_law_name', 'tbl_law_sub_master.lms_id')->get();
if (count($sublaw_details) > 0) {
$res_div .= '<table width="100%" border="0" class="table table-striped table-bordered table-hover">';
$res_div .= '<tr>
<td colspan="2" rowspan="2">
<strong>' . $law_details->lm_id . ' (' . $law_details->law_name . ')</strong>
</td>
<td >
<span class="required" aria-required="true">* </span><input type="text" value="' . $start_date . '" placeholder="DD-MM-YYYY (Start Date)" name="law_start_date[]" id="law_start_date" att_law_id="' . $lawdata[$i] . '" class="date-picker required locationformstyle locationparentsd dynamiclocationparentsd' . $lawdata[$i] . '">
</td></tr><tr><td>
<span class="required" aria-required="true">* </span><input type="text" placeholder="Law Registration No." name="law_reg_no" id="law_reg_no" class="locationformstyle required">
</td>
</tr>';
foreach ($sublaw_details as $sublawdetails) {
if (in_array($sublawdetails->sublaw_id, $sublawdata)) {
$res_div .= '<tr>
<td width="220">Start Date: <input type="text" name="sub_law_start_date[]" placeholder="DD-MM-YYYY" onfocus="this.blur()" class="locationformstyle date-picker dynamiclocationparentsd' . $lawdata[$i] . '" att_law_id="' . $lawdata[$i] . '"> </td>
<td width="220">End Date: <input type="text" name="sub_law_end_date[]" placeholder="DD-MM-YYYY" onfocus="this.blur()" class="locationformstyle date-picker"></td>
<td align="left"><strong>' . $sublawdetails->lms_id . ' (' . $sublawdetails->sub_law_name . ')</strong>
<input type="hidden" class="locationformstyle" name="company_sub_laws[]" value="' . $sublawdetails->sublaw_id . '">
</td>
</tr>
';
}
}
$res_div .= '</table>';
}
}
} else {
$validate_laws = 'Please Select Atleast One Law';
}
$data = array(
'law_info' => $res_div,
'validate_laws' => $validate_laws,
'sub_law_count' => $sub_law_count
);
return json_encode($data);
}
return response()->json(['error'=>$validator->errors()->all()]);
}
add use Validator; at the top.
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
}
?>
This is weird, and ive never seen this before. Im using post to post values back to the same page for processing. Everything is working fine until I try to use a hidden field to post values. Using the same convention ive used a million times before. The odd thing is that its not posting using the name supplied, its just using hiddenField as the name. Here is the code
<input name="eid" type="hidden" id="eid" value="<? print $_GET['eid']; ?>" />
And im using this to figure it out
print_r($_POST);
This is the result
[hiddenField] => 6
Now, its posting the value, and its posting the correct value that is put into the hidden field before its submitted, but for some reason that I cant seem to figure out, its not using the name attribute that I set in HTML to identify it. All my other values are using there posted names. Any insight would be greatly appreciated as I do not wish to have to deal with an awkward array of hiddenFields later on.
Edit: Here is the rest of the code for the page (pertinent parts)
<?
if (isset($_POST['Submit']))
{
print "<p>EID: " . $_POST['hiddenField'] . "</p>";
$eid = $_POST['hiddenField'];
$name = $_POST['name'];
$email = $_POST['email'];
$ncount = count($name);
$ecount = count($email);
$hash = uniqid() . "-" . count($name);
if ($ncount == $ecount)
{
$test = true;
for ($i = 0; $i < $ncount; $i++)
{
if ($name[$i] == "" || $email[$i] == "")
{
$test = false;
}
}
if ($test)
{
$tickets[] = array();
for ($i = 0; $i< $ncount; $i++)
{
$unique = false;
while (!$unique)
{
$tickets[$i] = generateCode();
$check_query = "SELECT id FROM ticket WHERE ticket_number='" . $tickets[$i] . "'";
if ($stmt = $mysqli->prepare($check_query))
{
$stmt->execute();
$stmt->store_result();
$count = $stmt->num_rows;
$stmt->close();
if ($count == 0)
{
$unique = true;
} else {
print "<p>Not unique</p>";
}
} else {
print "<p>Failed to work database</p>";
}
}
if ($unique == true)
{
$query = "INSERT INTO ticket (`ticket_number`, `event_id`, `name`, `email`,`date_created`, `hash`) VALUES (?,?,?,?,NOW(),?)";
print "<p>Ticket #" . $tickets[$i] . " Event Id: " . $eid . " Name: " . $name[$i] . " Email: " . $email[$i] . " Hash: " . $hash . "</p>";
if ($stmt = $mysqli->prepare($query))
{
$stmt->bind_param('sisss', $tickets[$i], $eid, $name[$i], $email[$i], $hash);
$stmt->execute();
$number = $stmt->affected_rows;
} else {
print "<p>Could not insert into DB because " . $stmt->error . "</p>";
}
}
}
}
}
}
<form action="register.php" method="post">
<table width="896" border="0">
<?
for($i = 0; $i<$_GET['quant']; $i++)
{
?> <tr>
<td><strong>Attendee <? print $z = $i+1; ?></strong></td>
<td> </td>
</tr>
<tr>
<td width="215">Name</td>
<td width="671"><label for="name"></label>
<input type="text" name="name[]" id="name" /></td>
</tr>
<tr>
<td>Email Address</td>
<td><input type="text" name="email[]" id="name2" /></td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
<?
}
}
?>
<tr>
<td><input name="eid" type="hidden" id="eid" value="<? print $_GET['eid']; ?>" /></td>
<td><input type="submit" name="Submit" id="Submit" value="Submit" /></td>
</tr>
</table>
</form>
Please help me regarding the problem specified in the title.
Input form page code:
<?
db_connect();
$query1 = "SELECT *, DATE_FORMAT(eventdate,'%m/%d/%y') AS
eventdate,DATE_FORMAT(throughdate,'%m/%d/%y') AS throughdate FROM events WHERE id = " . mysql_real_escape_string($_REQUEST['id']);
$result1 = mysql_query($query1) or die("Error - query failed " . mysql_error());
if ( mysql_num_rows($result1) == 0 ) {
print "<p>Error - no such event.</p>\n";
return;
}
else {
$qry_event1 = mysql_fetch_array($result1);
}
// default the formaction to the query
if (! isset($_REQUEST['formaction']) ) { $_REQUEST['formaction'] = 'query'; }
?>
<form name="eventform" method="post" action="act_updevent.php">
<input type="hidden" name="submit_check" value="1">
<input type="hidden" name="formaction" value="form">
<!-- if we are editing, $id will exist. Pass it along. -->
<input type="hidden" name="id" value="<?php $qry_event1['id'];?>">
<table>
<tr>
<td align="right" valign="center"><b><? displayformlabel('eventdate','Event Date:')?>
</b></td>
<td><input name="eventdate" value="<? echo $qry_event1['eventdate']; ?>">
<a name="calendar1here" id="calendar1here" href="JavaScript:;"
onClick="cal1.select(document.forms[0].eventdate,'calendar1here','MM/dd/yy'); return
false;">
<img src="resources/calendar.gif" alt="Calendar Icon" width="20" height="20"
border="0"></a>
</td>
</tr>
<tr>
<td align="right" valign="center"><b><? displayformlabel('throughdate','Through:')?>
</b></td>
<td><input name="throughdate" value="<? echo $qry_event1['throughdate']; ?>">
<a name="calendar2here" id="calendar2here" href="JavaScript:;"
onClick="cal2.select(document.forms[0].throughdate,'calendar2here','MM/dd/yy'); return
false;">
<img src="resources/calendar.gif" alt="Calendar Icon" width="20" height="20"
border="0"></a>
<span class="formnotes">Leave blank if only one day event</span>
</td>
</tr>
<tr>
<td align="right"><b><? displayformlabel('title','Event Title:')?></b></td>
<td><input name="title" size="50" maxlength="50" value="<? echo $qry_event1['title'];?
>"></td>
</tr>
<tr>
<td align="right"><? displayformlabel('website','Event Website:')?></td>
<td><input name="website" size="50" maxlength="100" value="<? echo
$qry_event1['website']; ?>"></td>
</tr>
<tr>
<td align="right"><? displayformlabel('email','Event Email:')?></td>
<td><input name="email" size="50" maxlength="100" value="<? echo
$qry_event1['email'];?>"></td>
</tr>
<tr>
<td align="right" valign="top"><? displayformlabel('notes','Notes:')?></td>
<td><textarea name="notes" style="width: 320px; height: 60px;"><? echo
$qry_event1['notes']; ?></textarea></td>
</tr>
<tr>
<td align="right"><? displayformlabel('venue','Venue:')?></td>
<td><input name="venue" size="50" maxlength="50" value="<? echo $qry_event1['venue'];?
>"></td>
</tr>
<tr>
<td align="right"><? displayformlabel('address','Address:')?></td>
<td><input name="address" size="50" maxlength="50" value="<?echo
$qry_event1['address'];?>"></td>
</tr>
<tr>
<td align="right"><? displayformlabel('city','City:')?></td>
<td><input name="city" size="50" maxlength="50" value="<?echo $qry_event1['city'];?
>"></td>
</tr>
<tr>
<td align="right"><? displayformlabel('state','State:')?></td>
<td><input name="state" size="3" maxlength="2" value="<?echo $qry_event1['state'];?
>"></td>
</tr>
<tr>
<td align="right"><? displayformlabel('lat','Latitude:')?></td>
<td><input name="lat" size="15" maxlength="15" value="<? echo $qry_event1['lat'];?>">
</td>
</tr>
<tr>
<td align="right"><? displayformlabel('lon','Longitude:')?></td>
<td><input name="lon" size="15" maxlength="15" value="<? echo $qry_event1['lon'];?>">
<span class="formnotes">Look up
coordinates using above address information.</span>
</td>
</tr>
<tr>
<td align="right"><? displayformlabel('accurate','Accurate:')?></td>
<td><input name="accurate" type="checkbox" value="1" <?php if
(isset($qry_event1['accurate'])) { echo 'checked="checked"'; }?>>
<a href="JavaScript:;" class="formnotes" onClick="window.open('<?php
print $vsf->self;?>?action=accuratehelp','helpwin','width=435,height=220');">Whats
this?</a>
</td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Submit"></td>
</tr>
</table>
</form>
Update page:
<?php
// updates a record in the database
// do validation (shared with update logic)
$id = $_REQUEST['id'];
$eventdate = $_REQUEST['eventdate'];
$throughdate = $_REQUEST['throughdate'];
$title = $_REQUEST['title'];
$website = $_REQUEST['website'];
$email = $_REQUEST['email'];
$notes = $_REQUEST['notes'];
$venue = $_REQUEST['venue'];
$address = $_REQUEST['address'];
$city = $_REQUEST['city'];
$state = $_REQUEST['state'];
$lat = $_REQUEST['lat'];
$lon = $_REQUEST['lon'];
$accurate = $_REQUEST['accurate'];
$errorwasthrown="";
$database = 'mapcal';
// database server
$dbsvr = 'localhost';
// username
$dbuser = 'root';
// password
$dbpass = 'usbw';
function db_connect() {
global $dbsvr,$dbuser,$dbpass,$database;
static $dbcon;
if ( ! $dbcon ) {
$dbcon = mysql_connect($dbsvr,$dbuser,$dbpass);
if (! mysql_select_db($database) ) {
die("Failure connecting to database - " . mysql_error());
}
}
}
if (! $eventdate ) {
adderrmsg('eventdate','Event date cannot be blank.');
$errorwasthrown=1;
}
else {
// else date wasn't blank, so validate it
if (! preg_match("/^\d\d\/\d\d\/\d\d$/",$eventdate) ) {
adderrmsg('eventdate',"Event date must be in format mm/dd/yy.");
$errorwasthrown=1;
}
}
if ($throughdate && ! preg_match("/^\d\d\/\d\d\/\d\d$/",$throughdate) ) {
adderrmsg('throughdate',"Through date must be in format mm/dd/yy.");
$errorwasthrown=1;
}
if (! $title ) {
adderrmsg('title','Title cannot be blank.');
$errorwasthrown=1;
}
if ($errorwasthrown) {
include('dsp_editevent.php');
}
else {
db_connect();
// format the date correctly for mysql
$dateparts = split("/",$eventdate);
$eventdate = "$dateparts[2]/$dateparts[0]/$dateparts[1]";
if ($throughdate) {
$dateparts = split("/",$throughdate);
$throughdate = "$dateparts[2]/$dateparts[0]/$dateparts[1]";
$throughdate = "'" . mysql_real_escape_string($throughdate) . "'";
}
else {
$throughdate = 'NULL';
}
// format event website if necessary
if ($website && ! preg_match("/:\/\//",$website) ) {
$website = "http://" . $website;
}
// update record in the database
$query = "UPDATE events SET ";
$query .= "eventdate = '" . mysql_real_escape_string($eventdate) . "', " .
"throughdate = " . $throughdate . ", " .
"title = '" . mysql_real_escape_string($title) . "', " .
"website = '" . mysql_real_escape_string($website) . "', " .
"email = '" . mysql_real_escape_string($email) . "', " .
"notes = '" . mysql_real_escape_string($notes) . "', " .
"venue = '" . mysql_real_escape_string($venue) . "', " .
"address = '" . mysql_real_escape_string($address) . "', " .
"city = '" . mysql_real_escape_string($city) . "', " .
"state = '" . mysql_real_escape_string($state) . "', " .
"lat = '" . mysql_real_escape_string($lat) . "', " .
"lon = '" . mysql_real_escape_string($lon) . "', " .
"accurate = '" . mysql_real_escape_string($accurate) . "' " .
"WHERE id = " . mysql_real_escape_string($id);
if ( ! mysql_query($query) ) {
exit("Query failed! - $query");
}
print "<p style='color: green'>Event <b>$title</b> was updated.</p>\n";
include('dsp_listevents.php');
} // close else ! errorwasthrown
?>
What i can see after printing the query is that it is not getting the value of id but all the fields from the form but why?
Keep the Id value in quotes.
"WHERE id = '" . mysql_real_escape_string($id)."'";