I have the following email form:
<form action="mailer.php" method="post" name="form1" id="form1" onsubmit="MM_validateForm('from','','RisEmail','name','','R','verif_box','','R','message','','R');return document.MM_returnValue">
<table width="500" border="0" cellpadding="2" cellspacing="0" bgcolor="#000000"><tr valign="top" align="right"> <td nowrap><font face="Verdana" size="3" color="#666666" >first name (<span class="R">*</span>)</font></td>
<td width="500" align="left"><input type="text" name="name" size="37" border="0" id="name" value="<?php echo $_GET['name'];?>"> </td></tr><tr valign="top" align="right"> <td nowrap><font face="Verdana" size="3" color="#666666">last name</font></td>
<td align="left"><input type="text" name="lastname" size="37" border="0" id="lastname" value="<?php echo $_GET['lastname'];?>"> </td></tr><tr valign="top" align="right"> <td nowrap><font face="Verdana" size="3" color="#666666">email (<span class="R">*</span>)</font></td>
<td align="left"><input type="text" name="from" size="37" border="0" id="from" value="<?php echo $_GET['from'];?>"> </td>
</tr><tr valign="top" align="right"> <td nowrap><font face="Verdana" size="3" color="#666666"></font></td>
<td align="left"><input type=checkbox name="mailinglist" id="mailinglist" value="<?php echo $_GET['mailinglist'];?>"><font face="Verdana" size="3" color="#666666"></font><br> </td></tr><tr valign="top" align="right"> <td nowrap><font face="Verdana" size="3" color="#666666">comments (<span class="R">*</span>)</font></td>
<td align="left"><textarea name="message" cols="35" rows="10" border="0" id="message"><?php echo $_GET['message'];?></textarea><br> </td></tr><tr> <td colspan="2"><table cellpadding=5 cellspacing=0 bgcolor="#000000" width="100%"><tr bgcolor="#000000">
<td class="label" colspan="2"><font color="#cccccc" face="Verdana" size="2"><b>Image Verification</b></font></td></tr><tr>
<td> <input name="verif_box" type="text" id="verif_box" style="padding:2px; border:1px solid #CCCCCC; width:80px; height:14px;"/> <img src="verificationimage.php?<?php echo rand(0,9999);?>" alt="verification image, type it in the box" width="50" height="24" align="top" /><br />
<br />
<!-- if the variable "wrong_code" is sent from previous page then display the error field -->
<?php if(isset($_GET['wrong_code'])){?>
<div style="border:1px solid #990000; background-color:#D70000; color:#FFFFFF; padding:4px; padding-left:6px;width:295px;">Wrong verification code</div><br />
<?php }?>
</td><td class="field" valign="bottom">
<div><input name="Submit" type="submit" style="margin-top:10px; display:block; border:1px solid #000000; width:100px; height:20px;font-family:Verdana, Arial, Helvetica, sans-serif; font-size:11px; padding-left:2px; padding-right:2px; padding-top:0px; padding-bottom:2px; line-height:14px; background-color:#EFEFEF;" value="Send Message"/>
<input type="reset" class="btn" value=" clear " name="Clear" border="0" style="margin-top:10px; display:block; border:1px solid #000000; width:100px; height:20px;font-family:Verdana, Arial, Helvetica, sans-serif; font-size:11px; padding-left:2px; padding-top:0px; padding-bottom:2px; line-height:14px; background-color:#EFEFEF;">
</td></tr></table></td></tr></table></form>
and the following code in my mailer.php
// check to see if verificaton code was correct
if(md5($verif_box).'a4xn' == $_COOKIE['tntcon']){
// if verification code was correct send the message and show this page
mail("myemail#gmail.com", 'Online Form: '.$subject, "\n".$message." \n\n".$name."\n\n".$lastname."\n\n".$from."\n\n".$_SERVER['REMOTE_ADDR']."\n\n".'mailinglist: '.$mailinglist, "From: $from");
// delete the cookie so it cannot sent again by refreshing this page
setcookie('tntcon','');
} else if(isset($message) and $message!=""){
// if verification code was incorrect then return to contact page and show error
header("Location: http://{$_SERVER['HTTP_HOST']}".dirname($_SERVER['PHP_SELF'])."contactform.php?subject=$subject&email=$email&message=".urlencode($message)."&wrong_code=true");
exit;
} else {
echo "no variables received, this page cannot be accessed directly";
exit;
}
?>
For some reason I receive emails when the verification code is correct, but the "wrong code warning" will not show up when the wrong verification code is entered.
Can someone help me please? I am new to php and it has taken me a long time just to get this to work. When the wrong verification code is entered, all that happens is that a blank mailer.php is called in the browser.
**sorry, not sure why the code copied in so many different windows.
The best idea would be to actually put the contents of mailer.php inside of contactform.php, so you wont need any redirects, no URL full of variables, no nothing.
The outcome of this would be something along the lines of:
<?php
$state = 0;
// check to see if verificaton code was correct
if(md5($verif_box).'a4xn' == $_COOKIE['tntcon']){
// if verification code was correct send the message and show this page
mail("myemail#gmail.com", 'Online Form: '.$subject, "\n".$message." \n\n".$name."\n\n".$lastname."\n\n".$from."\n\n".$_SERVER['REMOTE_ADDR']."\n\n".'mailinglist: '.$mailinglist, "From: $from");
// delete the cookie so it cannot sent again by refreshing this page
setcookie('tntcon','');
$state = 2;
} else if(isset($message) and $message!=""){
// if verification code was incorrect then return to contact page and show error
$state = 1;
}
if ($state == 0) { ?>
<form action="" method="post" name="form1" id="form1" onsubmit="MM_validateForm('from','','RisEmail','name','','R','verif_box','','R','message','','R');return document.MM_returnValue">
<!-- All the form that I dont want to copy paste... -->
</form>
<?php } else if ($state == 1) { ?>
Message for wrong verification code.
<?php } else if ($state == 2) { ?>
Message for email sent.
<?php } ?>
I changed the forms target attribute so it doesnt go to mailer.php and changed the opening php a bit to make it work with this distribution of things. You should change the input code to populate it with the POST data, instead of GET and you would avoid having that nasty looking URL.
In mailer.php, do this:
// check to see if verificaton code was correct
if (md5($verif_box).'a4xn' == $_COOKIE['tntcon']) {
// if verification code was correct send the message and show this page
mail("myemail#gmail.com", 'Online Form: '.$subject, "\n".$message." \n\n".$name."\n\n".$lastname."\n\n".$from."\n\n".$_SERVER['REMOTE_ADDR']."\n\n".'mailinglist: '.$mailinglist, "From: $from");
// delete the cookie so it cannot sent again by refreshing this page
setcookie('tntcon','');
} else if (isset($message) && $message != "") {
// if verification code was incorrect then return to contact page and show error
exit("<html><head><title>Redirect</title><meta http-equiv=\"refresh\" content=\"0;contactform.php?subject=$subject&email=$email&message=".htmlspecialchars(urlencode($message))."&wrong_code=true\" /></head><body>You should be redirected, if you aren't click here.</body></html>");
} else exit("no variables received, this page cannot be accessed directly");
Related
Hey Guys this should be probably really simple I am just missing a step.
So I have a form and I want to make sure all values are added before moving to the next page that processes my values and sends them to my email. I also have error messages if someone does not add a value. The error messages display on the reloading of the page.
The problem I have is that you have to reload the page for the Superglobal Post to contain any values. For some reason it does not add them until the page is reloaded. So what happens is if you fill all 5 input fields you have to reload the page, and then submit again for it to send it to my send_form_email.php script because at that point the values are added. I want it to logically reload if any of the values are empty (which will display error messages telling the user that the input field must have content), and automatically send the user to send_form_email.php if all values have been correctly added.
It's almost pull my hair out so if someone could help me understand what piece of the puzzle I am missing I would be so grateful!
<form name="contactform" method="post" action="<?php echo $value; ?>">
<table width="450px">
<tr>
<td valign="top">
</td>
<td valign="top">
<input class="inputs" placeholder="firstname" type="text" name="first_name" maxlength="50" size="30" placeholder="name"><br>
<span class="error">* <?php echo $firstErr;?></span>
</td>
</tr>
<tr>
<td valign="top">
</td>
<td valign="top">
<input class="inputs" placeholder="lastname" type="text" name="last_name" maxlength="50" size="30">
<span class="error">* <?php echo $lastErr;?></span>
</td>
</tr>
<tr>
<td valign="top">
</td>
<td valign="top">
<input class="inputs" placeholder="email" type="text" name="email" maxlength="80" size="30">
<span class="error">* <?php echo $emailErr;?></span>
</td>
</tr>
<tr>
<td valign="top">
</td>
<td valign="top">
<input class="inputs" placeholder="telephone" type="text" name="telephone" maxlength="30" size="30">
<span class="error">* <?php echo $telephoneErr;?></span>
</td>
</tr>
<tr>
<td valign="top">
</td>
<td valign="top">
<textarea class="inputs" placeholder="comments" name="comments" maxlength="1000" cols="25" rows="6"></textarea>
<span class="error">* <?php echo $commentsErr;?></span>
</td>
</tr>
<tr>
<td colspan="2" style="text-align:center">
<input type="submit" value="Submit" style="background-color: #0F6D87;
font-family: Exo-Light;
color: #000000;
width: 75px;
font-weight: bold;
border-color: #003D69;
border-style: outset;
font-size: .8em;
box-shadow: 2px 2px 2px rgba(0, 34, 97, 0.6);">
<INPUT TYPE="RESET">
</td>
</tr>
</table>
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST"){
if (!empty($_POST["first_name"]) && !empty($_POST["last_name"]) && !empty($_POST["email"]) && !empty($_POST["telephone"]) && !empty($_POST["comments"])) {
$value ="http://cdubach.com/inc/send_form_email.php";
} elseif (empty($_POST["first_name"]) || empty($_POST["last_name"]) || empty($_POST["email"]) || empty($_POST["telephone"]) || empty($_POST["comments"])){
$value = "#";
}
}
$first_name = $_POST['first_name']; // required
$last_name = $_POST['last_name']; // required
$email_from = $_POST['email']; // required
$telephone = $_POST['telephone']; // not required
$comments = $_POST['comments']; // required
echo $_POST['submit'] . " = Submit <br>";
echo $_POST["first_name"] . " = First Name <br>";
echo $_POST["last_name"] . " = Last Name <br>";
echo $_POST["email"] . "= Email <br>";
echo $_POST["telephone"] . "= Telephone <br>";
echo $_POST["comments"] . "= Comments <br>";
echo var_dump($_Post) . "= Dump <br>";
echo $value . " = Value <br>" ;
echo $_SERVER["PHP_SELF"];
header('Content-Type: text/plain');
var_dump(htmlspecialchars("<a href='test'>Test</a>", ENT_QUOTES, 'UTF-8'));
echo "<br>";
echo htmlspecialchars("<a href='test'>Test</a>", ENT_XHTML, 'UTF-8');
echo "<br>";
$str = "A 'quote' is <b>bold</b>";
/* */
//convert from utf8
$str = utf8_decode($str);
//translate HMTL entities
$trans = get_html_translation_table(HTML_ENTITIES);
$str = strtr($str, $trans);
echo htmlspecialchars($str);
echo "<br>";
echo htmlentities($str, ENT_QUOTES);
$new = htmlspecialchars("<a href='test'>Test</a>", ENT_QUOTES);
echo $new; // <a href='test'>Test</a>
if ($_SERVER["REQUEST_METHOD"] == "POST") {
//Check First Name Field if Nothing Post Error
if (empty($_POST["first_name"])) {
$firstErr = "Name is required";
} else {
$firstErr = test_input($_POST["name"]);
}
//Check Last Name Field if Nothing Post Error
if (empty($_POST["last_name"])) {
$lastErr = "Last Name is required";
} else {
$lastErr = test_input($_POST["last_name"]);
}
//Check Email Field if Nothing Post Error
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$emailErr = test_input($_POST["email"]);
}
//Check Telephone Field if Nothing Post Error
if (empty($_POST["telephone"])) {
$telephoneErr = "Telephone is Required";
} else {
$telephoneErr = test_input($_POST["telephone"]);
}
//Check Comments Field if Nothing Post Error
if (empty($_POST["comments"])) {
$commentsErr = "Comments is Required";
} else {
$commentsErr = test_input($_POST["comments"]);
}
//Check Comments
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
The reason you need to reload a second time in order for the script to work is because the action property of the form is not populated on the first run (since $value is not set), on the 2nd run however it is (if the $_POST pass the checks you have set) and is set to http://cdubach.com/inc/send_form_email.php.
You will see this if you check the actual html code in the first and second run.
However this is only one of the problems with your script. Some hints:
remove the header('Content-Type: text/plain');, that line instructs the browser to treat the page as text and it will not render it as html.
move the whole html after your PHP script - that way the errors messages you have prepared will work as they should
finally to resolve your problem with "$_POST only if all ok" condition check the validity of the script with client side JavaScript. On another hand if you have access over the called script (the one that $value points to) you could make the check there and redirect to the form if you should.
I have been trying to improve our contact forms with php validation, I can get the form to be validated and show errors when each field is not filled in correctly, success message appears when the form is completed and validated correctly, and an email is sent to me with the information from the form.
My problem is that I can not get the header('location'...) part of the code to work. Rather than just having "Form has been submitted successfully" appear underneath the form once submitted, I would like it to go to a "Thank You" page instead.
Here is my code:
This is this my form page:
<?php
include('validate.php');
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>TEST</title>
<style>
input, textarea {font-size: 1em;}
p.error {background: #ffd; color: red;}
p.error:before {content: "Error:";}
p.success {background: #ffd; color: green;}
p.success:before {content: "Success:";}
p.error, p.success {font-weight: bold;}
</style>
</head>
<body>
<h2>Please fill up the form below and submit.</h2>
<?=$error?>
<form action="html_form_to_validate.php" method="post">
<table>
<tr>
<td>Name: </td>
<td>
<input type="text" name="name" placeholder="Name *(Required)" value="<?=#$name?>"/> </td>
</tr>
<tr>
<td>Company: </td>
<td><input type="text" name="company" placeholder="Company" value="<?=#$company?>"/> </td>
</tr>
<tr>
<td>Hear: </td>
<td><input type="text" name="hear" placeholder="How did you hear about us?" value="<?=#$hear?>"/></td>
</tr>
<tr>
<td>Email: </td>
<td><input type="text" name="email" value="<?=#$email?>"/></td>
</tr>
<tr>
<td>Phone: </td>
<td><input type="text" name="phone" value="<?=#$phone?>"/></td>
</tr>
<tr>
<td>Message: </td>
<td><textarea name="comments"><?=#$comments?></textarea></td>
</tr>
</table>
<input type="submit" name="submit" value="Submit"/> <input type="reset" name="reset" value="Reset"/>
</form>
<?php
if (isset($_POST['submit']) && $error == '') { // if there is no error, then process further
echo "<p class='success'>Form has been submitted successfully.</p>"; // showing success message
$name=$_POST['name'];
$company=$_POST['company'];
$telephone=$_POST['telephone'];
$email=$_POST['email'];
$hear=$_POST['hear'];
$comments=$_POST['comments'];
$to="chris#example.com";
$subject="Request for information";
$from="sales#example.com";
$message="<html>
<body topmargin='0'>
<div align='center'>
<table border='0' width='736' id='table1' cellspacing='0' cellpadding='0'>
<tr>
<td height='129' bgcolor='#EDEDE9' width='736' valign='top' style='margin-left: 10'>
<table border='0' id='table2' cellspacing='10' cellpadding='15' width='726'>
<tr>
<td width='676' valign='top' bgcolor='#FFFFFF'>
<p align='left'>
<img border='0' src='http://www.example.com/images/logo.png' align='left' hspace='0'> </p>
<p align='left'>
<br><br>
<b>
<font face='Verdana' color='#0078c1' style='font-size: 20pt'>
Request for information</font></b></p>
<p align='left'> </p>
</td>
</tr>
<tr>
<td width='676' valign='top' bgcolor='#FFFFFF'>
<p>
<font face='Verdana' size='2'>The following person has been on <a href='http://www.example.com'>
<font color='#0078c1'>www.example.com</font></a> and requesting information from our 'contact form'.</font></p>
<p>
<font face='Verdana' size='2'>Name: </font><font face='Verdana' size='2'><b>$name</b> </font></p>
<p>
<font face='Verdana' size='2'>Company: </font><font face='Verdana' size='2'><b>$company</b></font></p>
<p>
<font face='Verdana' size='2'>Telephone: <font face='Verdana' size='2'><b>$telephone</b></font></p>
<p>
<font face='Verdana' size='2'>Email: <font face='Verdana' size='2'><b>$email</b></font></p>
<p>
<font face='Verdana' size='2'>Heard about us from: </font><font face='Verdana' size='2'><b>$hear</b></font></p>
<p>
<font face='Verdana' size='2'>Message: <font face='Verdana' size='2'><b>$comments</b></font></p>
</td>
</tr>
</table>
</td>
</tr>
</table>
</div>
</body>
</html>
";
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
$headers .= "From: $from\r\n";
#mail($to, $subject, $message, $headers);
header('Location: http://www.example.com/contact/thank-you.php');
}
?>
</body>
</html>
And my validate.php file:
<?php
$error = ""; // Initialize error as blank
if (isset($_POST['submit'])) { // check if the form is submitted
#### removing extra white spaces & escaping harmful characters ####
$name = trim($_POST['name']);
$company = trim($_POST['company']);
$hear = trim($_POST['hear']);
$email = $_POST['email'];
$phone = $_POST['phone'];
$comments = $_POST['comments'];
#### start validating input data ####
#####################################
# Validate Name #
// if name is not 3-20 characters long, throw error
if (strlen($name) < 3 OR strlen($name) > 20) {
$error .= '<p class="error">Name should be within 3-20 characters long.</p>';
}
# Validate Email #
// if email is invalid, throw error
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { // you can also use regex to do same
$error .= '<p class="error">Enter a valid email address.</p>';
}
# Validate Phone #
// if phone is invalid, throw error
if (!ctype_digit($phone) OR strlen($phone) < 9) {
$error .= '<p class="error">Enter a valid telephone number.</p>';
}
# Validate Comments #
if (strlen($comments)==0 OR strlen($comments)>240) {
$error .= '<p class="error">Please enter your message less than 240 characters.</p>';
}
#### end validating input data ####
#####################################
}
I am a novice and have used scripts from other places to do what I wanted to do - so be nice lol
Thanks
Chris
I personally love this method...
echo '<meta http-equiv="refresh" content="0;URL=www.mylink.com" />';
In my PHP code I always use header("refresh:0;url=the_url_here"); instead of header('Location: url');.
Try it, maybe it works to you.
Validation and redirect needs to happen before any output to the browser, so you need to place header function before showing form.
Or if you must do redirect after form you can use javascript redirect instead of PHP.
<script>
// just redirect
window.location='http://your-site.dev/new-url.php'
// or redirect after showing form
setTimeout(function () {
window.location.href = 'http://your-site.dev/new-url.php';
}, 2000); //will call the function after 2 secs.
</script>
I have a web form where the user is required to enter information for the following fields: Full Name, Contact Number and Best Time to Call. Once these fields have been filled the user will submit the form and the data is then added to the database however, my issue right now is that my web form is ignoring the validation i have set and allowing the user to submit a blank web form. I am not sure if it may be the way i have structured my code? nevertheless, how can i resolve this?
PHP
<?php
require_once($_SERVER['DOCUMENT_ROOT'].'/inc/bootstrap.php');
include("config/cn.php");
$template['template']="page";
// define variables and set to empty values
$nameErr = $contactErr = $callErrErr = "";
$full_name = $contact_number = $best_time_to_call = "";
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["full_name"]))
{$nameErr = "Full name is required";}
else
{$full_name = test_input($_POST["full_name"]);}
if (empty($_POST["contact_number"]))
{$contactErr = "Contact number is required";}
else
{$contact_number = test_input($_POST["contact_number"]);}
if (empty($_POST["best_time_to_call"]))
{$callErr = "Must not be left blank";}
else
{$best_time_to_call = test_input($_POST["best_time_to_call"]);}
$enter_sql = "INSERT INTO contact (full_name,contact_number,best_time_to_call) VALUES('$full_name','$contact_number','$best_time_to_call')";
/*print($enter_sql);*/
$enter_query = mysql_query($enter_sql) or die(mysql_error());
header('Location: /thankyou.php');
exit;
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
HTML
<form name="frmContact" id="frmCallContact" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<table width="100%" border="0" cellspacing="1" cellpadding="0" class="TableFormat">
<tr><th align="left" valign="top" colspan="2">Call me back</th></tr>
<tr><td align="right" valign="top">Full Name:</td>
<td><input type="text" name="full_name" id="full_name" style="width:250px;" title="Please enter your full name"/><span class="error">* <?php echo $nameErr;?></span></td></tr>
<tr>
<td align="right" valign="top">Contact Number:</td>
<td><input type="text" name="contact_number" id="contact_number" style="width:250px;" />
<span class="error">*<?php echo $contactErr;?></span></td>
</tr>
<tr>
<td align="right" valign="top">Best Time to Call:</td>
<td><input type="text" name="best_time_to_call" id="best_time_to_call" style="width:250px;" title="Please enter your best time to call"/>
<span class="error">*<?php echo $callErr;?></span></td>
</tr>
<tr>
<td align="right" valign="top"> </td>
<td><!--<a name="submit" href="#"><img src="/img/bn_submit.png" width="93" height="28" /></a>--><input type="submit" name="Submit" value="Submit">
</tr>
</table>
</form>
$myflag = true; //create a flag
1.
if (empty($_POST["full_name"]))
{
echo $nameErr = "Full name is required"; // echo the error
$myflag = false; //change status of flag
}
2.
if ( $myflag )
{
//if flag is true then insert data;
$enter_sql = "INSERT INTO contact (full_name,contact_number,best_time_to_call) VALUES('$full_name','$contact_number','$best_time_to_call')";
}
3.you are vulnerable to SQL injection if the data is directly inserted into database from a user
I am trying to change the password from the user logged in. On the page it says the password was changed, but it does not change, not on the database and not at all. I have trying logging in with the new password, but just the old one remains to login. I did refreshed the page and everything. I am trying this for a couple of days and I wonder if someone would kindly spot my error. Tonight I thought it could be because the password is encrypted with md5 on the database. How would I proceed as I already tried a few things and do not work.
error_reporting(E_ALL); ini_set("display_errors","On");
<?php include "includes/connection.php" ?>
<?php
session_start();
if(#$_REQUEST["Submit"]=="Update")
{
$sql="update users set password ='$_REQUEST[newpassword]' where user='$_SESSION[myusername]'";
if (!mysql_query($sql)) die('err: PROBLEM IN QUERY: '.mysql_error());
header("Location:changpass.php?msg=updated");
}
else
die('err: PROBLEM IN REQUEST');
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD><TITLE>Change password</TITLE>
<script language="javascript" type="text/javascript">
function validate()
{
var formName=document.frm;
if(formName.newpassword.value == "")
{
document.getElementById("newpassword_label").innerHTML='Please Enter New Password';
formName.newpassword.focus();
return false;
}
else
{
document.getElementById("newpassword_label").innerHTML='';
}
if(formName.cpassword.value == "")
{
document.getElementById("cpassword_label").innerHTML='Enter ConfirmPassword';
formName.cpassword.focus();
return false;
}
else
{
document.getElementById("cpassword_label").innerHTML='';
}
if(formName.newpassword.value != formName.cpassword.value)
{
document.getElementById("cpassword_label").innerHTML='Passwords Missmatch';
formName.cpassword.focus()
return false;
}
else
{
document.getElementById("cpassword_label").innerHTML='';
}
}
</script>
<style type="text/css">
<!--
.style1 {font-weight: bold}
.style7 {
color: yellow;
font-size: 24px;
}
.style9 {
color: #FF6666;
font-weight: bold;
}
.style12 {
color: #666666;
font-weight: bold;
}
.style14 {color: #CC0033; font-weight: bold; }
-->
</style>
<META http-equiv=Content-Type content="text/html; charset=windows-1252">
</HEAD>
<BODY>
<form action="changpass.php" method="post" name="frm" id="frm" onSubmit="return validate();">
<table width="47%" border="1" cellspacing="0" cellpadding="0">
<tr>
<td colspan="2" align="center"></td>
</tr>
<tr bgcolor="#666666">
<td colspan="2"><span class="style7">Change Password</span></td>
</tr>
<?php if(isset($_REQUEST['msg']) && $_REQUEST['msg'] == 'updated') { ?>
<tr bgcolor="#666666">
<td colspan="2"><span class="style7">Password has been changed successfully.</span></td>
</tr>
<?php } ?>
<tr>
<td bgcolor="#CCCCCC"><span class="style14">New Password:</span></td>
<td bgcolor="#CCCCCC"><input type="password" name="newpassword" id="newpassword" size="20" autocomplete="off"/> <label id="newpassword_label"
class="level_msg"></td>
</tr>
<tr>
<td bgcolor="#CCCCCC"><span class="style14">Confirm Password:</span></td>
<td bgcolor="#CCCCCC"><input type="password" name="cpassword" id="cpassword" size="20" autocomplete="off"> <label id="cpassword_label"
class="level_msg"></td>
</tr><tr bgcolor="#666666"><td colspan="2" align="center"><input type="submit" name="Submit" value="Update" /></td>
</tr></table>Home</form></BODY></HTML>`
I enhanced your code:
<?php
if ($_REQUEST['Submit'] == "Update")
{
$sql = "UPDATE `users` SET `password`='".$_REQUEST['newpassword']."' WHERE `user`='".$_SESSION['myusername']."'";
mysql_query($sql);
header("Location: changpass.php?msg=updated");
exit;
}
?>
To use this code make sure following:
1) You are having correct Submit button, example is following:
<input type="submit" name="Submit" value="Update" />
2) You are having correct password field, example is following:
<input type="password" name="newpassword" value="" />
3) Session has to be set under key myusername
4) Make sure your table fields and names are okay. Do more debugging.
If this still won't solve, add form code for further investigation.
EDIT
Here is interpretation of this code with for some basic debugging purposes that might help:
<?php
if (isset($_REQUEST['Submit']) && $_REQUEST['Submit'] == "Update")
{
if (!isset($_SESSION['myusername'])) trigger_error("DEBUG: SESSION VARIABLE IS NOT SET");
if (!isset($_REQUEST['newpassword']) || empty($_REQUEST['newpassword'])) trigger_error("DEBUG: NEW PASSWORD IS NOT GIVEN");
$sql = "UPDATE `users` SET `password`='".mysql_real_escape_string($_REQUEST['newpassword'])."' WHERE `user`='".mysql_real_escape_string($_SESSION['myusername'])."'";
$qw = mysql_query($sql);
if (!$qw) trigger_error("DEBUG: MYSQL RESPONDED WITH ERROR - ".mysql_error());
header("Location: changpass.php?msg=updated");
exit;
}
?>
UPDATE: Debugging step #1
Change a code in your php file to this and tell us if any error messages show up.
if(#$_REQUEST["Submit"]=="Update")
{
$sql="update users set password ='$_REQUEST[newpassword]' where user='$_SESSION[myusername]'";
if (!mysql_query($sql)) die('err: PROBLEM IN QUERY: '.mysql_error());
header("Location:changpass.php?msg=updated");
}
else
die('err: PROBLEM IN REQUEST');
I am trying to add ReCaptcha into a mail form that I created which is intended for sharing content,
but for some reason the captcha is not being validated when I hit "submit", meaning that even if you enter a wrong text in the captcha, the form will still send the email.
I am using joomla 2.5.8, the recaptcha plugin is enabled (although I don't think it is being intialized since I added the recaptchalib.php myself and I am including the ref to the publickey and privatekey inside the mail form code).
Any help would be very much appreciated!
Thank you!!
here is the code:
<?php require_once('recaptchalib.php'); ?>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script language="javascript" type="text/javascript">
function validateEmail($email)
{
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if( !emailReg.test( $email ) )
{
return false;
}
else
{
return true;
}
}
function validateForm()
{
var form = document.mailForm;
if (form.recipient.value == "" || validateEmail(form.recipient.value)==false)
{
alert("bad email");
return false;
}
if (form.subject.value == "")
{
alert("please enter subject");
return false;
}
if (form.content.value == "")
{
alert("please enter massage");
return false;
}
<?php
$privatekey = "privatekey";
$resp = recaptcha_check_answer($privatekey,$_SERVER["REMOTE_ADDR"],$_POST["recaptcha_challenge_field"],$_POST["recaptcha_response_field"]); ?>
if (!$resp->is_valid)
{
alert("try again");
return false;
}
return true;
}
</script>
<?php
if($this->success=='1')
{
echo JText::_('MAIL_SEND_SUCCESSFULLY');
}
elseif($this->success=='0')
{
echo JText::_('MAIL_SEND_FAILED');
}
?>
<div id="SendMail">
<h2>send mail</h2>
<form action="index.php" name="mailForm" method="post" onsubmit="return validateForm()">
<table>
<tr>
<td><label><?php echo JText::_('MAIL_SEND_TO'); ?>:</label></td>
<td><input type="text" name="recipient" size="25" value=""/></td>
</tr>
<tr>
<td><label><?php echo JText::_('MAIL_SUBJECT'); ?>:</label></td>
<td><input type="text" name="subject" size="25" value=""/></td>
</tr>
<tr>
<td><label><?php echo JText::_('MAIL_MESSAGE'); ?>:</label></td>
<td>
<textarea name="content" rows="10" cols="40"></textarea>
<br/><?php echo JText::_('MAIL_DESC'); ?>
</td>
<tr>
<td><?php $publickey = "public key"; ?></td>
<td><?php echo recaptcha_get_html($publickey);?></td>
</tr>
</table>
<p>
<input type="hidden" name="controller" value="mail" />
<input type="hidden" name="task" value="sendMail" />
<div class="button-mail">
<input style="width: 50px;height: 25px;" type="submit" name="submit" value="<?php echo JText::_('SEND'); ?>"/>
<a href="javascript: void window.close()" title="Close Window"><span style="color: #444;
border: #D5D5D5 1px solid; padding: 4px; width: 50px;height: 25px;"><?php echo JText::_('CLOSE'); ?></span></a>
</div>
</p>
</form>
</div>
You have error in the code. Please look this lne
if (!$resp->is_valid)
{
alert("try again");
return false;
}
Where $resp->is_valid is the PHP but executed as JS.
Correct code would be
if (!<php (int)$resp->is_valid;?>)
{
alert("try again");
return false;
}
But it will not work anyway because of 2.
You cannot check recaptcha code in Javascript validation. It should be checked server side. Or if you want to check with javascript it should be checked with AJAX request to server. That is because you code
<?php
$privatekey = "privatekey";
$resp = recaptcha_check_answer($privatekey,$_SERVER["REMOTE_ADDR"],$_POST["recaptcha_challenge_field"],$_POST["recaptcha_response_field"]); ?>
is executed on form load before even user eneter captcha.