No matter what I type in (even the correct captcha), I always get missmatched output. I've tried echoing the values (they are supposed to match if you type in the right code). and I always get something like this:
6952304285049
-1247767175
I am using jquery-1.10.2.min.js (and have this linked in my header along with the realperson.js file)
http://gfishdesigns.com/COMP2920/_COMPLETED/Assignment%202/SignUp.php
Here's my code (im doing some other validating as well):
<?php
include 'Header.php';
include 'Database.php';
?>
<script type="text/javascript">
$(function() {
$('#defaultReal').realperson();
});
</script>
<h1>Sign Up</h1>
<?php
if ($_POST){
$username = $_POST['username'];
$password = $_POST['password'];
$check = '';
//validate CAPTCHA
function rpHash($value) {
$hash = 5381;
$value = strtoupper($value);
for($i = 0; $i < strlen($value); $i++) {
$hash = (($hash << 5) + $hash) + ord(substr($value, $i));
}
return $hash;
}
if (rpHash($_POST['defaultReal']) == $_POST['defaultRealHash']) { ?>
<p class="accepted">You have entered the "real person" value correctly and the form has been processed.</p>
<?php
//if username is not blank
if($username != ''){
//check if username exists already
$query = "SELECT username FROM tbl_user;";
$result = mysql_query($query) or die(mysql_error());
while ($record = mysql_fetch_row($result))
{
foreach($record as $field)
{
if($field == $username){
//if user exists, dont let them add same user
$error_message_username = 'username already used; choose a unique name';
}
else{
$check = 'pass';
}
}
}
}else{
$error_message_username = 'username cannot be blank';
}
//if password is not blank
if($password != ''){
$error_message_password = '';
// encrypt password
$encrypted_password = md5($password);
if($check == 'pass'){
//set username and password into database
$query = "INSERT INTO tbl_user VALUES('','".$username."','".$encrypted_password."');";
$result = mysql_query($query) or die(mysql_error());
}
}else{
$error_message_password = 'password cannot be blank';
}
} else { ?>
<p class="rejected">You have NOT entered the CAPTCHA value correctly and the form has been rejected.</p>
<?php
echo rpHash($_POST['defaultReal']) . '<br/>';
echo $_POST['defaultRealHash'];
}
}
?>
<form method="post" action="SignUp.php">
<p>
E-Mail:
<input type="text" class="required email" id="username" name="username">
<?php
if ( $error_message_username != '' ) {
print "$error_message_username";
}
?>
</p>
<p>
Password:
<input type="text" name="password">
<?php
if ( $error_message_password != '' ) {
print "$error_message_password";
}
?>
</p>
<p>
CAPTCHA:
<input type="text" id="defaultReal" name="defaultReal">
</p>
<p>
<button class="mybutton" type="submit" value="Sign Up">Sign Up</button>
</p>
</form>
Well said Craig Jacobs, it is the same problem which you pointed out. I also faced the same thing and solved by making changes shown below:
function rpHash($value) {
$hash = 5381;
$value = strtoupper($value);
for($i = 0; $i < strlen($value); $i++) {
$hash = (leftShift32($hash, 5) + $hash) + ord(substr($value, $i));
}
return $hash; }
function leftShift32($number, $steps) {
$binary = decbin($number);
$binary = str_pad($binary, 32, "0", STR_PAD_LEFT);
$binary = $binary.str_repeat("0", $steps);
$binary = substr($binary, strlen($binary) - 32);
return ($binary{0} == "0" ? bindec($binary) :
-(pow(2, 31) - bindec(substr($binary, 1))));
}
if (isset($_POST['submit'])) {
.....
if (rpHash($_POST['defaultReal']) != $_POST['defaultRealHash']) {
echo "Invalid contact request, please try again with correct verification code...";
exit;
}
.....
.....
}
Hope it will help someone else too.
There are two versions of the php rpHash function provided, one for 32-bit and one for 64-bit PHP. Run phpinfo and make sure you are using the correct version of the function as provided on this page http://keith-wood.name/realPerson.html. The bitwise functions as used here will return different values on 32 and 64 bit machines. See this page: http://www.php.net/manual/en/language.operators.bitwise.php
Related
In the username availability check I created two pages: register.php and registercontrol.php controlling it. I check the database connection its on work. Everything (all statements, insertin data into db) that was previously created on a single php page. But when ajax validates other inputs its duplicates the html content and shows the error inside of it instead of showing error messages in a just single html element.
So I seperated it into two pages but now ajax not shows any error and responds. Here is my work:
registercontrol.php
<?php
require('../includes/config.php');
if(isset($_POST['username'])){
//username validation
$username = $_POST['username'];
if (! $user->isValidUsername($username)){
$infoun[] = 'Your username must be 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 already in use';
}
}
}
?>
register.php
<script type="text/javascript">
$(document).ready(function(){
$("#username").keyup(function(event){
event.preventDefault();
var username = $(this).val().trim();
if(username.length >= 3){
$.ajax({
url: 'registercontrol.php',
type: 'POST',
data: {username:username},
success: function(response){
// Show response
$("#uname_response").html(response);
}
});
}else{
$("#uname_response").html("");
}
});
});
</script>
<form id="register-form" class="user" role="form" method="post" action="registercontrol.php" autocomplete="off">
<input type="text" name="username" id="username" class="form-control form-control-user" placeholder="Username" value="<?php if(isset($error)){ echo htmlspecialchars($_POST['username'], ENT_QUOTES); } ?>" tabindex="2" required>
<div id="uname_response" ></div>
</form>
we need to print the response in registercontrol.php so that we can get response in your register.php
Change your code as below
<?php
require('../includes/config.php');
if(isset($_POST['username'])){
//username validation
$username = $_POST['username'];
if (! $user->isValidUsername($username)){
echo 'Your username must be 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'])){
echo 'This username already in use';
}
}
}
?>
You need to return or echo something from registercontrol.php
<?php
require('../includes/config.php');
if(isset($_POST['username'])){
//username validation
$username = $_POST['username'];
if (! $user->isValidUsername($username)){
$infoun[] = 'Your username must be at least 6 alphanumeric characters';
echo json_encode($infoun);
exit;
} 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 already in use';
echo json_encode($errorun);
exit;
}
echo $row[username];
exit;
}
}
?>
I am writing a simple login validation. (I know people say I shouldn't deal with passwords in plaintext, because it's dangerous, however, I am doing this for a school assignment where we do not need to use any security.) The issue I am having here is that I can't get the message for login to be successful. I am getting a login failure. I inserted a couple of users and passwords into a database table. What I need to do is to get the value from the "name" column and the "pwd" (password) column from my database table and allow a successful login (in Javascript) if the user's input has a match with the user and password in the database table.
Here is my form code:
<form method="post" action="login.php" onsubmit="validateForm()" id="loginForm" name="loginForm">
Name:<br>
<input type="text" name="personName"><br>
Password:<br>
<input type="password" name="pswd"><br>
<input type="submit" name="submit" id="submit" value="Login" />
</form>
Javascript:
<script>
function validateForm()
{
var n = document.loginForm.personName.value;
var p = document.loginForm.pswd.value;
//The var below is what I need help on.
var name = "<?php echo $row['name']; ?>";
//The var below is what I need help on.
var ps = "<?php echo $row['pwd']; ?>";
if ((n == name) && (p == ps))
{
alert ("Login successful!");
return true;
}
else
{
alert ("Login failed! Username or password is incorrect!");
return false;
}
}
</script>
PHP code (I have an empty while statement just in case I need it):
<?php
function validateLogin()
{
//I hid this information from here.
$servername = "";
$username = "";
$password = "";
$dbname = "";
// Create connection
$dbc = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($dbc->connect_error)
{
die("Connection failed: " . $dbc->connect_error);
}
$n = $_POST["personName"];
$p = $_POST["pswd"];
$query = "SELECT `name`, `pwd` FROM `chatApp`";
$result = $dbc->query($query);
$numRows = mysql_num_rows($result);
$count = 1;
if ($result->num_rows > 0)
{
while($row = $result->fetch_assoc())
{
}
}
else
{
echo "0 results";
}
$dbc->close();
}
if(array_key_exists('loginForm',$_POST))
{
validateLogin();
}
?>
I have this simple form I'm testing. It's just a test for the beginning of a form that will be improved later on; I only need it to work correctly. I still don't have the database ready, so in my code I have two users that I want to pass as 'registered'.
Here's the code for the form:
<form action="" method="POST">
<label>User: </label>
<input type="text" name="user" id="usuario" />
<label>Password: </label>
<input type="password" name="password" id="password" />
<div class="text-center">
<button type="button" class="boton-submit" name="submit" onClick="login()">Sign In</button>
</div>
</form>
These two inputs are validated with JavaScript, and the values are sent through AJAX.
This is the code (only the AJAX part, the rest are only validations and they work fine):
function login(){
if(validationLogin()){
$.ajax({
url: "http://localhost/MyApp/extras/processLogin.php",
type: "POST",
data: {"user": user,
"password": password,
},
dataType: "html",
cache: false,
beforeSend: function() {
console.log("Processing...");
},
success:
function(data){
if(data == "OK"){
window.location.href = "http://localhost/MyApp/loginSuccess.php";
}else{
window.location.href = "http://localhost/MyApp/loginFail.php";
}
}
});
}else{
//alert("Incorrect data");
}
}
And this is code in the PHP file:
<?php
session_start();
$user = "";
$password = "";
$errors = array();
if (isset($_POST['submit'])){
if(isset($_POST['user'])){
if(!empty($_POST['user'])){
$user = $_POST['user'];
}else{
$errors = 1;
}
}else{
$errors = $errors;
}
if(isset($_POST['password'])){
if(!empty($_POST['password'])){
$password = $_POST['password'];
}else{
$errors = 1;
}
}else{
$errors = $errors;
}
$_SESSION['user'] = $user;
$_SESSION['password'] = $password;
//TEST: Check if user is --> LAURA 123456 or LUIS 567899
if((($user == "LAURA") && ($password == "123456")) || (($user == "LUIS") &&
($password == "567899"))){
$data = "OK";
echo $data;
//header("location: ../loginSuccess.php");
}else{
$data = "ERROR";
echo $data;
//echo "No se encontrĂ³ usuario";
//header("location: ../loginFail.php");
}
}
At the beginning, I had an action in the form that sent data to the PHP directly, and in that way it worked fine --> if user was LAURA or LUIS it would redirect to loginSuccess.php and greeted the user, if not, it would redirect to loginFail.php (that's why the headers are commented)
I just want to test that this functions, but when I modified the code to use AJAX, it always fails, even if the user is LAURA or LUIS, it redirects to the loginFail page...
I suspect there is some problem in the success function in the AJAX call.
Any help is appreciated :) Have a nice day!
There's no submit index your $_POST array, so this condition if (isset($_POST['submit'])){ ... will always fail. Remove this conditional check if (isset($_POST['submit'])){ ... } entirely, and refactor your backend PHP code in the following way,
<?php
session_start();
$user = "";
$password = "";
$errors = array();
if(isset($_POST['user'])){
if(!empty($_POST['user'])){
$user = $_POST['user'];
}else{
$errors = 1;
}
}else{
$errors = $errors;
}
if(isset($_POST['password'])){
if(!empty($_POST['password'])){
$password = $_POST['password'];
}else{
$errors = 1;
}
}else{
$errors = $errors;
}
$_SESSION['user'] = $user;
$_SESSION['password'] = $password;
//TEST: Check if user is --> LAURA 123456 or LUIS 567899
if((($user == "LAURA") && ($password == "123456")) || (($user == "LUIS") &&
($password == "567899"))){
$data = "OK";
echo $data;
//header("location: ../loginSuccess.php");
}else{
$data = "ERROR";
echo $data;
//echo "No se encontrĂ³ usuario";
//header("location: ../loginFail.php");
}
?>
Im creating login script which are based on javascript and PHP. But I had problem with it.
Whatever I send via form I will be redirected to user.php?u=loginfailed. It doesen't matter whether it is properly email and password (which I have in my database). As you can see page "user.php?u=X" should be open only when email and password are entered correctly. But in my case when I sent correct data and incorrect data it will be the same... To sum up - correct data should redirected me to user.php?u=X and incorrect should display an error message below the form.
What do you think about it?
Index.php
<?php
if(isset($_POST["e"])){
include_once("../db/db_fns.php");
$e = mysqli_real_escape_string($db_conx, $_POST['e']);
$p = md5($_POST['p']);
$ip = preg_replace('#[^0-9.]#', '', getenv('REMOTE_ADDR'));
if($e == "" || $p == ""){
echo "loginfailed";
exit();
} else {
$sql = "SELECT id, username, password FROM users WHERE email='$e' AND activated='1' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$row = mysqli_fetch_row($query);
$db_id = $row[0];
$db_username = $row[1];
$db_pass_str = $row[2];
if($p != $db_pass_str){
echo "loginfailed";
exit();
} else {
$_SESSION['userid'] = $db_id;
$_SESSION['username'] = $db_username;
$_SESSION['password'] = $db_pass_str;
setcookie("id", $db_id, strtotime( '+30 days' ), "/", "", "", TRUE);
setcookie("user", $db_username, strtotime( '+30 days' ), "/", "", "", TRUE);
setcookie("pass", $db_pass_str, strtotime( '+30 days' ), "/", "", "", TRUE);
$sql = "UPDATE users SET ip='$ip', lastlogin=now() WHERE username='$db_username' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
echo $db_username;
exit();
}
}
exit();
}
?>
<script src="../js/main.js"></script>
<script src="../js/ajax.js"></script>
<script src="login.js"></script>
<form id="loginform" onsubmit="return false;">
<div>Email Address:</div>
<input type="text" id="email" onfocus="emptyElement('status')" maxlength="88">
<div>Password:</div>
<input type="password" id="password" onfocus="emptyElement('status')" maxlength="100">
<br /><br />
<button id="loginbtn" onclick="login()">Log In</button>
<p id="status"></p>
Forgot Your Password?
</form>
login.js
function emptyElement(x) {
_(x).innerHTML = "";
}
function login() {
var e = _("email").value;
var p = _("password").value;
if (e == "" || p == "") {
_("status").innerHTML = "Fill out all of the form data";
} else {
_("loginbtn").style.display = "none";
_("status").innerHTML = 'please wait ...';
var ajax = ajaxObj("POST", "index.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText == "loginfailed") {
_("status").innerHTML = "Login unsuccessful, please try again.";
_("loginbtn").style.display = "block";
} else {
window.location = "user.php?u="+ajax.responseText;
}
}
}
ajax.send("e="+e+"&p="+p);
}
}
Try this :
Try to alert ajax.responseText and see if it return proper result without an error. Also user trim before comparing responsetext like this : if(ajax.responseText.trim() == "loginfailed")
Why you are not using Jquery as it is very simple and easy to use.
I believe you are missing return and therefore your form is submitting regardless. Don't forget to have the login() function return false so it doesn't submit.
try <button id="loginbtn" onclick="return login();">Log In</button>
I have managed to go ahead with my user update page and it all seems to be fine at the form I had it reading the current details from logged in user when i clicked submit it says submit successful, then I am stuck with this page can't go back, I don't know if it worked and cannot see any error messages or any that i can see.
I am very new to coding so sorry if any silly mistake i missed out on... someone help me please....
Here is my PHP
<?php
include_once("php_includes/check_login_status.php");
session_start();
if (isset($_SESSION['username'])) {
$username = $_SESSION['username'];
}
else {
echo "You have not signed in";
}
// Initialize any variables that the page might echo
$firstname = "";
$surname = "";
$u = "";
$weight = "";
$height = "";
// Make sure the _GET username is set, and sanitize it
if(isset($_GET["u"])){
$u = preg_replace('#[^a-z0-9]#i', '', $_GET['u']);
} else {
header("location: index.php");
exit();
}
// Select the member from the users database table
$sql = "SELECT * FROM users WHERE username='$u' AND activated='1' LIMIT 1";
$user_query = mysqli_query($db_conx, $sql);
// check if the user exists in the database
$numrows = mysqli_num_rows($user_query);
if($numrows < 1){
echo "That user does not exist or is not yet activated, press back";
exit();
}
while ($row = mysqli_fetch_array($user_query, MYSQLI_ASSOC)) {
$firstname = $row["firstname"];
$surname = $row["surname"];
$weight = $row["weight"];
$height = $row["height"];
$profile_id = $row["id"];
$u = $row["u"];
}
// this is the calculation of the BMI index
//$BMI = ($weighteight / ($heighteight * $heighteight))* 10000;
if($firstname =="" || $surname == ""|| $weight == "" || $height == ""){
echo "The form submission is missing values.";
exit();
} else {
$p_hash = md5($p);
// Add user info into the database table for the main site table
$sql = "INSERT INTO users (firstname, surname, weight, height)
VALUES('$fn','$sn','$w','$h')";
$query = mysqli_query($db_conx, $sql);
$uid = mysqli_insert_id($db_conx);
// Establish their row in the useroptions table
$sql = "INSERT INTO useroptions (id, username, background) VALUES ('$uid','$u','original')";
$query = mysqli_query($db_conx, $sql);
// Create directory(folder) to hold each user's files(pics, MP3s, etc.)
if (!file_exists("user/$u")) {
mkdir("user/$u", 0755);
}
// Email the user their activation link
$to = "$e";
$from = "k1003140#kingston.ac.uk";
$subject = 'studentnet.kingston.ac.uk/k1003140';
$message = '<!DOCTYPE html><html><head><meta charset="UTF-8"><title>yoursitename Message</title></head><body style="margin:0px; font-family:Tahoma, Geneva, sans-serif;"><div style="padding:10px; background:#333; font-size:24px; color:#CCC;"><img src="http://www.yoursitename.com/images/logo.png" width="36" height="30" alt="yoursitename" style="border:none; float:left;">yoursitename Account Activation</div><div style="padding:24px; font-size:17px;">Hello '.$u.',<br /><br />Click the link below to activate your account when ready:<br /><br />Click here to activate your account now<br /><br />Login after successful activation using your:<br />* E-mail Address: <b>'.$e.'</b></div></body></html>';
$headers = "From: $from\n";
$headers .= "MIME-Version: 1.0\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\n";
mail($to, $subject, $message, $headers);
echo "signup_success";
exit();
}
exit();
?>
Here is my Javascript code
<script>
function signup(){
var u = _("username").value;
var fn = _("firstname").value;
var sn = _("surname").value;
var w = _("weight").value;
var h = _("height").value;
var e = _("email"). value;
var status = _("status");
if(fn == "" || sn == "" || w == "" || h == ""|| g == ""){
status.innerHTML = "Fill out all of the form data";
} else {
_("signupbtn").style.display = "none";
status.innerHTML = 'please wait ...';
var ajax = ajaxObj("POST", "signup.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText != "signup_success"){
status.innerHTML = ajax.responseText;
_("signupbtn").style.display = "block";
} else {
window.scrollTo(0,0);
_("signupform").innerHTML = "OK "+u+", check your email inbox and junk mail box at <u>"+e+"</u> in a moment to complete the sign up process by activating your account. You will not be able to do anything on the site until you successfully activate your account.";
}
}
}
ajax.send("fn="+fn+"&sn="+sn+"&w="+w+"&h="+h+);
}
}
here i added some more of my code to see the HTML
<body>
<?php include_once("template_pageTop.php"); ?>
<div id="pageMiddle">
<form name="signupform" id="signupform" onsubmit="return false;">
<div id="usernamecss"><?php echo $u; ?></div>
<p><b>Is the viewer the page owner, logged in and verified? <?php echo $isOwner; ?></b></p>
<p>First Name: <input type="text" name="firstname" onfocus="emptyElement('status')" size="35" maxlength="15" value='<?=$firstname?>'></p>
<p>Surname: <input type="text" name="surname" onfocus="emptyElement('status')" size="35" maxlength="15" value='<?=$surname?>'></p>
<p>Weight: <input type="text" name="weight" onfocus="emptyElement('status')" size="35" maxlength="15" value='<?=$weighteight?>'></p>
<p>Height: <input type="text" name="height" onfocus="emptyElement('status')" size="35" maxlength="15" value='<?=$heighteight?>'></p>
<button id="signupbtn" onclick="signup()">Create Account</button>
</div>
</form>
<?php include_once("template_pageBottom.php"); ?>
<span id="status"></span>
</body>
i can't write comment so i will write here
U should use session_start(); at the first line of the page and this may cause some problem try it
session_start();
include_once("php_includes/check_login_status.php");
As I can see you are doing a POST in your ajax but are reacting to GET in your php.
Try to change:
if(isset($_GET["u"])){
to:
if(isset($_POST["u"])){
or:
if(isset($_REQUEST["u"])){