Sending a few php variables in email triggered by javascript - javascript

i want to send a few php variables by a trigger from javascript. The variables, databases and the script is working but i cant figure our the PHP part.
This is what I think the PHP should be like but its obviously faulit. i just want to send the few variables.
if{
$mail = new PHPMailer;
$mail->isSMTP();
//Enable SMTP debugging
// 0 = off (for production use)
// 1 = client messages
// 2 = client and server messages
$mail->CharSet = 'UTF-8';
$mail->SMTPDebug = 0;
$mail->Debugoutput = 'html';
$mail->Host = "host";
$mail->SMTPAuth = false;
$mail->Port = 25;
$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
);
$mail->setFrom('noreply', 'hint');
$mail->addAddress('email.test.com');
$mail->Subject = 'hint';
$msg='Allikas: '.$_POST['source']
$mail->msgHTML('<strong>Hint.</strong>;
if (!$mail->send()) {
echo 'ERROR';
//return false;
//echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "SUCCESS";
}
}else{echo "SUCCESS";}
}
This is my javascript trigger
else if (checked === true) {
console.log("asddd")
"send the stuff (part i need help with")
}
}

You need to do an ajax request
var values = {"source":"the source...", "location":"the location..."}; // add your others variable here...
$.ajax({
url: "yourphpfile.php",
type: "post",
data: values ,
success: function (response) {
// it will return the result (SUCCESS or ERROR)
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});

Related

Uncaught SyntaxError: JSON.parse: unexpected character ierror after include php file

Uncaught SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data site:stackoverflow.com error is showing in firefox debug console.
I have a form in my website and on submit button this functions calls
$("#contact-form").on("submit",function(e)
{
var sendData = $(this).serialize();
e.preventDefault();
if ( checkSubmitInputs(this) )
{
$.ajax({
type: "POST",
url: "js/ajaxsubmit.php",
data: sendData,
success: function(data)
{
$("#loading-img").css("display","none");
// $(".response_msg").text(data);
// document.getElementById('contact-form').style.display = 'none'
// document.getElementById('success').style.display = 'block'
data = JSON.parse(data);
if(data.status){
document.getElementById('contact-form').style.display = 'none';
$("#error").text('');
$("#success").text(data.msg);
document.getElementById('success').style.display = 'block';
document.getElementById('scicon-c').style.display = 'block';
document.getElementById('error').style.display = 'none';
$("#contact-form").find("input[type=text], input[type=email], textarea").val("");
}
else {
document.getElementById('contact-form').style.display = '';
$("#success").text('');
$("#error").text(data.msg);
document.getElementById('error').style.display = 'block'
document.getElementById('success').style.display = 'none'
document.getElementById('scicon-c').style.display = 'none'
}
}
});
} else{
document.getElementsByClassName('error').style.display = 'block'
}
})
This line data = JSON.parse(data); shows above error as soon as i add include_once('mail.php'); in my ajaxsubmit.php file and without including it works perfectly.
Mail.php I am receiving mail too
<?php
error_reporting(-1);
ini_set('display_errors', 'On');
set_error_handler("var_dump");
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
require_once("vendor/autoload.php");
$mail = new PHPMailer(true);
//Enable SMTP debugging.
$mail->SMTPDebug = 3;
//Set PHPMailer to use SMTP.
$mail->isSMTP();
//Set SMTP host name
$mail->Host = "email-smtp.us-west-1.amazonaws.com";
//Set this to true if SMTP host requires authentication to send email
$mail->SMTPAuth = true;
//Provide username and password
$mail->Username = "ID";
$mail->Password = "Pass";
//Set TCP port to connect to
$mail->Port = 587;
$mail->setFrom('demo#example', 'demo#example');
error_reporting(E_ALL); // Error/Exception engine, always use E_ALL
ini_set('ignore_repeated_errors', TRUE); // always use TRUE
ini_set('display_errors', true); // Error/Exception display, use FALSE only in production environment or real server. Use TRUE in development environment
ini_set('log_errors', TRUE); // Error/Exception file logging engine.
ini_set('error_log', 'zeeErrors.log'); // Logging file path
function sendEmailToUser($con, $emailMsg, $Subject)
{
global $mail;
$msg = "";
$subject = $Subject;
$tempArray = explode(',', $emailMsg);
$name = $tempArray[0];
$mobile = $tempArray[1];
$email = $tempArray[2];
$mail->Subject = "Test.";
$to = $email;
$htmlTemplate = file_get_contents('ration.html', true);
$mail->addAddress($to, $name); //Add a recipient
//$mail->addAddress('ellen#example.com'); //Name is optional
//$mail->addCC('cc#example.com');
//$mail->addBCC('varun7952#gmail.com');
$mail->isHTML(true);
$mail->Body = $msg;
//$mail->AltBody = "This is the plain text version of the email content";
try {
$mail->send();
echo "Message has been sent successfully";
return true;
} catch (Exception $e) {
echo "Mailer Error: " . $mail->ErrorInfo;
return false;
}
}
?>
AjaxSubmit.php
<?php
include_once('mail.php');
$response = array();
if((isset($_POST['name'])&& $_POST['name'] !='') && (isset($_POST['email'])&& $_POST['email'] !='') && (isset($_POST['phone'])&& $_POST['phone'] !=''))
{
//whether ip is from share internet
$ia = '';
if (!empty($_SERVER['HTTP_CLIENT_IP']))
{
$ia = $_SERVER['HTTP_CLIENT_IP'];
}
//whether ip is from proxy
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
{
$ia = $_SERVER['HTTP_X_FORWARDED_FOR'];
}
//whether ip is from remote address
else
{
$ia = $_SERVER['REMOTE_ADDR'];
}
/*Get user ip address details with geoplugin.net*/
$geopluginURL='http://www.geoplugin.net/php.gp?ip='.$ia;
$addrDetailsArr = unserialize(file_get_contents($geopluginURL));
/*Get City name by return array*/
$city = $addrDetailsArr['geoplugin_city'];
/*Get Country name by return array*/
$country = $addrDetailsArr['geoplugin_countryName'];
$region = $addrDetailsArr['geoplugin_regionName'];
if(!$city){
$city='Not Define';
}
if(!$country){
$country='Not Define';
}
if(!$region){
$region='Not Define';
}
//file_put_contents('zee1.log', print_r($addrDetailsArr, TRUE));
$yourName = $conn->real_escape_string($_POST['name']);
$yourEmail = $conn->real_escape_string($_POST['email']);
$yourPhone = $conn->real_escape_string($_POST['phone']);
$city = $conn->real_escape_string($city);
$country = $conn->real_escape_string($country);
$region = $conn->real_escape_string($region);
$checkSql = "SELECT name, email, contact from reg where email='".$yourEmail."' OR contact='".$yourPhone."'";
$resultCheck = $conn->query($checkSql);
if($resultCheck->num_rows > 0) {
$response['status'] = false;
$response['msg'] = "You have registered already with ".$yourEmail." OR ".$yourPhone."";;
}else {
$userLocation = $city.' '.$region.' '.$country;
$sql="INSERT INTO reg (name, email, contact,IP_Address,City) VALUES ('".$yourName."','".$yourEmail."', '".$yourPhone."','".$ia."','".$userLocation."')";
if(!$result = $conn->query($sql)){
$response['status'] = false;
$response['msg'] = 'There was an error running the query [' . $conn->error . ']';
}
else
{
$response['status'] = true;
$response['msg'] = "Thank you $yourName. Welcome in SAAS Application. We will connect with you soon. :)";
$msg = $yourName.','.$yourPhone.','.$yourEmail.','.$userLocation;
if(sendEmailToUser($conn,$msg,'Reg')){
//Email Sent
}
}
}
}
else
{
$response['status'] = false;
$response['msg'] = 'Please fill Name and Email';
}
echo json_encode($response);
?>
As i said everything is working if i don't add require in ajaxsubmit file. I am not good in php or JS so after reading so many answers i still can't figure out why i am not able to parse json at my form.
This is JSON Returned by AJAXsubmit
{
"status": true,
"msg": "Thank you Demo. Welcome in SAAS Application. We will connect with you soon. :)"
}
Your problem is that mail.php has this code in it:
try {
$mail->send();
echo "Message has been sent successfully";
return true;
} catch (Exception $e) {
echo "Mailer Error: " . $mail->ErrorInfo;
return false;
}
which, regardless of the result, causes text to be echo'ed. As a result, your json response will look something like:
Message has been sent successfully
{
... normal json response
}
which will not parse successfully.

How to fix error between JSON, jQuery, AJAX and PHP

I'm having problems figuring out what is wrong with my json. I used php's json_encode.So, on every page I have the some form which need be sent on each page to different email address. However, if I comment jQuery file, then the form is submitted correctly, all data inserted into database correctly, and in place of jQuery AJAX response I get valid JSON, like
{"response":"success","content":{"3":"Thanks John Doe! Your message is successfully sent to owner of property Hotel Milano!"}}
If I want to read and process this data with jQuery instead of get valid response I get just empty [] I was try a lot of options and so if I add JSON_FORCE_OBJECT instead of get empty [] I get empty {}. However if I write json data which need to encode after closing tag for if (is_array($emails) && count($emails) > 0) { just then json data it's encoded correctly and when a form is submitted I get valid response, but in this case form isn't sent and data isn't inserted into db. Bellow is my PHP code:
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
// define variables and set to empty values
$fname = $tel = $email_address_id = "";
$error = false;
$response = [];
//Load the config file
$dbHost = "localhost";
$dbUser = "secret";
$dbPassword = "secret";
$dbName = "booking";
$dbCharset = "utf8";
try {
$dsn = "mysql:host=" . $dbHost . ";dbName=" . $dbName . ";charset=" . $dbCharset;
$pdo = new PDO($dsn, $dbUser, $dbPassword);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
$response['response'] = 'error';
$response['errors'][] = $e->getMessage();
echo json_encode($response);
die();
}
use PHPMailer\PHPMailer\PHPMailer;
require 'PHPMailer/PHPMailer.php';
require 'PHPMailer/SMTP.php';
require 'PHPMailer/Exception.php';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (isset($_POST['submit'])) {
//print_r($_POST);
$fname = $_POST['fname'];
$tel = $_POST['tel'];
if (empty($fname)) {
$response['response'] = 'error';
$error = true;
$response['errors'][] = 'Name can not be empty!';
} else {
if (!preg_match("/^[a-zšđčćžA-ZŠĐČĆŽ\s]*$/", $fname)) {
$response['response'] = 'error';
$error = true;
$response['errors'][] = 'Name can contain just letters and white space!';
}
}
if (empty($tel)) {
$response['response'] = 'error';
$error = true;
$response['errors'][] = "Phone can not be empty!";
} else {
if (!preg_match('/^[\+]?[0-9]{9,15}$/', $tel)) {
$response['response'] = 'error';
$error = true;
$response['errors'][] = "Phone can contain from 9 to 15 numbers!";
}
}
if (!$error) {
// Instantiate a NEW email
$mail = new PHPMailer(true);
$mail->CharSet = "UTF-8";
$mail->isSMTP();
$mail->Host = 'secret.com';
$mail->SMTPAuth = true;
//$mail->SMTPDebug = 2;
$mail->Username = 'booking#secret.com';
$mail->Password = 'secret';
$mail->Port = 465; // 587
$mail->SMTPSecure = 'ssl'; // tls
$mail->WordWrap = 50;
$mail->isHTML(true);
$mail->setFrom('booking#secret.com');
$mail->clearAddresses();
$mail->Subject = "New message from secret.com";
$query = "SELECT owners_email.email_address_id, email_address, owner_name, owner_property, owner_sex, owner_type FROM booking.owners_email INNER JOIN booking.pages ON (pages.email_address_id = owners_email.email_address_id) WHERE `owner_sex`='M' AND `owner_type`='other' AND `pages_id` = ?";
$dbstmt = $pdo->prepare($query);
$dbstmt->bindParam(1, $pages_id);
$dbstmt->execute();
//var_dump($dbstmt);
$emails = $dbstmt->fetchAll(PDO::FETCH_ASSOC);
if (is_array($emails) && count($emails) > 0) {
foreach ($emails as $email) {
//var_dump($email['email_address']);
$mail->addAddress($email['email_address']);
$body = "<p>Dear {$email['owner_name']}, <br>" . "You just received a message from <a href='https://www.secret-booking.com'>secret-booking.com</a><br>The details of your message are below:</p><p><strong>From: </strong>" . ucwords($fname) . "<br><strong>Phone: </strong>" . $tel . "</p>";
$mail->Body = $body;
if ($mail->send()) {
$mail = "INSERT INTO booking.contact_owner (fname, tel, email_address_id) VALUES (:fname, :tel, :email_address_id)";
$stmt = $pdo->prepare($mail);
$stmt->execute(['fname' => $fname, 'tel' => $tel, 'email_address_id' => $email['email_address_id']]);
$response['response'] = "success";
$response['content'][$email['email_address_id']] = "Thanks " . ucwords($fname) . "! Your message is successfully sent to owner of property {$email['owner_property']}!";
}//end if mail send
else {
$response['response'] = "error";
$response['content'][$email['email_address_id']] = "Something went wrong! Try again..." . $mail->ErrorInfo;
}
}//end foreach for email addresses
} //end if for array of emails
/* If use this else for response I allways get this response. Even, if I write JSON for success hier I get it but data isn't sent and isn't inserted into db
else {
$response['response'] = 'error';
$response['error'][] = '$emails is either not an array or is empty'; // jQuery just read this
}//end if else for array of emails
*/
}//end if validation
}//end submit
echo json_encode($response);
}//end REQUEST METHOD = POST
And this is jQuery for submitHanfdler
submitHandler: function (form) {
//Your code for AJAX starts
var formData = jQuery("#contactOwner").serialize();
console.log(formData); //this work
jQuery.ajax({
url: '/classes/Form_process.class.php',
type: 'post',
data: formData,
dataType: 'json',
cache: false,
success: function (response) {
jQuery("#response").text(response['content']);
// debbuger;
console.log(response);
//console.log(response.hasOwnProperty('content'));
},
error: function (response) {
// alert("error");
jQuery("#responseOwner").text("An error occurred");
console.dir("Response: " + response);
}
}); //Code for AJAX Ends
// Clear all data after submit
var resetForm = document.getElementById('contactOwner').reset();
return false;
} //submitHandler
Thanks in advance for any kind of your help, any help will be highly appreciated!
I suspect the issue is the dataType: 'json' attribute. This is because the serialize function does not provide json data. See if this works:
jQuery.ajax({
url: '/classes/Form_process.class.php',
method: 'POST',
data: jQuery("#contactOwner").serialize()
}).done(function (response) {
console.log(response);
}).fail(function (error) {
console.log(error);
});
Alternatively, if you want to use dataType: 'json', you will need to send in json data:
jQuery.ajax({
url: '/classes/Form_process.class.php',
method: 'POST',
data: {
firstName: jQuery("#contactOwner .first-name").val(),
lastName: jQuery("#contactOwner .last-name").val(),
...
}
dataType: 'json',
cache: false,
}).done(function (response) {
console.log(response);
}).fail(function (error) {
console.log(error);
});
If you add you data using an object as shown above this should work with dataType: 'json'.

I cant get my php mailer to send a mail using post data

i am having some trouble with phpmailer and ajax. Im quite new to ajax and dont fully understand it yet so this might have a quite obvious fix but here we go.
So when i just put my php mailer script in a page and visit it with set values i can send the mail. but whenever i try to send my form data to the script something doesnt work.
This is my jquery
$(document).ready(function(){
$(".contact-form").on("submit",function(e){
e.preventDefault();
function validateEmail($email) {
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
return emailReg.test( $email );
}
var valid = true;
if(!$("#name").val()) {
$("#userEmail").css('border','2px solid #FFFFDF');
valid = false;
}
if( !validateEmail($(' #email').val())) {
valid = false
}
if(!$("#subject").val()) {
$("#subject").css('border','2px solid #FFFFDF');
valid = false;
}
if(!$("#message").val()) {
$("#message").css('border','2px solid #FFFFDF');
valid = false;
}
//send data to php file
var isValid;
isValid = valid
if(isValid) {
var name = $("#name").val();
var email = $("#email").val();
var subject = $("#subject").val();
var message = $("#message").val();
jQuery.ajax({
url: "includes/sendmail.inc.php",
type : "POST",
data:{name:name,email:email,subject:subject,message:message},
success:function(data){
$(".err_msg").text("Send!");
$(".err_msg").css('background-color', 'green')
$(".err_msg").show()
},
error:function (){}
});
} else {
$(".err_msg").text("Oops! check your input.");
$(".err_msg").css('background-color', 'red')
$(".err_msg").show()
}
});
});
This is my php
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
// Import PHPMailer classes into the global namespace
// These must be at the top of your script, not inside a function
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
// Load Composer's autoloader
require 'vendor/autoload.php';
$name = $_POST['name'];
$mail = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
// Instantiation and passing `true` enables exceptions
$mail = new PHPMailer(true);
try {
//Server settings
$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
);
$mail->SMTPDebug = SMTP::DEBUG_SERVER; // Enable verbose debug output
$mail->isSMTP(); // Send using SMTP
$mail->Host = 'mail.example#example.com'; // Set the SMTP server to send through
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'example#example.com'; // SMTP username
$mail->Password = 'example123'; // SMTP password
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged
$mail->Port = 587 ; // TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above
//Recipients
$mail->setFrom( $email , $name);
$mail->addAddress('example#example.com', 'John Doe'); // Add a recipient
$mail->addReplyTo($email , $name);
// Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = $subject;
$mail->Body = $message;
$mail->send();
echo 'Message has been sent';
} catch (Exception $e) {
echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
so this is what i have so far i hope you guys can figure out what i did wrong because i have been stuck on this for about two days now.
greetz Floris
yes i figured it out guys thanks ! so what went wrong is that for some reason it wouldnt send because the FROM email adress was a gmail account and i am using my own domain smtp that was causing it appearantly

Differ PhpMailer in AngularJS foreach

I have problems :
My code for emailing is working, but I don't think its the right way to do so. Is it possible to use the $http service inside an AngularJS foreach loop? Will it overheat the process, if each loop is destined to PhpMailer to send one mail each time? Should I use the $q service? The code works to send a low amount of emails but will it overheat the php script if more emails are sent?
AngularJS code
$scope.submit = function(contactform) {
$scope.submitted = true;
$scope.submitButtonDisabled = true;
angular.forEach($scope.intervenants,function(data){
var x = angular.copy($scope.formData);
x.destinataire = data.email;
$http({
method : 'POST',
url : 'contact-form.php',
data : $.param(x), //param method from jQuery
headers : { 'Content-Type': 'application/x-www-form-urlencoded' } //set the headers so angular passing info as form data (not request payload)
}).success(function(data){
console.log(data);
if (data.success) { //success comes from the return json object
$scope.submitButtonDisabled = true;
$scope.resultMessage = data.message;
$scope.result='bg-success';
} else {
$scope.submitButtonDisabled = false;
$scope.resultMessage = data.message;
$scope.result='bg-danger';
}
});
});
}
PhpMail code
//check if any of the inputs are empty
if (empty($_POST['inputName']) || empty($_POST['inputEmail']) || empty($_POST['inputSubject']) || empty($_POST['inputMessage'])) {
$data = array('success' => false, 'message' => 'Please fill out the form completely.');
echo json_encode($data);
exit;
}
//create an instance of PHPMailer
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->Host = "smtp.orange.fr";
$mail->From = $_POST['inputEmail'];
$mail->FromName = $_POST['inputName'];
$mail->AddAddress($_POST['destinataire']); //recipient
$mail->Subject = $_POST['inputSubject'];
$mail->Body = "Name: " . $_POST['inputName'] . "\r\n\r\nMessage: " . stripslashes($_POST['inputMessage']);
if (isset($_POST['ref'])) {
$mail->Body .= "\r\n\r\nRef: " . $_POST['ref'];
}
if(!$mail->send()) {
$data = array('success' => false, 'message' => 'Message could not be sent. Mailer Error: ' . $mail->ErrorInfo);
echo json_encode($data);
exit;
}
$data = array('success' => true, 'message' => 'Thanks! We have received your message.');
echo json_encode($data);
} else {
$data = array('success' => false, 'message' => 'Please fill out the form completely.');
echo json_encode($data);
}

If statement not working in javascript/ajax

Ok so this is driving me mad. I've got 2 modal forms - login and register. Javascript does the client side validation and then an ajax call runs either a registration php file or a login php file which returns OK if successful or a specific error message indicating what was wrong (incorrect password, username already taken,etc). There is an If Then statement that checks if the return message is OK and if it is then a success message is displayed and the other fields hidden.
The register form works perfectly. I get my OK back and fields get hidden and the success message displays.
The login form however doesn't work. A successful login returns an OK but the if statement fails and instead of a nicely formatted success message I just get the OK displayed without the username and password fields being hidden which is what makes me think the IF is failing although I cannot see why it would.
I've been staring at this code for hours now and all I can see is the same code for both and no idea why one is working and one is not ....
On to the code...Here is the Login javascript:
$("#ajax-login-form").submit(function(){
var str = $(this).serialize();
$.ajax({
type: "POST",
url: "php/login.php",
data: str,
success: function(msg) {
$("#logNote").ajaxComplete(function(event, request, settings) {
if(msg == 'OK') {
// Display the Success Message
result = '<div class="alertMsg success">You have succesfully logged in.</div>';
$("#ajax-login-form").hide();
$("#swaptoreg").hide();
$("#resetpassword").hide();
} else {
result = msg;
}
// On success, hide the form
$(this).hide();
$(this).html(result).slideDown("fast");
$(this).html(result);
});
}
});
return false;
});
and here is the register javascript:
$("#ajax-register-form").submit(function(){
var str = $(this).serialize();
$.ajax({
type: "POST",
url: "php/register.php",
data: str,
success: function(msg) {
$("#regNote").ajaxComplete(function(event, request, settings) {
if(msg == 'OK') {
// Display the Success Message
result = '<div class="alertMsg success">Thank you! Your account has been created.</div>';
$("#ajax-register-form").hide();
} else {
result = msg;
}
// On success, hide the form
$(this).hide();
$(this).html(result).slideDown("fast");
$(this).html(result);
});
}
});
return false;
});
I don't think I need to add the php here since both just end with an echo 'OK'; if successful and since I'm seeing the OK instead of the nicely formatted success message I'm confident that it is working.
Any suggestions?
EDIT: Here's the login php:
<?php
require("common.php");
$submitted_username = '';
$user = stripslashes($_POST['logUser']);
$pass = stripslashes($_POST['logPass']);
if(!empty($_POST))
{
$query = "
SELECT
id,
username,
password,
salt,
email
FROM users
WHERE
username = :username
";
$query_params = array(
':username' => $user
);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
die("Failed to run query ");
}
$login_ok = false;
$row = $stmt->fetch();
if($row)
{
$check_password = hash('sha256', $pass . $row['salt']);
for($round = 0; $round < 65536; $round++)
{
$check_password = hash('sha256', $check_password . $row['salt']);
}
if($check_password === $row['password'])
{
$login_ok = true;
}
}
if($login_ok)
{
unset($row['salt']);
unset($row['password']);
$_SESSION['user'] = $row;
echo 'OK';
}
else
{
echo '<div class="alertMsg error">Incorrect username or password</div>';
$submitted_username = htmlentities($_POST['username'], ENT_QUOTES, 'UTF-8');
}
}
?>
if($login_ok)
{
unset($row['salt']);
unset($row['password']);
$_SESSION['user'] = $row;
echo 'OK';
}
else
{
echo '<div class="alertMsg error">Incorrect username or password</div>';
$submitted_username = htmlentities($_POST['username'], ENT_QUOTES, 'UTF-8');
}
}
?> <!------- There is a space here! -->
There is a space after the closing ?> which is being sent to the user. The closing ?> is optional, and it is highly recommended to NOT include it, for just this reason. Get rid of that ?>.

Categories

Resources