I am creating a login form which if the user tries 3 input login it will automatically block. but the problem is after 1 login only it already block. and All the users have been blocked. I want only after 3 times the username that i input will be blocked. Can someone help me?Thank you.
here is my code...
<!DOCTYPE html>
<?php
function p(){
$xmldoc=new DOMDocument();
$xmldoc->load('person.xml');
$root=$xmldoc->documentElement;
$data=$root->getElementsByTagName('user');
$status="Blocked";
if($data){
$domelemupdate=[];
foreach ($data as $domElement) {
$domElement->childNodes->item(5)->textContent=$status;
}
}
foreach ($domelemupdate as $domElement) {
# code...
$domElement->parentNode->replaceChild($domElement);
}
$xmldoc->save('person.xml');
}
?>
<html>
<head>
<body>
</body>
</head>
</html>
var ctr=0;
window.login = function(e)
{
if (document.frmlogin.login_username.value == "")
{
alert("User name is not blank");
return;
}
else if(document.frmlogin.login_pass.value == "")
{
alert("Password is not blank");
return;
}
else
{
var xmlDoc;
var x;
var txt = "";
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else { // IE 5/6
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.overrideMimeType('text/xml');
xhttp.open("GET", "person.xml", false);
xhttp.send(null);
xmlDoc = xhttp.responseXML;
var ktra=false;
var xml=xmlDoc.childNodes[0];
var name = xml.childNodes["username"];
var pass=xml.childNodes["password"];
var status=xml.childNodes["status"];
for(var i=0;i<xml.childNodes.length;i++){
if(xml.childNodes[i].nodeName=="user"){
name = xml.childNodes[i].childNodes[3];
pass = xml.childNodes[i].childNodes[5];
status = xml.childNodes[i].childNodes[7];
position = xml.childNodes[i].childNodes[9];
if(name.textContent==frmlogin.login_username.value && pass.textContent==frmlogin.login_pass.value && status.textContent== "Active")
{
alert("Login Success!");
}
}
if(ktra==false)
{
ctr+=1
alert("Login Failed !!!" +ctr);
if(ctr==3){
//alert("You are now Blocked!!!" );
x=p()
alert(x);
}
}
}
}
</script>
Whenever i call the function in my ctr==3 .If i run the program,if for example i try first login wrong username . after i click login the text easily update to block,.i want my counter 3 times before it will be block and i want the user that i input will be blocked only not all the users
You should be keeping track of the failed count either in a database, or write to the XML file an incremental count each time they fail to login with valid credentials..
Related
please i want to know how to store the user input data in the registeration page then i pass it to login page and in login page i validate if the user write the right username and password or not(that already passed from registeration page)
here is my js code for registeration page:
<head>
<script>
//function to check if the passoword is matched
function checkpass() {
if (document.getElementById('psw').value ==
document.getElementById('psw-confirm').value) {
document.getElementById('message').style.color = 'green';
document.getElementById('message').innerHTML = 'Matched Passowrds';
} else {
document.getElementById('message').style.color = 'red';
document.getElementById('message').innerHTML = 'Those passwords didn’t match. Try again.';
}
}
//function to disable the submit button if the password is not matched
function check_pass() {
if (document.getElementById('psw').value ==
document.getElementById('psw-confirm').value) {
document.getElementById('submit').disabled = false;
} else {
document.getElementById('submit').disabled = true;
}
}
//function of cancel button
function goBack() {
window.history.back();
}
//function to only choose one gendre
function onlyOne(checkbox) {
var checkboxes = document.getElementsByName('check')
checkboxes.forEach((item) => {
if (item !== checkbox) item.checked = false
})
}
</script>
<link href="RegisterartinStyle.css" rel="stylesheet">
</head>
You can use sessionStorage to store temporary data like this...
sessionStorage.setItem('Username',username);
sessionStorage.setItem('Password',password);
To retreive the data from any of your pages...
var Username = sessionStorage.getItem('Username');
var Password = sessionStorage.getItem('Password');
Blow everything away...
sessionStorage.clear();
I recently notice that I have a duplicate line on the table, when the device is spinning or calling someone on this davay at the time of pressing the 'save' button. On the lines of UserRealTime I see that the interval is a duplicate of 5-6 milliseconds.
How to avoid duplicates using javascript or jQuery. For example, check the connection of the device to the Internet?
ajax.php
<?php
if (isset($_GET['d1']) && isset($_GET['d2']))
{
$conn=connSQL();
$query = "insert into doorname(d1, d2, UserRealTime) values ('".$_GET['d1']."','".$_GET['d2']."', getdate())";
$rs=$conn->execute($query);
$rs->Close();
$conn->Close();
}
?>
JavaScript
<script>
var httpObject = null;
function getHTTPObject()
{
if (window.ActiveXObject)
{
return new ActiveXObject("Microsoft.XMLHTTP");
}
else if(window.XMLHttpRequest)
{
return new XMLHttpRequest();
}
else
{
return null;
}
}
function Inter()
{
httpObject = getHTTPObject();
if (httpObject != null)
{
var d1=document.getElementById('d1').value;
var d2=document.getElementById('d2').value;
if (d1=="" || d2=="")
{
alert("sorry!!!");
}
else
{
httpObject.open("GET", "ajax.php?d1="+d1+"&d2="+d2, true);
httpObject.send(null);
httpObject.onreadystatechange = InterSet;
}
}
}
function InterSet()
{
if(httpObject.readyState == 4)
{
var data=httpObject.responseText;
alert("Good!!!");
}
}
</script>
This way of approach it is not a suggested practice. However, just to work around the problem here is one way of handling general duplicate DB entries.
Generate one random Token on the client side for every successful server side insert. Discard the Token on client side once the server confirms the successful insert. Following is an example:
1) Generate a random Token on the client side, like so
Generate random string/characters in JavaScript
var tokenOnClientSide = makeid();
2) Attach the generated Token to Ajax Params:
httpObject.open("GET", "ajax.php?d1="+d1+"&d2="+d2+"&token="+token, true);
3) Server side: Look if the Token already exists
<?php
if (isset($_GET['d1']) && isset($_GET['d2']) && isset($_GET['token']))
{
$query = sprintf("SELECT * FROM token_table WHERE token = '%s'", $_GET['token']);
$rs=$conn->execute($query);
if (mysql_num_rows($res) == 0) {
// carry on with insert and return success message
.....
// now store the token permanently
$query = "insert into token_table(token, time_of_exec) values ('".$_GET['token']."', getdate())";
$rs=$conn->execute($query);
}
4) Finally, unset the global token on client side
tokenOnClientSide = "";
Hope that one gets a basic idea of handling duplicates.
I have set 2 min for session timeout and if it occurred the page
will redirect to a session timeout page.
However, I have some pages that could be browsed without login.
In these pages, if I leave it more than 2 min, pop out will appear asking user to log in again. User will go back to click it and it will redirect to session timeout page.
Could anyone teach me, how to get rid of this such that the pages be browsed without login should not occur session time?
ajax.js
window.onload = init;
var interval;
function init() {
interval = setInterval(trackLogin, 1000);
}
function trackLogin() {
var xmlReq = false;
try {
xmlReq = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlReq = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e2) {
xmlReq = false;
}
}
if (!xmlReq && typeof XMLHttpRequest != 'undefined') {
xmlReq = new XMLHttpRequest();
}
xmlReq.open('get', 'check.php', true);
xmlReq.setRequestHeader("Connection", "close");
xmlReq.send(null);
xmlReq.onreadystatechange = function() {
if (xmlReq.readyState == 4 && xmlReq.status == 200) {
if (xmlReq.responseText == 1) {
clearInterval(interval);
alert('You have been logged out. You will now be redirected to home page.');
document.location.href = "index.php";
}
}
}
}
firstSession
<?php
// session_start ();
if (! isset ( $_SESSION ["isLoggedIn"] ) || ! ($_SESSION ['isLoggedIn'])) {
// code for authentication comes here
// ASSUME USER IS VALID
$_SESSION ['isLoggedIn'] = true;
$_SESSION ['timeOut'] = 120;
$logged = time ();
$_SESSION ['loggedAt'] = $logged;
// showLoggedIn ();
} else {
require 'timeCheck.php';
$hasSessionExpired = checkIfTimedOut ();
if ($hasSessionExpired) {
session_unset ();
header ( "Location:index.php" );
exit ();
} else {
$_SESSION ['loggedAt'] = time ();
}
}
?>
footer.php
<?php include ('includes/firstSession.php'); ?>
<footer class="main">
<div class="wrapper container">
<div class="copyright">All Rights Reserved
</div>
<div class="logo"><img src="images/logo.png"></div>
</footer>
</div>
draft ajax.js
window.onload = init;
var interval;
function init() {
interval = setInterval(trackLogin, 1000);
}
function trackLogin() {
var xmlReq = false;
try {
xmlReq = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlReq = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e2) {
xmlReq = false;
}
}
if (!xmlReq && typeof XMLHttpRequest != 'undefined') {
xmlReq = new XMLHttpRequest();
}
xmlReq.open('get', 'check.php', true);
xmlReq.setRequestHeader("Connection", "close");
xmlReq.send(null);
xmlReq.onreadystatechange = function() {
if (xmlReq.readyState == 4 && xmlReq.status == 200) {
return json_encode(array(
'role' => $_SESSION['role'], //assuming something like guest/logged-in
'user_id' => $_SESSION['user_id']
));
var obj = xmlReq.responseText;
var jsonObj = JSON.parse(obj);
//now we can make a comparison against our keys 'role' and 'user_id'
if(jsonObj['role'] == 'guest'){
//guest role, do something here
} else if (jsonObj['role'] == 'logged-in') {
alert('You have been logged out. You will now be redirected to home page.');
document.location.href = "index.php";
//do something else for logged in users
}
I think since you have a session that is persistent whether logged in or not, you need to base your action on the username (however that is set). See if this is what you are trying to do. I have notated for clarity:
myfunctions.php
<?php
// return a session set on not set OR false if set
function is_loggedin()
{
return (!empty($_SESSION["isLoggedIn"]));
}
// Check if username is set (not sure how your usernames are stored in your session
// but that is what you want to check here
function user_set()
{
return (!empty($_SESSION["username"]));
}
// Do your set time function
function set_time_out($timeout = 120)
{
$_SESSION['isLoggedIn'] = true;
$_SESSION['timeOut'] = (is_numeric($timeout))? $timeout : 120;
$_SESSION['loggedAt'] = time();
}
function process_timeout($supRed = false)
{
// If a user has NOT already been poking around your site
if(!is_loggedin()) {
// Set the timeout
set_time_out();
return 0;
}
else {
// If a navigating user is logged in
if(user_set()) {
// Check for expire time
require('timeCheck.php');
// If they have been timed out
if(checkIfTimedOut()) {
if(!$supRed) {
// destroy the session and forward to login (or wherever)
session_destroy();
header("Location:index.php" );
exit();
}
return 1;
}
}
// Set the logged time by default
$_SESSION['loggedAt'] = time();
}
return 0;
}
header.php
<?php
include_once("includes/firstSession.php");
include_once("includes/myfunctions.php");
process_timeout();
?><!DOCTYPE html>
...etc
check.php
<?php
include_once("includes/firstSession.php");
include_once("includes/myfunctions.php");
echo process_timeout(true);
EDIT:
This is the entire script, both js and php.
// return a session set on not set OR false if set
function is_loggedin()
{
return (!empty($_SESSION["isLoggedIn"]));
}
// Check if username is set (not sure how your usernames are stored in your session
// but that is what you want to check here
function user_set()
{
return (!empty($_SESSION["username"]));
}
// Do your set time function
function set_time_out($timeout = 120)
{
$_SESSION['isLoggedIn'] = true;
$_SESSION['timeOut'] = (is_numeric($timeout))? $timeout : 120;
$_SESSION['loggedAt'] = time();
}
function checkIfTimedOut()
{
if(!empty($_SESSION['loggedAt'])) {
$active = ($_SESSION['loggedAt'] + strtotime("120 seconds"));
$now = time();
return (($active - $now) > 0);
}
return true;
}
function process_timeout($supRed = false)
{
// If a user has NOT already been poking around your site
if(!is_loggedin()) {
// Set the timeout
set_time_out();
return 0;
}
else {
// If a navigating user is logged in
if(user_set()) {
// Check for expire time
// If they have been timed out
if(checkIfTimedOut()) {
// destroy the session
session_destroy();
if(!$supRed) {
// Forward to login (or wherever)
header("Location:index.php" );
exit();
}
return 1;
}
}
// Set the logged time by default
$_SESSION['loggedAt'] = time();
}
return 0;
}
check.php:
// Include the functions here
if(!empty($_POST['getPost'])) {
echo json_encode(array("redirect"=>process_timeout(true),"sess"=>$_SESSION));
exit;
}
CALLING PAGE:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<script>
function init()
{
interval = setInterval(trackLogin, 2000);
}
function trackLogin()
{
$.ajax({
url: '/check.php',
data: { getPost: true },
type: 'post',
success: function(response) {
var instr = JSON.parse(response);
console.log(response);
if(instr.redirect == 1) {
clearInterval(interval);
alert('You have been logged out. You will now be redirected to home page.');
document.location.href = "index.php";
}
}
});
}
$(document).ready(function() {
var interval;
init();
});
</script>
EDITED
I'm trying to get some code to work for a uni assignment, I am still learning but feel like I'm going a little crazy trying to understand why a class variable is not working.
Using a PHP class such that
class Users {
//Variables
protected $_userName;
protected $_password;
protected $_login;
protected $_firstName;
protected $_lastName;
protected $_email;
protected $_phone;
protected $_addressStreet;
protected $_addressCity;
protected $_addressState;
protected $_company;
public function __construct() {
// gets the number of parameters
$numArgs = func_num_args();
$arg_list = func_get_args();
// make decisions based on the arguments number
switch($numArgs){
case "2":return $this->ConstructorWithTwoArgs($arg_list[0], $arg_list[1]);
case "10":return $this->ConstructorWithTenArgs($arg_list[0], $arg_list[1],$arg_list[2], $arg_list[3],$arg_list[4], $arg_list[5],$arg_list[6], $arg_list[7],$arg_list[8], $arg_list[9]);
default:
//Handle exception for method not existing with that many parrams
break;
}
}
//In order to log in we require minimum of user name and password
protected function ConstructorWithTwoArgs($userName, $password){
$this->_userName = $userName;
$this->_password = $password;
$this->_login = "false";
return $this;
}
//Checks users details and updates user details if valid
public function DoLogin(){
$result = false;
// Check if userName and password exist in the db
$query = "SELECT * FROM SIT203Users WHERE USER_NAME = :userName AND PASSWORD = :password";
// Create a new connection query
$ds = new Connection();
$ds->parse($query);
$ds->setBindValue(':userName', $this->_userName);
$ds->setBindValue(':password', $this->_password);
$ds->execute();
//User exists if rows are returned there will only be one as userName is unique
if($ds->getNextRow()){
$result = true;
$this->_login = "true";
$this->_firstName = $ds->getRowValue("FIRST_NAME");
$this->_lastName = $ds->getRowValue("LAST_NAME");
$this->_email = $ds->getRowValue("EMAIL");
$this->_phone = $ds->getRowValue("PHONE");
$this->_addressStreet = $ds->getRowValue("ADDRESS_STREET");
//Ensure all street details are obtained
if($ds->getRowValue("ADDRESS_STREET2"))
$this->_addressStreet .= $ds->getRowValue("ADDRESS_STREET2");
$this->_addressCity = $ds->getRowValue("ADDRESS_CITY");
$this->_addressState = $ds->getRowValue("ADDRESS_STATE");
$this->_company = $ds->getRowValue("COMPANY");
}
$ds->freeResources();
$ds->close();
return $result;
}
}
Now this class works fine for a direct call to it from;
http://www.deakin.edu.au/~jtparker/SIT203/xyz/flower_shop2/MyAccount.php?userName=JaieP&password=jp
<?php
require_once('initialise.php');
// Need to Validate all feilds and remove unwanted text
// The feilds to be tested are the $_REQUEST values
$userName = Validation::validateString(isset($_REQUEST['userName'])?$_REQUEST['userName']:"");
$password = Validation::validateString(isset($_REQUEST['password'])?$_REQUEST['password']:"");
$remberMe = isset($_REQUEST['remberMe'])?$_REQUEST['remberMe']:"";
// Create a new user
$newUser = new Users($userName, $password);
// Try and login
$newUser->DoLogin();
if($newUser->getLogin() == "true")
{
$_SESSION['user'] = $newUser;
// Echo out the users details plus cart details for last 3 months
//test its working to here
//echo($newUser->toString());
echo("Its working!!!");
}
else
{
//echo("falseValue");
echo($userName.$password.$remberMe.$newUser->getLogin().$newUser->getUserName().$newUser->DoLogin().$newUser->toString());
}
?>
But when I try to use it via a javascript call using the below code the _login variable fails to update and for the life of me I can't work out why?
as can be seen from this link;
http://www.deakin.edu.au/~jtparker/SIT203/xyz/flower_shop2/myaccount.html
it fails every time?
Any ideas
Many thanks in advance
Jaie
function TryLogin(){
try{
// Get the userName and password supplied
var userName = document.getElementById( "userName" );
var password = document.getElementById( "password" );
// Get the remember me value
var rememberMe = document.getElementById( "rememberMe" );
// Get the error feild
var errorDisplay = document.getElementById( "submitError" );
// set to no error
errorDisplay.innerHTML = "";
var documentMyAccount = document.getElementById( "myAccount" );
// Submit details to server for verification if not empty
if(userName.value != "" && password.value != ""){
// Now check via DB if username and password are valid
if (window.XMLHttpRequest)
{ // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{ // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
// IF Response indicates a successful login
var myResponse = xmlhttp.responseText;
if(myResponse != "falseValue"){
// set to nothing
documentMyAccount.innerHTML = "";
// add php content
documentMyAccount.innerHTML = myResponse;
}
else{
// Do not advise what details are incorrect, just that some combination is incorrect
errorDisplay.innerHTML = "Sorry those details are not correct";
}
}
}
var submitString = "MyAccount.php?";
submitString +="userName="+userName.value;
submitString +="&password="+password.value;
submitString +="&rememberMe="+rememberMe.checked?"true":"false";
xmlhttp.open("GET",submitString,true);
xmlhttp.send();
}
else{
errorDisplay.innerHTML = "Not all details have been entered!";
}
}
catch(error){
alert(error.message);
}
}
You simply have to debug what's the final URL that is being called by your AJAX and confirm if everything is being sent as you expect and that will solve it.
Try
console.log(submitString)
before your AJAX call and you'll know if everything is being sent correctly.
In this Code i try to get the value from text-field and dropdown listbox , I get values dynamically from user and send that value to webserices, In Given code get the value pass that values to webservice through javascript, but script didn't reponse to that code.. any one help me to fix this problem.
Here Code:
<body style=" "><script type="text/JavaScript" >
var xmlhttpuserid;
functionmyFunction() {
var checkid=new Array();
var userid = document.getElementById("userid").value;
for(var i=0;i<2;i++)
{
if(document.getElementById('domainid'+i).checked==true)
{
checkid[i]=document.getElementById('domainid'+i).value;
alert(checkid);
}
}
// var domainid = document.getElementById("").value;
//alert(userid);
var url= "../webservice/Passwordstation/ws_userauthpwdstation.jsp? userid="+userid+"&domain="+checkid;
alert(url);
xmlhttpduserid=GetXmlHttpObject();
if (xmlhttpduserid==null)
{
alert ("Your browser does not support Ajax HTTP");
return;
}
xmlhttpduserid.onreadystatechange=getuserid;
xmlhttpduserid.open("GET",url,true);
xmlhttpduserid.send(null);
}
function GetXmlHttpObject()
{
//alert("GetXmlHttpObject1");
if (window.XMLHttpRequest)
{
return new XMLHttpRequest();
}
if (window.ActiveXObject)
{
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}
function getuserid()
{
if (xmlhttpduserid.readyState==4)
{
var text=xmlhttpduserid.responseText;
//alert(text);
text=text.replace(/^\s+|\s+$/g,"");
// alert("Text 2"+text);
if(text.match("SUCCESS"))
{
alert("Authenticate successfully");
window.location="accountmain.jsp";
}
else
{
alert("Please check your User id");
}
}
}
I hope this will help you .
You can get them in java script and pass them in the query as query parameter as already doing for user id .
// var domainid = document.getElementById("").value;
//alert(userid);
var textboxval = document.getElamentById("mytextbox").value;
var dropDown = document.getElementById("ddlViewBy");
var dropDownValue= dropDown.options[dropDown.selectedIndex].value;
var url= "../webservice/Passwordstation/ws_userauthpwdstation.jsp? userid="+userid+"&domain="+checkid&textboxvalue="+textboxval&selectedFromDropDown="+dropDownValue;