My account was suspended because of SPAM several times and my host provider told me to check my website security. May be my forms are not secured enough. Do you think that this form can be used to send spam?
Here is my code:
<script type="text/javascript">
$(document).ready(function () {
$('#form').ajaxForm({
beforeSubmit: validate
});
function validate(formData, jqForm, options) {
var name = $('input[name=name]').fieldValue();
var email = $('input[name=email]').fieldValue();
var company = $('input[name=company]').fieldValue();
var location = $('input[name=location]').fieldValue();
var phone = $('input[name=phone]').fieldValue();
var message = $('textarea[name=message]').fieldValue();
if (!name[0]) {
alert('Please enter your name');
return false;
}
if (!company[0]) {
alert('Please enter the name of your organization');
return false;
}
if (!email[0]) {
alert('Please enter your e-mail address');
return false;
}
if (!phone[0]) {
alert('Please enter your phone number');
return false;
}
if (!location[0]) {
alert('Please enter your location');
return false;
}
if (!message[0]) {
alert('Please enter your message');
return false;
}
else {
$("#form").fadeOut(1000, function () {
$(this).html("<img src='note.png' style='position: relative;margin: 0 auto;width: 500px;left: 20px;top: 30px;'/>").fadeIn(2000);
});
var message = $('textarea[name=message]').val('');
var name = $('input[name=name]').val('');
var email = $('input[name=email]').val('');
var phone = $('input[name=phone]').val('');
var company = $('input[name=company]').val('');
var location = $('input[name=location]').val('');
}
}
});
</script>
html:
<form id="form" method="post" name="form" action="send.php">
<input id="name" type="text" name="name"/>
<input id="company" type="text" name="company"/>
<input id="email" type="text" name="email"/>
<input id="phone" type="text" name="phone"/>
<input id="location" type="text" name="location"/>
<textarea name="message" id="message" rows="10"></textarea>
<input class="submit" type="submit" value="send" name="submit"></input>
</form>
php:
<?php
if($_POST){
$email = $_POST['email'];
$name = $_POST ['name'];
$company = $_POST ['company'];
$phone = $_POST ['phone'];
$location = $_POST ['location'];
$message = $_POST ['message'];
// response hash
$ajaxresponse = array('type'=>'', 'message'=>'');
try {
// do some sort of data validations, very simple example below
$all_fields = array('name', 'email', 'message');
filter_var($email, FILTER_VALIDATE_EMAIL);
foreach($all_fields as $field){
if(empty($_POST[$field])){
throw new Exception('Required field "'.ucfirst($field).'" missing input.');
}
}
// ok, if field validations are ok
// now Send Email, ect.
// let's assume everything is ok, setup successful response
$subject = "Someone has contacted you";
//get todays date
$todayis = date("l, F j, Y, g:i a") ;
$message = " $todayis \n
Attention: \n\n
Please see the message below: \n\n
Email Address: $email \n\n
Organization: $company \n\n
Phone: $phone \n\n
Location: $location \n\n
Name: $name \n\n
Message: $message \n\n
";
$from = "From: $email\r\n";
//put your email address here
mail("...#yahoo.com", $subject, $message, $from);
//prep json response
$ajaxresponse['type'] = 'success';
$ajaxresponse['message'] = 'Thank You! Will be in touch soon';
} catch(Exception $e){
$ajaxresponse['type'] = 'error';
$ajaxresponse['message'] = $e->getMessage();
}
// now we are ready to turn this hash into JSON
print json_encode($ajaxresponse);
exit;
}
?>
Many thanks!
Your form would actually be not safe against bots, because you dont got any captcha or something.
2 Options for you:
Captcha
Captcha -> you got something to fill in -> you probably know this!:)
https://www.google.com/recaptcha
Honeypot
Honeypot means, you are adding hidden fields in your form. And if those hidden fields have changed - you know that a BOT has entered content in your form. Aswell, this is better than Captchas, because your User doesnt has to fill in a Captcha
I would prefer Honeypot, because I don't like forms, where i have to fill in a Captcha once or even twice, when I failed or the captcha wasnt readable.
http://haacked.com/archive/2007/09/11/honeypot-captcha.aspx/
I have a simple approach to stopping spammers which is 100% effective, at least in my experience, and avoids the use of reCAPTCHA and similar approaches. I went from close to 100 spams per day on one of my sites' html forms to zero for the last 5 years once I implemented this approach.
another option is what I did is to use a hide field and put the time stamp on it and then compare to the time stamp on the PHP side, if it was faster than 15 seconds (depends on how big or small is your forms) that was a bot...
Taking clue from the suggestions above, I am just putting a ready code for you to use.
HTML
<form id="form" method="post" name="form" action="send.php">
<input id="name" type="text" name="name"/>
<input id="company" type="text" name="company"/>
<input id="email" type="text" name="email"/>
<input id="checkbot" type="hidden" name="timestamp" value="" />
<input id="phone" type="text" name="phone"/>
<input id="location" type="text" name="location"/>
<textarea name="message" id="message" rows="10"></textarea>
<input class="submit" type="submit" value="send" name="submit"></input>
</form>
Javascript
<script type="text/javascript">
$(document).ready(function () {
/*Set current time on the hidden field.*/
$('#checkbot').val($.now());
$('#form').ajaxForm({
beforeSubmit: validate
});
function validate(formData, jqForm, options) {
var name = $('input[name=name]').fieldValue();
var email = $('input[name=email]').fieldValue();
var company = $('input[name=company]').fieldValue();
var location = $('input[name=location]').fieldValue();
var phone = $('input[name=phone]').fieldValue();
var message = $('textarea[name=message]').fieldValue();
if (!name[0]) {
alert('Please enter your name');
return false;
}
if (!company[0]) {
alert('Please enter the name of your organization');
return false;
}
if (!email[0]) {
alert('Please enter your e-mail address');
return false;
}
if (!phone[0]) {
alert('Please enter your phone number');
return false;
}
if (!location[0]) {
alert('Please enter your location');
return false;
}
if (!message[0]) {
alert('Please enter your message');
return false;
}
else {
$("#form").fadeOut(1000, function () {
$(this).html("<img src='note.png' style='position: relative;margin: 0 auto;width: 500px;left: 20px;top: 30px;'/>").fadeIn(2000);
});
var message = $('textarea[name=message]').val('');
var name = $('input[name=name]').val('');
var email = $('input[name=email]').val('');
var phone = $('input[name=phone]').val('');
var company = $('input[name=company]').val('');
var location = $('input[name=location]').val('');
}
}
});
</script>
PHP
<?php
if($_POST){
$email = $_POST['email'];
$name = $_POST ['name'];
$company = $_POST ['company'];
$phone = $_POST ['phone'];
$location = $_POST ['location'];
$message = $_POST ['message'];
$checkbot = $_POST['timestamp'];
$time_diff = time() - $checkbot;
//If Time difference is less than 15 sec it's a bot
if($time_diff < 15){
exit;
}
// response hash
$ajaxresponse = array('type'=>'', 'message'=>'');
try {
// do some sort of data validations, very simple example below
$all_fields = array('name', 'email', 'message');
filter_var($email, FILTER_VALIDATE_EMAIL);
foreach($all_fields as $field){
if(empty($_POST[$field])){
throw new Exception('Required field "'.ucfirst($field).'" missing input.');
}
}
// ok, if field validations are ok
// now Send Email, ect.
// let's assume everything is ok, setup successful response
$subject = "Someone has contacted you";
//get todays date
$todayis = date("l, F j, Y, g:i a") ;
$message = " $todayis \n
Attention: \n\n
Please see the message below: \n\n
Email Address: $email \n\n
Organization: $company \n\n
Phone: $phone \n\n
Location: $location \n\n
Name: $name \n\n
Message: $message \n\n
";
$from = "From: $email\r\n";
//put your email address here
mail("...#yahoo.com", $subject, $message, $from);
//prep json response
$ajaxresponse['type'] = 'success';
$ajaxresponse['message'] = 'Thank You! Will be in touch soon';
} catch(Exception $e){
$ajaxresponse['type'] = 'error';
$ajaxresponse['message'] = $e->getMessage();
}
// now we are ready to turn this hash into JSON
print json_encode($ajaxresponse);
exit;
}
?>
In theory it can be used to send spam, because there are only checks if fields have values and as long the fields have a value, it does not care whether the input was human or a bot. You could improve the security by adding captcha codes (http://www.captcha.net/), to validate if an individual filling in your form is a human.
Try using this Spam Checker.
Useful program written in Java which looks up for spam IP Addresses using DNS lookups. Hope so it helps.
Related
My PHP username validation with Ajax duplicates my html page inside of html div(this is for showing ajax error) element. I tried some solutions and google it bu can't find anything else for solution. Maybe the problem is about the $_POST but I also separated them in php (all the inputs validation).
Here is PHP code
<?php
if(isset($_POST['username'])){
//username validation
$username = $_POST['username'];
if (! $user->isValidUsername($username)){
$infoun[] = 'Your username has at least 6 alphanumeric characters';
} else {
$stmt = $db->prepare('SELECT username FROM members WHERE username = :username');
$stmt->execute(array(':username' => $username));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if (! empty($row['username'])){
$errorun[] = 'This username is already in use';
}
}
}
if(isset($_POST['fullname'])){
//fullname validation
$fullname = $_POST['fullname'];
if (! $user->isValidFullname($fullname)){
$infofn[] = 'Your name must be alphabetical characters';
}
}
if(isset($_POST['password'])){
if (strlen($_POST['password']) < 6){
$warningpw[] = 'Your password must be at least 6 characters long';
}
}
if(isset($_POST['email'])){
//email validation
$email = htmlspecialchars_decode($_POST['email'], ENT_QUOTES);
if (! filter_var($email, FILTER_VALIDATE_EMAIL)){
$warningm[] = 'Please enter a valid email address';
} else {
$stmt = $db->prepare('SELECT email FROM members WHERE email = :email');
$stmt->execute(array(':email' => $email));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if (! empty($row['email'])){
$errorm[] = 'This email is already in use';
}
}
}
?>
Here is Javascript
<script type="text/javascript">
$(document).ready(function(){
$("#username").keyup(function(event){
event.preventDefault();
var username = $(this).val().trim();
if(username.length >= 3){
$.ajax({
url: 'register.php',
type: 'post',
data: {username:username},
success: function(response){
// Show response
$("#uname_response").html(response);
}
});
}else{
$("#uname_response").html("");
}
});
});
</script>
<input type="text" name="username" id="username" class="form-control form-control-user" placeholder="Kullanıcı Adınız" value="<?php if(isset($error)){ echo htmlspecialchars($_POST['username'], ENT_QUOTES); } ?>" tabindex="2" required>
<div id="uname_response" ></div>
Here is the screenshot:
form duplicate screenshot
The only code in your PHP file should be within the <?php ?> tags. You need to seperate your PHP code into another file.
So, I needed a contact form that can send emails with a "success" prompt that appears in my form, WITHOUT reloading. I have found PHPmailer that helps with sending mail to the inbox and not spam (this alone works fine, email sent straight to inbox). I then add the JS validation then AJAX, then the PHP that deals with the JSON response.
The "success" prompt appears when I click "send" (good!) but the problem is that no email has been sent/received. The code without the AJAX works fine on both my local and web hosts perfectly. How do I optimize this so the success prompt appears and the email is sent (inbox, ideally)?
No jQuery or any extra plugins please.
Thanks in advance.
HTML:
<div class="contact-form">
<form action="mail.php" method="POST" onsubmit="return doRegister()">
<input id="mail-name" type="text" name="name" placeholder="Your Name">
<span id="name-alert"></span>
<input id="mail-email" type="text" name="email" placeholder="Your Email">
<span id="email-alert"></span>
<input id="mail-subject" type="text" name="subject" placeholder="Your Subject">
<span id="subject-alert"></span>
<textarea id="mail-message" name="message" placeholder="Your Message"></textarea>
<span id="message-alert"></span>
<input type="submit" value="Send">
<input type="reset" value="Clear">
<span class="contact__form--alert-success" id="success-alert"></span>
</form>
</div>
JS:
function doRegister() {
let checks = {
name : document.getElementById("mail-name"),
email : document.getElementById("mail-email"),
subject : document.getElementById("mail-subject"),
message : document.getElementById("mail-message")
},
error = "";
if (checks.name.value=="") {
error += document.getElementById("name-alert").innerHTML+='<p>A name is required!</p>';
}
if (checks.subject.value=="") {
error += document.getElementById("subject-alert").innerHTML+='<p>A subject is required!</p>';
}
if (checks.message.value=="") {
error += document.getElementById("message-alert").innerHTML+='<p>A message is required!</p>';
}
let pattern = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (!pattern.test(checks.email.value.toLowerCase())) {
error += document.getElementById("email-alert").innerHTML+='<p>A valid email is required!</p>';
}
// Ajax
if (error!="") {
error="";
} else {
let data = new FormData();
for (let k in checks) {
data.append(k, checks[k].value);
}
let xhr = new XMLHttpRequest();
xhr.open('POST', "mail.php", true);
xhr.onload = function(){
let res = JSON.parse(this.response);
// SUCCESS!
if (res.status) {
document.getElementById("success-alert").innerHTML+='<p>Success!</p>';
} else {
// ERROR!
error = "";
for (let e of res['error']) {
error += e + "\n";
}
alert(error);
}
};
// SEND
xhr.send(data);
}
return false;
}
PHP:
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
$error = [];
$msg = '';
if ( array_key_exists( 'email', $_POST ) ) {
date_default_timezone_set( 'Etc/UTC' );
require 'mail/vendor/autoload.php';
// Call super globals from the contact form names
$email = $_POST['email'];
$name = $_POST['name'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$mail = new PHPMailer;
$mail->isSMTP();
$mail->Host = 'mail.host.com';
$mail->SMTPAuth = true;
$mail->Username = 'name#host.com';
$mail->Password = 'password1';
$mail->SMTPSecure = 'ssl';
$mail->Port = 465;
$mail->setFrom( 'name#host.com', 'New Message' );
$mail->addAddress( 'somemail#mail.com' );
if ($mail->addReplyTo($email, $name)) {
$mail->Subject = $subject;
$mail->isHTML(false);
$mail->Body = <<<EOT
Email: {$email}
Name: {$name}
Message: {$message}
EOT;
}
// Check inputs
if ($name=="") {
$error[] = "A name is required.";
}
if ($subject=="") {
$error[] = "A subject is required.";
}
if ($message=="") {
$error[] = "A message is required.";
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$error[] = "A valid email is required.";
}
// JSON encode with a response
echo json_encode([
"status" => count($error)==0 ? 1 : 0,
"error" => $error
]);
}
Solution:
the "send()" function was missing
if(empty($error)){
if(!$mail->send()){
$error[] = 'There was an error sending the mail. Please try again!';
}
}
Your PHP script doesn't send the mail because the send() function is not called, so after the validation, you should add something like:
if(empty($error)){
if(!$mail->send()){
$error[] = 'There was an error sending the mail. Please try again!';
}
}
echo json_encode([
"status" => count($error)==0 ? 1 : 0,
"error" => $error
]);
This way you're sending the mail and, if there was a problem(send() returns false), an error is being added to your error array.
have been a while since i posted last thanks, in advance for all your help in the past..i have a single email box with a submit button.
What i want to do is to check this email address to make sure its not empty, if it is to display a message and then ask user to enter the valid email address which i want to validate so that it is only hotmail and gmail accounts e.g. xyz#hotmail.com and xyz#gmail.com and nothing else..
my code below works ok to check for empty and does display alert message on screen but i do not know how to manpulate the email address check and if all is ok how to use the same one submit button to submit the valid email with thank u popup message after submissions..thanks in advance...singhy
ps: apologises in advance for any beginners mistake i have made ...sorry
<?php
if(isset($_POST['email'])) {
$to = 'xyz#hotmail.com';
$subject = '';
$email = $_POST['email_from'];
//$message = "LIST \r\n".
$message = "signoff list name \r\n";
}
$email_from = $_POST['email'];
// create email headers
$message = wordwrap($message, 100, "\r\n");
$headers = 'From: '.$email."\r\n".
'Reply-To: '.$email."\r\n" .
'X-Mailer: PHP/' . phpversion();
#mail($to, $subject, $message, $headers);
?>
<p>If you would like to receive our weekly newsletter email address below.</p>
<script type="text/javascript">
function IsEmpty(){
if(document.forms['isgtest'].email_from.value == "")
{
alert("Email field is empty, please enter email format");
return false;
}
//return submit "email_from.value";
(document.forms['test'].email_from.value == "subscribe")
//return .email_from.value == "";
//alert("thank u for joining the list !");
//return true;
}
</script>
<!--<script type="text/javascript"></script>-->
<form name="isgtest" class="rform" method="post" action="g.php">
<fieldset><legend>testing...</legend>
<label for="email_from"><span style="color: #ff0000;"><strong>*</strong>
</span>Email address:<input id="email_from" type="text" name="email_from" size="25" /> <input id="insert" id="btn" onclick="return IsEmpty();" style="float: right;" type="button" name="submit" value="Subscribe" /></fieldset>
</form>
If you are going for frontend validation (which should only be used to improve the user experience, never trust user input and always validate at the server side!), why not use the HTML5 features that exist for exactly that purpose. Something like this:
<form>
<label>Email:
<input type='email' pattern=".+(#gmail.com|#hotmail.com)" required />
</label>
<button type="submit">subscribe</button>
</form>
type=email makes sure only email addresses are accepted
required makes sure a value is provided before it can be submitted
pattern accepts a regex to which the input needs to comply before it can be submitted.
Personally I'm not a big fan of the default error messages my browser produces, but I'm even less of a fan of the alerts you are using, so...
If you insist on going the javascript way, I would advise something like this (pseudo code, untested):
function isEmpty(input) { ... }
function isEmail(input) { ... }
function isGmailOrHotmail(input) { ... }
function isValid(node) {
var value = node.value;
return ! isEmpty(value) && isEmail(value) && isGmailOrHotmail(value);
}
And then you could bind the isValid function to your submit button (preferably from your script file or block, but the inline onclick way should work as well)
<?php
$email_from = $_POST['email'];
$errors=array(); //track the errors as the script runs
function isValidEmail($addr) // Check for a valid email
{
return filter_var($addr, FILTER_VALIDATE_EMAIL) ? TRUE : FALSE;
}
if(!isValidEmail($email_from))$errors[]='Please enter a valid email address';
//Next, test for the email provider you wanted to filter by
$atPos=strpos($email_from,'#');//find the # symbol
$afterAt=substr($email_from,$atPos,strlen($email_from)-$atPos); //get everything after
$dotPos=strpos($afterAt,'.');
$domain=strtolower(substr($afterAt,0,$dotPos)); //get the typed domain, lowercase
if($domain!='hotmail'||$domain!='gmail')$errors[]='Email must be hotmail or gmail';
if(isset($_POST['email'])) {
if(count($errors)<0)
{
$to = 'xyz#hotmail.com';
$subject = '';
$email = $_POST['email_from'];
//$message = "LIST \r\n".
$message = "signoff list name \r\n";
// create email headers
$message = wordwrap($message, 100, "\r\n");
$headers = 'From: '.$email."\r\n".
'Reply-To: '.$email."\r\n" .
'X-Mailer: PHP/' . phpversion();
#mail($to, $subject, $message, $headers);
}
}// note that I changed the nesting to only trigger the mail on post
?>
<p>If you would like to receive our weekly newsletter email address below.</p>
<script type="text/javascript">
function IsEmpty(){
if(document.forms['isgtest'].email_from.value == "")
{
alert("Email field is empty, please enter email format");
return false;
}
//return submit "email_from.value";
(document.forms['test'].email_from.value == "subscribe")
//return .email_from.value == "";
//alert("thank u for joining the list !");
//return true;
}
</script>
<!--<script type="text/javascript"></script>-->
<?php
if(count($errors)>0)
{
foreach $errors as $e //Now tell the user what went wrong
{
echo "$e<br>"; // you can also use '' to enclose js tags and use alert
}
}
?>
<form name="isgtest" class="rform" method="post" action="g.php">
<fieldset><legend>testing...</legend>
<label for="email_from"><span style="color: #ff0000;"><strong>*</strong>
</span>Email address:<input id="email_from" type="text" name="email_from" size="25" /><input id="insert" id="btn" onclick="return IsEmpty();" style="float: right;" type="button" name="submit" value="Subscribe" /> </fieldset>
</form>
In the following code, I have a contact form and in that form there is an email validation script. As a result of validation, I want the error message to be shown in a div called confirmation without reloading the page. Also, if the email is valid, the mail will be sent and I want the Thank you message to be shown in the same div confirmation. The problem is what can I do to prevent reloading the page and let the error message or the thanks message shows in the confirmation div?
<html>
<body>
<?php
function spamcheck($field) {
// Sanitize e-mail address
$field=filter_var($field, FILTER_SANITIZE_EMAIL);
// Validate e-mail address
if(filter_var($field, FILTER_VALIDATE_EMAIL)) {
return TRUE;
} else {
return FALSE;
}
}
?>
<?php
if (!isset($_POST["submit"])) {
?>
<form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>">
From: <input type="text" name="from"><br>
Subject: <input type="text" name="subject"><br>
Message: <textarea rows="10" cols="40" name="message"></textarea><br>
<input type="submit" name="submit" value="Submit Feedback"><br>
<div id="confirmation" style="display:none" align="center"></div>
</form>
<?php
} else { // the user has submitted the form
// Check if the "from" input field is filled out
if (isset($_POST["from"])) {
// Check if "from" email address is valid
$mailcheck = spamcheck($_POST["from"]);
if ($mailcheck==FALSE) {
echo"
<script>
document.getElementById('confirmation').text ='invalid email';
</script>";
} else {
$from = $_POST["from"]; // sender
$subject = $_POST["subject"];
$message = $_POST["message"];
// message lines should not exceed 70 characters (PHP rule), so wrap it
$message = wordwrap($message, 70);
// send mail
mail("nawe11#gmail.com",$subject,$message,"From: $from\n");
echo"
<script>
document.getElementById('confirmation').text ='Thank you';
</script>";
}
}
}
?>
</body>
</html>
Thanks
<input type="text" name="from" id ="from">
Call example:
var request = $.ajax({
url: "file.php",
type: "POST",
data: { email : $('#from').val() }
});
request.done(function( msg ) {
//handle HTML
});
request.fail(function( jqXHR, textStatus ) {
//Handle problem at server side
});
PHP Side
<?php
$email = $_POST["email"]
function spamcheck($field) {
// Sanitize e-mail address
$field=filter_var($field, FILTER_SANITIZE_EMAIL);
// Validate e-mail address
if(filter_var($field, FILTER_VALIDATE_EMAIL)) {
return 'valid';
} else {
return 'no_valid';
}
}
echo spamcheck($email);
There's no way you could do that with just PHP.
What you're looking at is commonly known as AJAX, and uses client-side language (Javascript)
It's very common, and widely used on the internet. You can find many examples and production-ready scripts by searching ajax on google.
More informations here : http://www.w3schools.com/ajax/
I have an update password page that won't let me enter the actual current password for the current password field. Instead, it wants the hashed password. Once changed however, the new one is then hashed, which is a good thing. I just need to be able to enter the actual password and not hashed.
Yes I know, no md5; this is more for testing is all.
changepassword.js
<script>
function validatePassword() {
var currentPassword,newPassword,confirmPassword,output = true;
currentPassword = document.frmChange.currentPassword;
newPassword = document.frmChange.newPassword;
confirmPassword = document.frmChange.confirmPassword;
if(!currentPassword.value) {
currentPassword.focus();
document.getElementById("currentPassword").innerHTML = "required";
output = false;
}
else if(!newPassword.value) {
newPassword.focus();
document.getElementById("newPassword").innerHTML = "required";
output = false;
}
else if(!confirmPassword.value) {
confirmPassword.focus();
document.getElementById("confirmPassword").innerHTML = "required";
output = false;
}
if(newPassword.value != confirmPassword.value) {
newPassword.value="";
confirmPassword.value="";
newPassword.focus();
document.getElementById("confirmPassword").innerHTML = "not same";
output = false;
}
return output;
}
</script>
updatepassword.php
<?php
include 'core/login.php'; === this contains the connection, it's obviously good ===
include 'includes/head.php'; === changepassword.js is linked in the head ===
if(count($_POST)>0) {
$result = mysqli_query($link, "SELECT *from users WHERE id='" . $_SESSION["id"] . "'");
$row = mysqli_fetch_array($result);
if($_POST["currentPassword"] == $row["password"]) {
mysqli_query($link, "UPDATE users set `password`='" .md5(md5($_POST['newPassword'])) . "' WHERE id='" . $_SESSION["id"] . "'");
$message = "Password Changed";
} else $errormessage = "Current Password is not correct";
}
print_r($_SESSION);
?>
form on same page:
<div class="container">
<div class="text-center">
<h4>Change password below</h4>
</div><br />
<div class="message"><?php if(isset($message)) { echo $message; } ?></div>
<div class="message"><?php if(isset($errormessage)) { echo $errormessage; } ?></div>
<div class="col-md-4 col-md-offset-4">
<form name="frmChange" method="post" action="" onSubmit="return validatePassword()">
<div class="form-group">
<label>Current Password*</label>
<input type="text" name="currentPassword" class="form-control input-md" />
</div>
<div class="form-group">
<label>New Password*</label>
<input type="text" name="newPassword" class="form-control input-md" />
</div>
<div class="form-group">
<label>Confirm Password*</label>
<input type="text" name="confirmPassword" class="form-control input-md" />
</div>
<br />
<div class="text-center">
<input type="submit" name="submit" class="btn btn-success" value="Submit" />
</div>
</form>
</div>
</div>
Your problem is here:
if($_POST["currentPassword"] == $row["password"]) {
You are comparing the actual text version of the hash (say "password") to the hashed version of that password (say "213y789hwuhui1dh"). This evaluates out to:
if("password" == "213y789hwuhui1dh") {
Which obviously is never accurate. All you have to do to solve the problem is hash the password in the same way you did when you created it. If I understand your code properly, that should be:
if(md5(md5($_POST["currentPassword"]))==$row["password"]) {
SIDE NOTE ON SQL INJECTION
Please note that this code would be super easy to inject into. All a user would have to do is end the "currentPassword" POST value with '; SHOW DATABASE; and they would have unlimited access to your server's MySQL database. Consider learning to use MySQLi Prepared Statements. They are easy to understand, and easy to implement.
I went overboard. Your other question was closed. Juuuuust gonna leave this here... I'm using PHP version PHP 5.2.0.
http://php.net/manual/en/faq.passwords.php
http://php.net/manual/en/function.password-hash.php
http://php.net/manual/en/function.password-verify.php
<?php
// so I don't actually have to test form submission, too...
$_POST['current_password'] = 'Tacotaco';
$_POST['new_password'] = 'NINrocksOMG';
$_POST['confirmPassword'] = 'NINrocksOMG';
$_SESSION['id'] = 1;
// this is Tacotaco encrypted... update your db to test
// update users set password = '$2y$10$fc48JbA0dQ5dBB8MmXjVqumph1bRB/4zBzKIFOVic9/tqoN7Ui59e' where id=1
// the following is sooooo ugly... don't leave it this way
if (!isset($_SESSION['id']) or empty($_SESSION['id']) or
!isset($_POST['current_password']) or empty($_POST['current_password']) or
!isset($_POST['new_password']) or empty($_POST['new_password']) or
!isset($_POST['confirmPassword']) or empty($_POST['confirmPassword']) ) {
$message = 'Please enter your password';
}
else {
$sid = $_SESSION['id'];
$currpass = $_POST['current_password'];
$newpass = $_POST['new_password'];
$conpass = $_POST['confirmPassword'];
$message = validate_password($sid, $currpass, $newpass, $conpass);
}
print "<br/>$message<br/>";
function validate_password($sid, $currpass, $newpass, $conpass) {
$mysqli = mysqli_connect('localhost','root','','test')
or die('Error ' . mysqli_error($link));
$stmt = $mysqli->prepare('select id, password from users where id = ?');
$stmt->bind_param("s", $sid);
$stmt->execute();
$stmt->bind_result($userid, $userpass);
$message = '';
if ($stmt->fetch()) {
$stmt->close();
if (strlen($newpass) < 8) {
$message = 'Please enter a password with at least 8 characters';
}
elseif (!preg_match('`[A-Z]`', $newpass)) {
$message = 'Please enter at least 1 capital letter';
}
elseif ($newpass !== $conpass) {
$message = 'Your passwords do not match.';
}
else {
if (password_verify($currpass, $userpass)) {
$hashed_new = password_hash($newpass, PASSWORD_BCRYPT);
$query = 'update users set password = ? where id = ?';
$stmt_new = $mysqli->prepare($query);
$stmt_new->bind_param('ss', $hashed_new, $sid);
if ($stmt_new->execute()) {
$message = 'Password Changed';
}
else {
$message = $mysqli->error;
}
}
else $message = 'Current Password is not correct';
}
}
else {
$message = 'user not found for id $sid';
}
$mysqli->close();
return $message;
}
?>