Jump to content

preventing double clicking of submit button on forms - headache !


ajoo
 Share

Recommended Posts

Hi, I am trying to achieve preventing double clicking of submit buttons on php forms because double clicking causes the user to logout. 

 

After checking on the net i found that only javascript can be used for that purpose and came across this article here:-

 

http://www.webdeveloper.com/forum/showthread.php?28560-How-to-prevent-double-clicking-a-form-button

 

However when i tried it, well it stopped the user from logging out but for some reason the form is no longer submitting. i.e. this.form.submit() part of it seems not to be functioning. 

 

I was actually looking for something as simple as this for my code. Can someone point me in the right direction. A simple example that works would be great !

 

Thanks.

Link to comment
Share on other sites

This is really simple. Just disable the submit button after the form has been submitted. Here's a simple example. It will probably be that fast you won't even notice that the button is disabled after clicking it.

<html>
<head>
<title>Test</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
	// do stuff when the submit button is clicked
	$('form[name="myform"]').submit(function(e)
	{
		// disable the submit button 
		$('input[type="submit"]').attr('disabled', true);
		// submit the form
		return true;
	});
});
</script>
</head>
<body>
<form method="post" name="myform">
<p>Field 1</p>
<p><input type="text" name="field1" size="100" value="entry1" readonly></p>
<p>Field 2</p>
<p><input type="text" name="field2" size="100" value="entry2" readonly></p>
<p><input type="submit" name="submit" value="submit"></p>
</form>
</body>
</html>
Link to comment
Share on other sites

After checking on the net i found that only javascript can be used for that purpose

 

 

Not completely true,

 

While Javascript is the only way to dynamically stop a form from sending at all, there's another method using PHP where you compare a token or nonce to a value in the session and then just don't process it if it's a repeat.

Link to comment
Share on other sites

I think this is mostly unnecessary. Sure, if the form is submitting data that goes into a database then using an INSERT IGNORE query to prevent duplication is fine. However the OP states

 

 

Hi, I am trying to achieve preventing double clicking of submit buttons on php forms because double clicking causes the user to logout.

 

Why is a user being "logged out" (is a session being destroyed?) based on a double button click. I would be investigating this as opposed to trying to implement a quick hack.

Link to comment
Share on other sites

Hi barrikor, I tried using the unique token method but that does not prevent the double click from logging me out. 

 

Yes this does cause a data to be entered into a database but the problem of duplication is not the real problem since I get logged out. The problem is to prevent / cause to ignore the second click ( double click) totally. 

 

The logging out takes places because I have a session count which if it exceeds 2( >2) , it causes the program to logout. So a double click kind of triggers that. Actually I have been studying to implemented a login system where if a user is already logged in elsewhere ( on machine A, another browser on the same machine ) and tries to login from another machine (machine B or another browser on Machine A), he gets logged out from the first ( machine A / browser). That logic causes the successive clicks to log the user out. 

 

Implementing the solution here : http://www.webdevelo...g-a-form-button does prevent the second click but alas the data does not get submitted somehow. I must mention that I am very new to javascript with little knowledge of it. Hence I wanted a PHP solution or one involving as little as possible JS ( something that I understood easily)

 

Any more ideas.  Thanks loads.

Link to comment
Share on other sites

you need to stop creating new threads for the same problem.

 

you also need to determine exactly why the logout occurs. it's more likely that you are changing the host-name/sub-domain part of the url (www.domain.com vs domain.com) due to the multiple page requests/responses and the session is no longer matching the url of the last page request.

 

to reiterate something from one of your earlier threads about this problem - nothing a user can normally do on a site should cause them to be logged out. if you have such a problem, you need to find what is causing it and fix it. putting a band-aid over the top of the problem, such as trying to prevent double-clicking doesn't fix the problem and won't work in all cases. the problem is not being caused by the double-clicking. that's just a symptom. the problem is what your code is doing in response to the multiple page requests.

Link to comment
Share on other sites

Hi Mac, No this is a different problem. The earlier problem involves the jquery login panel which falls down on button / menu click. That has nothing to do with a double click. I have in fact put that on a website whose link I have already put on that query. If you visit that link you can see the problem in action. In fact I think both problems can be seen there. the double click as well as the login panel sliding down on button and menu clicks. 

 

Yea ok so i have just checked it out on the website and both these problems can be seen there.

 

The link is : www.bestbet.bugs3.com/club/demo 

Username is "Itsme" (without quotes) and password is bcf134

 

I'ld also like to mention that I am very close to solving the panel drop problem. I think I now have an idea why that is occurring because I have been working on it and slowly eliminating portions one by one. So I think that would be solved. 

 

The double clicking problem is not really a problem. All I need is to be able to prevent the second click to be ignored even if for a short ( few seconds time). So thats what I was trying to ask help for here. 

 

So these are two disparate problems. Thanks all ! 

Link to comment
Share on other sites

not too many people are going to visit an unknown site posted in a forum and login just to observe the symptoms.

 

also, seeing the problems occur from the client side doesn't tell us what the server side code is doing, which is where the session is being maintained. about the only things you can do from the client side would be to check if the session id is changing (which it might intentionally be doing if you are regenerating it, so that won't even tell us anything) or if your page is redirecting/refreshing and the url is changing in such a way as to no longer match where the session was first started.

 

the fact that a stripped down version of your code still exhibits the problems says the problem is somewhere in your core code, which we still haven't seen.

Link to comment
Share on other sites

Hi Mac_gyver & the rest. Thanks for all the inputs so far. 

 

So the panel falling down problem is finally solved.  

 

I put the boiled down version of the site out there because someone on the jquery forum asked me to do so as he did not wish to receive an email of the zipped file for reasons as stated by mac_gyver. He however was willing to look it up on a site. This is not a sessions problem. 

 

The problem is that i wish to ignore the second double click for a short while ( like 1-2 seconds). This can be achieved by disabling the submit button for a short while after its been clicked once. That's all I wish to achieve.

 

So i researched quite a bit and found that I need to use the following

 

(A)   <input name="submitButton" id="submitButton" type="submit" value="Submit"onclick="this.disabled=true;this.form.submit();" /> 

or the 2nd  version 

(B)     this.disabled=true;if(this.form.onsubmit()){this.form.submit();}else{this.disabled=false;}

 

with a NOTE 

 

NOTE:
If in your code, you are using the following to check if the form has been submitted:

if (isset($_POST['submitButton'])) { echo "Form submitted!"; }

It will need to be replaced by the following:

if ($_SERVER['REQUEST_METHOD'] == "POST") { echo "Form submitted!"; }

Well (A) above definitely solves the logging out problem. So it does ignore the 2nd click for a very short while as it submits the form but THE FORM SUBMIT IS NOT DETECTED BY ITS HANDLER ROUTINE. For eg I submit the empty form and the handler is supposed to display an error message which I do not receive. So the handler is unable to catch the form submission. 

 

Well that solves one problem and creates another. Can anyone suggest something here. I have tried both 

 

if (isset($_POST['submitButton']) and if ($_SERVER['REQUEST_METHOD'] == "POST")  with 

 

to catch the $_post array but none seems to work,

 

Thanks all !

Link to comment
Share on other sites

ummm. the reason your code is no longer logging you out is because your server side code is no longer being executed and whatever it is doing to cause the logout is no longer being triggered.

 

the  if($_SERVER['REQUEST_METHOD'] == "POST"){ ... }, assuming your form is using method='post', would have detected the form submission (you can also put a hidden field into the form that you can detect.)

 

at this point, without seeing your form and form processing code that reproduces the problem, no one can help you.

Link to comment
Share on other sites

Hi all !

 

Neil I have just tried your code. Sorry  I was looking for a javascript solution but have not found one so far. So finally I tried it. It seems to work though earlier I could not figure it out. I have implemented in an example below. 

 

What I have is a form which has 3 buttons. The problem now is that of figuring which of those buttons is being triggered which I think would need a hidden field as Mac has just suggested. I would be glad if you can show me how to do that for 3 buttons on a form.

 

Here's the code using Neil's jquery solution.   

<?php

if($_SERVER['REQUEST_METHOD'] == "POST")
 {
     echo "<pre>"; print_r($_POST) ;  echo "</pre>";
  if(isset($_POST['but1'])&& $_POST['but1']=='SUBMIT1')                                 // && $_POST['myButton'] == "myButton")
    {
      echo " Submittin -- But1 Caught <br>";
      echo "Submit =  ".$_POST['but1'];
    }
    
  if(isset($_POST['but2']))             // && $_POST['but2']=='SUBMIT2')                                 // && $_POST['myButton'] == "myButton")
    {
      echo " Submittin -- But2 Caught <br>";
      echo "Submit =  ".$_POST['but2'];
    }
    
  if(isset($_POST['but3']) && $_POST['but3']=='SUBMIT3')                                 // && $_POST['myButton'] == "myButton")
    {
      echo " Submittin -- But3d Caught <br>";
      echo "Submit =  ".$_POST['but3'];
    }

    
 }else echo "POST Not caught";
 

?>

<head>
<title>Test</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
        // do stuff when the submit button is clicked
        $('form[name="myform"]').submit(function(e)
        {
                // disable the submit button
                $('input[type="submit"]').attr('disabled', true);
                // submit the form
                return true;
        });
});
</script>
</head>

<form name = "myform" action = "button5.php" method = "post" >

<p>First Name: <input type="text" size="32" name="firstname"></p>
<p>Last Name: <input type="text" size="32" name="lastname"></p>
<p><input type="submit" name="but1" value = "SUBMIT1" ></p>
<p><input type="submit" name="but2" value = "SUBMIT2" ></p>
<p><input type="submit" name="but3" value = "SUBMIT3" ></p>

</form>

Since I have been hunting for a javascript solution I tried the following as well. This does not seem to work for more than one button . I'll put this here too just in case anyone has some ideas on improving this and getting it working. Would be great !

<?php


if($_SERVER['REQUEST_METHOD'] == "POST")
 {
//    echo "<pre>"; print_r($_POST) ;  echo "</pre>";
  if(isset($_POST['but1'])&& $_POST['but1']=='SUBMIT1')                                 // && $_POST['myButton'] == "myButton")
    {
      echo " Submittin -- But1 Caught <br>";
      echo "Submit =  ".$_POST['but1'];
    }
    
  if(isset($_POST['but2']))             // && $_POST['but2']=='SUBMIT2')                                 // && $_POST['myButton'] == "myButton")
    {
      echo " Submittin -- But2 Caught <br>";
      echo "Submit =  ".$_POST['but2'];
    }
    
  if(isset($_POST['but3']) && $_POST['but3']=='SUBMIT3')                                 // && $_POST['myButton'] == "myButton")
    {
      echo " Submittin -- But3d Caught <br>";
      echo "Submit =  ".$_POST['but3'];
    }

    
 }else echo "POST Not caught";
 

?>

<script type="text/javascript">

function locksubmit(button) {
    var oldValue = button.value;

    button.setAttribute('disabled', true);
    button.value = '...processing...';

    setTimeout(function(){
        button.value = oldValue;
        button.removeAttribute('disabled');
    }, 500)
}
</script>


<form action = "button3.php" method = "post" >

<p>First Name: <input type="text" size="32" name="firstname"></p>
<p>Last Name: <input type="text" size="32" name="lastname"></p>
<p><input type="submit" name="but1" value = "SUBMIT1" id = "but1" onclick = "locksubmit(this)"></p>
<p><input type="submit" name="but2" value = "SUBMIT2" id = "but2" onclick = "locksubmit(this)"></p>
<p><input type="submit" name="but3" value = "SUBMIT3" id = "but3" onclick = "locksubmit(this)"></p>

</form>

Thanks you all.

Link to comment
Share on other sites

Hi Guys !

 

Thanks for the inputs and Neil you are absolutely correct that the above line of code would disable temporarily all the buttons. I too observed that while I was trying to figure things out with these buttons. So while it disables the buttons, it does not send any information of the button that was actually pressed. The $_POST array does not contain any information that would indicate which of the tree buttons was actually pressed. Here's the version :-

<?php

if($_SERVER['REQUEST_METHOD'] == "POST")
 {
     echo "<pre>"; print_r($_POST) ;  echo "</pre>";
  if(isset($_POST['but1'])&& $_POST['but1']=='SUBMIT1')                                 // && $_POST['myButton'] == "myButton")
    {
      echo " Submittin -- But1 Caught <br>";
      echo "Submit =  ".$_POST['but1'];
    }
    
  if(isset($_POST['but2']))             // && $_POST['but2']=='SUBMIT2')                                 // && $_POST['myButton'] == "myButton")
    {
      echo " Submittin -- But2 Caught <br>";
      echo "Submit =  ".$_POST['but2'];
    }
    
  if(isset($_POST['but3']) && $_POST['but3']=='SUBMIT3')                                 // && $_POST['myButton'] == "myButton")
    {
      echo " Submittin -- But3d Caught <br>";
      echo "Submit =  ".$_POST['but3'];
    }
 }else echo "POST Not caught";

?>

<head>
<title>Test</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
        // do stuff when the submit button is clicked
        $('form[name="myform"]').submit(function(e)
        {
                // disable the submit button
                $('input[type="submit"]').attr('disabled', true);
                 // submit the form
                return true;
        });
});
</script>
</head>

<form name = "myform" action = "button5.php" method = "post" >

<p>First Name: <input type="text" size="32" name="firstname"></p>
<p>Last Name: <input type="text" size="32" name="lastname"></p>

<p><input type="submit" name="but1" value = "SUBMIT1" ></p>
<p><input type="submit" name="but2" value = "SUBMIT2" ></p>
<p><input type="submit" name="but3" value = "SUBMIT3" ></p>

</form>

So working with this code I added a hidden field which I could then check to find which button was actually pressed. I will just paste the HTML bit of the code for brevity since the rest is the same. So here's the code with the hidden field.

<form name = "myform" action = "button5a.php" method = "post" >

<p>First Name: <input type="text" size="32" name="firstname"></p>
<p>Last Name: <input type="text" size="32" name="lastname"></p>
<Input type ="hidden" name="hidbut" value="" id="hidbut">
<p><input type="submit" name="but1" value = "SUBMIT1" onclick="document.getElementById('hidbut').value='SUBMIT1'" ></p>
<p><input type="submit" name="but2" value = "SUBMIT2" onclick="document.getElementById('hidbut').value='SUBMIT2'" ></p>
<p><input type="submit" name="but3" value = "SUBMIT3" onclick="document.getElementById('hidbut').value='SUBMIT3'" ></p>

</form> 

and when I ran this code, not only did i get the correct value of the button in the hidden field but surprisingly I also got the submit button value which i did not expect. And greater wonder ( though disappointing) still the temporary disabling of the buttons just vanished !!! I tried a lot of variations but I failed to get that what i wanted which is once again:

1. When any button is pressed, it should submit the $_POST data with the submitted button information ( as a hidden field OR as name pair value)

2. that button should be temporarily, for a short duration, disabled , with an intermediate button state with value changed to say ..wait..

3. The button handler should do the needful and change the state of the button back to Submit just before exiting the button handler routine. 

 

Its ok if all buttons are temporarily reset or just that particular button. 

 

Thanks for the patience everybody. I am really a beginner in JS so I may be trying all wrong.

I really hope that someone can help me solve this. 

 

Thanks loads everybody.

Edited by ajoo
Link to comment
Share on other sites

Don't use inline javascript with jQuery as you are doing. Here is the code that will do exactly what you are asking. Run it as test.php or whatever

<html>
<head>
<title>Test</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
	// do stuff when the form is submitted
	$('form[name="myform"]').submit(function(e)
	{
		// disable the submit button 
		$('input[type="submit"]').attr('disabled', true);
		$('input[type="submit"]').val('Please Wait');
		// submit the form
		return true;
	});
	// when a submit button is clicked
	$('input[type="submit"]').click(function() {
		$('input[name="button_value"]').val($(this).val());		
	});

});
</script>
</head>
<body>
<?php if(isset($_POST['action']) && $_POST['action'] == 'submit'): ?>
<p>The button that was clicked was <?php print $_POST['button_value']; ?></p>
<?php endif; ?>
<form method="post" name="myform">
<input type="hidden" name="button_value" value="">
<input type="hidden" name="action" value="submit">
<p>Field 1</p>
<p><input type="text" name="field1" size="100" value="entry1" readonly></p>
<p>Field 2</p>
<p><input type="text" name="field2" size="100" value="entry2" readonly></p>
<p><input type="submit" name="submit" value="submit 1"></p>
<p><input type="submit" name="submit" value="submit 2"></p>
<p><input type="submit" name="submit" value="submit 3"></p>
</form>
</body>
</html>

I do have the following issues with your PHP and methodology

 

1. Why have you got 3 buttons in the same form? Doesn't matter which one is clicked they will all submit the same data. If clicking button 1 is to perform a different action to button 2 then use links with url parameters, not form buttons.

2. When a form is submitted don't test for the value of a button to perform an action. Put a hidden field in the form that you can use to test that the form has been submitted. If you change the value of the button, you break your code.

3. When a form has been submitted and your server side code validates the data, once it has completed the page should be reloaded or a user should be redirected somewhere. This will prevent a page refresh from submitting the same data. This is done using a header() i.e

header('Location/thankyou.php');
Edited by neil.johnson
Link to comment
Share on other sites

my last attempt to get you to find the cause of the problem and stop wasting time with javascript as a fix (it's been a week+ since your first thread about logging out when a form is submitted.)

 

based on actual information you have finally shown and that you are just now attempting to tell the server side code which submit button has been used (or more likely which form out of multiple forms has been submitted), i can state with 98% certainty what is wrong with your side code that is causing the problem.

 

you have three things to fix that is causing the logout -

 

1) your form(s)/submit button(s) are not uniquely identified and/or your current server-side code isn't using anything to control which of the form processing logic is executed. it's likely that any form submission at all, is running your login form processing code and since at that time there isn't any username/password, the login fails and actually logs the current user out.

 

2) your form processing code isn't validating the submitted data, so an empty username/passowrd causes the login to fail, when in fact you should never try to log someone in if they left the username/password empty.

 

3) your login form and login form processing code should not be active at all if the current user is already logged in.

 

and here's why this javascript you are trying to add won't fix the problem. let us say that you do manage to get the form submit buttons to be disabled for an amount of time. what will happen when they become enabled and someone submits a form? exactly that same thing that is currently happening. your current form processing logic will run all/or at least for the login logic, there will be no username/password submitted in this case, the login logic will fail to find a matching user and log the current user out.

Edited by mac_gyver
Link to comment
Share on other sites

Hi guys ! Thanks very much for all the inputs so far. 

 

Neil your solution works except that all buttons get disabled together - like i said was ok -but i am sure that can be changed to ensure that the one pressed gets disabled and displays the waiting message. So thanks loads. To answer your questions.

- Why 3 buttons  ----- because i designed the form like that. It loads a record from a DB and then the next or previous records can be displayed from there on using the next and previous buttons. Then if the edit button is pressed, the form can be edited and two further buttons update and cancel can be used to update or cancel the record. 

- If the problem of double click was to be ignored for the moment, then its fairly easily to detect the button clicked using php.

- once the button handler has done its job, I remain on the same page. I am not using any redirection. I have already said what the buttons do. 

Since you have been so kind and helpful I have actually changed the code on the website to show you the functioning of my form. If you feel it's ok then please try out the working of the form on www.bestbet.bugs3.com/club/demo.php. The login and password are once again "Itsme" and "bcf134". 

There if you go to the gallery, you'll see the submit form. A right div has a small search box. Type any alphabet and press enter and that would load the form and the new buttons will appear. -- PREV - EDIT - NEXT and you can check their usage.  

If you double click on any buttons, you'll get logged out. That's another issue and the main reason I was trying to disable the buttons temporarily.

Maybe you can give me some suggestion then as regards the design of the form. 

 

Mac_gyver thanks for being so persistent trying to think out the real cause of the logout. I was in fact trying to find a temporary solution in disabling buttons so that I could get on with the rest of it and then come back to the logout problem. I have in fact tried to look into all the 3 reasons that you have mentioned. Quite frankly I am sure that there is no conflict in the button names. If there was a conflict then the buttons would not work at all. The conflict would show up even on a single click. So the buttons are uniquely identifiable.

My form validating code does validate the user and checks for blank username and password fields etc and the usual for email etc. 

I am not sure about the last one because I don't know what you mean by "login form processing code should not be active". But i don't think because it checks for a logged in user and login & register modules are only activated by the login and register modules which can be activated only by the respective button clicks on the login and register panel.

 

Mac if you would like to have a look at the files I would be happy to send them across to you. I too am flummoxed by this logout. I tried to segregate the code as much as I could to try and locate the reason for this logout but so far no luck. 

 

One thing that has really surprised me is the fact that there is no real simple -short n sweet - solution to the double click issue in HTML. I searched so much on the net and tried so much code till NEIL was kind enuff to help me using jquery. I may or may not be able to use it but i am grateful for it was a great learning experience.

 

MAC I sure wish you'ld allow me to send you the files to have a look at them.  

 

Thanks all for all the help and inputs to this so far. 

Edited by ajoo
Link to comment
Share on other sites

Hi guys !! So I have started once again to unravel the reason for the logging out that occurs when i double click the buttons or the menu buttons. The reason for that is that disabling buttons is a temporary solution and some sort of bug would remain in the program. Besides I would have to do the button disabling for all buttons on all forms. So might as well try and nip it at the bud. Inspiration ofcourse was from Mac_Gyver. 

 

So still more help is needed. I am doing it all from the beginning trying to see where the problem lies. I have a sliding login panel and at the very end of it I have added the web page as follows:-


</div> <!--panel -->

<?php if($_SESSION['usr']): ?>
<? include("member_1.php") ?>
<? endif; ?>

</body>

The structure of member_1.php is as follows:-

<?php
// error_reporting(E_ALL & ~E_NOTICE);
//if(!defined('INCLUDE_CHECK')) die('member_1.php cannot run directly');
define('INCLUDE_CHECK',true);
require_once 'f_load_1.php';

session_start();
session_regenerate_id(true);

include_once("include/fra_header.php");
include_once("include/fra_navbar.html");

$page = $_GET['page'];
switch ($page)
    {
        case "members":
        include_once("include/clubmem.php");
        break;

        default:
        include_once("include/home.php");
        break;
    }

 include_once("include/fra_footer.html");
?>

Members.php and home.php can be simply one line files echoing "members" and "home" respectively. 

 

The question is that since i am including the member_1.php in the main login file would I need to do a session_start and session_regenerate_id in member_1.php and for that matter in the home.php and clubmem.php like we need to for files that are accessed via a link to ensure the session integrity. 

 

If not then does it mean that if files are included like I have done, the session integrity is maintained thru all the files that are loaded vai includes ( like home,php is via member_1.php.)

 

Once I am clear on this I can proceed forward. Thanks all !  

Link to comment
Share on other sites

for the most part, you are posting to yourself. your threads haven't gotten many replies at all and nothing has been resolved because you are not making it easy for anyone to help you. the information and code you have posted isn't complete and certainly doesn't show any of the information needed to reproduce or debug the stated problems. the reason we cannot directly help you with any of the problems is because there can be many different things your code could be doing that is causing any one symptom. there is not a one to one relationship between any symptom and what is causing it. based on the symptom we cannot tell you what to fix without narrowing down the cause of the problem and it takes knowing what your code is doing to narrow down what in it is causing any symptom.

 

even the above code is the tail end of the problem. that's your code that is producing the content on the page based on the user being logged in via a session variable. that shows nothing that would allow anyone to help you with the log out problem.

 

the only things i can tell from the above posted code are -

 

1) you are trying to use php to copy/pasting together a site and are inconstant or are just not looking at or understand your code. you have short and full opening php tags. you have include, include_once, and require_once statements. you are sometimes using the () and other times not with the include, include_one, and require_once statements. you are leaving out the closing ; on some statements right before a ?> tag. you are mixing traditional logic syntax with alternate logic syntax.

 

2) even if the commented out error_reporting() statement was in effect, it is not showing all the php errors and you can be missing out on some error messages that would help pin down the problem. without that statement, php is not help you at all.

 

3) your member_1.php code should only be accessible if the current member is logged in. why have you commented out the code that would prevent direct access to it? and why then have you defined the 'INCLUDE_CHECK' constant in the member_1.php code?

 

4) if the member_1.php code can only be accessed by a logged in member via the $_SESSION['usr'] variable check code, why do you have a session_start() statement in the member_1.php code? the only way member_1.php can be included is if the session was already started. also, by having a session_start() statement after you have output html content (after you have output anything) to the browser, it won't work. the session_start() statement must go before any thing at all has been output on the page.

 

some suggestions -

 

you need to have php's error_reporting set to E_ALL and display_errors set to ON so that php will help you by reporting and displaying all the errors it detects. you should set these before most of your php code so that any problems detected in any of your php code will be reported. the preferable place to set these is in your php.ini file so that even php syntax errors will get reported and so that you don't need to remember to put them into your code for debugging and remember to remove them when the code is put onto a live server (you don't want to give hackers the information contained in the php error messages.)

 

you should only have one session_start()/session_regenerate_id(true) statement and they must go before you output anything to the browser. i.e. they would normally be near the start of your main file or be in a file that you include near the start of your main file.

 

you need to prevent direct access to all the included files, either by using the defined constant method or by putting the included files into a folder where direct access is not permitted.

 

back to your logout symptom. there's three main possibilities -

 

1) the session variable remembering that the current user is logged in is not actually part of a session. this could be caused by a session_start() statement that is failing (there would be php error messages.) the symptom of this would be that you are setting a variable like $_SESSION['usr'], but that variable is only present on the page where it was set. anything you do on that page looks like the log in was successful, but it is not. any action you take after that page has been displayed doesn't have any session variable and it looks like the user was logged out, when in fact the user's log in was never actually remembered by the code.

 

2) your log in is working, but code on your page is logging the user out so that any action you take next will be met with an indication that the user has been logged out, when in fact they were previously logged out, on the previous page request, and you are only being notified of this because you caused an action to occur, another page request, that notified you that the user wasn't currently logged in.

 

3) your log in is working, but the url's you are using in navigation/form actions no longer match the url (path or host-name) where the session was first started and the session is not carrying over to the page that is being requested.

 

in order to narrow down which of these three possibilities is causing the problem, it will take seeing your code.

Edited by mac_gyver
Link to comment
Share on other sites

Hi Mac,

 

Thanks for that great reply. Yes i am trying to put together a website login and I thought the best way would be to go ahead and do it, make mistakes and learn. I read a whole lot on sessions before I began but i guess they are quite confusing. Taking your advise I have gone through the entire code again, with error reporting on, and removed almost as many errors I could find to reduce the warnings to a bare minimum. Tried to make it as consistent as possible.  Most of the errors and inconsistencies you found were a result of a many days of changes to the code. 

 

I read an article on session security and it said that session_regenerate_id should be called on login. Hence I have sec_session_start() after login. I have tried the code with it removed but that does not prevent the logouts.

 

I was not sure if I needed the sec_session_start() on the various sub pages and I asked about that earlier:

 

The question is that since i am including the member_1.php in the main login file would I need to do a session_start and session_regenerate_id in member_1.php and for that matter in the home.php and clubmem.php like we need to for files that are accessed via a link to ensure the session integrity. 

 

If not then does it mean that if files are included like I have done, the session integrity is maintained thru all the files that are loaded vai includes ( like home,php is via member_1.php.)

 

sec_session_start() does give a notice/ warning and ignores the session_start() command in sec_session_start(); So I have removed it from all the subpages.

 

Of the three logout symptoms that you mentioned above I think its the first one because when I tried, I was unable to display the $_SESSION['usr'] value on the home page after login. So it seems that $_SESSION['usr'] is available only on demo.php and not elsewhere. I hope you can tell me why and show me how to ensure the session integrity across sub pages ( like the home page that get included via menu button ).

 

I also got two warnings on demo.php as folows: 

 
Notice: Undefined index: usr in D:\xampp\htdocs\xampp\temp\demo.php on line 302
Notice: Undefined index: id in D:\xampp\htdocs\xampp\temp\demo.php on line 305
 
and one on member_1.php
Notice: Undefined index: page in D:\xampp\htdocs\xampp\temp\member_1.php on line 22

 

I do not know how to remove these notices in the usual manner as it kind of upsets the php syntax.

 

Please find attached the demo.php and other files.

<?php
// error_reporting(E_ALL & ~E_NOTICE);
define('INCLUDE_CHECK',true);
require_once 'connect_1.php';

// connect_1.php provides the database link $link

sec_session_start();

$now = time();
//echo "INDEX  Time = ".date('d-m-Y H:i:s',$now)."<br>";     // server_mod

if(isset($_SESSION['timeout']))
{
   $is_timed_out =  is_timed_out();
   if($is_timed_out == 1)
   {
     $_SESSION['msg'] = " FROM  --- TIMEOUT ---  LINE 51";
     header ("Location: loggedout.php");
     exit;
   }
}

//// Asan1 - df2881  ///////////

/*
if($_SESSION['id'] && !isset($_COOKIE['tzRemember']) && !$_SESSION['rememberMe'])
{
        // If you are logged in, but you don't have the tzRemember cookie (browser restart)
        // and you have not checked the rememberMe checkbox:

        $err[]='You are already logged in!';
        $_SESSION['msg']['login-err'] = implode('<br />',$err);

        header("Location: demo.php");
        exit;
}
*/

if(isset($_GET['logoff']))

{       $_SESSION = array();
        session_destroy();

        header("Location: demo.php");
        exit;
}

function sec_session_start()
{
        $session_name = 'sec_session_id';
        $secure = false;
        $httponly = true;
        ini_set('session.use_only_cookies', 1); // Forces sessions to only use cookies.
        $cookieParams = session_get_cookie_params();
        session_set_cookie_params($cookieParams["lifetime"], $cookieParams["path"], $cookieParams["domain"], $secure, $httponly);   //   0, /, ''.
        session_name($session_name);
        session_start();
        session_regenerate_id(TRUE); // regenerated the session, delete the old one.
}

if(isset($_POST['submit']) && $_POST['submit']=='Login')
{

        if(isset($_SESSION['usr']))
         {
                 echo  $_SESSION['usr']. "Already Logged in ";
                 echo " You are being logged out as you have logged in from another page ";
                 session_destroy();

                 header("Location: loggedout.html");
                 exit();
         }


        $err = array();
        // Will hold our errors
        
        if(!$_POST['username'] || !$_POST['password'])
                $err[] = 'All the fields must be filled in!';
        
        if(!count($err))
        {
                $_POST['username'] = mysql_real_escape_string($_POST['username']);
                $_POST['password'] = mysql_real_escape_string($_POST['password']);
                $_POST['rememberMe'] = (int)$_POST['rememberMe'];
                
                // Escaping all input data
                
                $query = "SELECT id,Username FROM members WHERE Username='".$_POST['username']."' AND Password = '".md5($_POST['password'])."' ";
                $result = mysqli_query($link, $query);
                $row = mysqli_fetch_assoc($result);

                if($row['Username'])
                {
                        // If everything is OK login

                        sec_session_start();                            // regenerate_ID

                        // Store some data in the session
                        
                        $_SESSION['usr']=$row['Username'];
                        $_SESSION['id'] = $row['ID'];
                        $_SESSION['logged'] = 1;
                        $_SESSION['user_id'] = $row['Username'];
                        $pass = md5($_POST['password']);
                        
                        $_SESSION['rememberMe'] = $_POST['rememberMe'];

                }
                else $err[]='Wrong username and/or password!';
             }
        if($err)
        $_SESSION['msg']['login-err'] = implode('<br />',$err);
        // Save the error messages in the session

        header("Location: demo.php");
        exit;
}

   else if(isset($_POST['submit']) && $_POST['submit']=='Register')
    {
        // code to register


        header("Location: demo.php");
        exit;
}

$script = '';

if(isset($_SESSION['msg']) && $_SESSION['msg']!="")
{
        // The script below shows the sliding panel on page load
        
        $script = '
        <script type="text/javascript">
        
                $(function(){
                
                        $("div#panel").show();
                        $("#toggle a").toggle();
                });
        
        </script>';
        
}
?>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>SMASHIN CLUB </title>
    
    <link rel="stylesheet" type="text/css" href="demo.css" media="screen" />
    <link rel="stylesheet" type="text/css" href="login_panel/css/slide.css" media="screen" />
    
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    
    <!-- PNG FIX for IE6 -->
    <!-- http://24ways.org/2007/supersleight-transparent-png-in-ie6 -->
    <!--[if lte IE 6]>
        <script type="text/javascript" src="login_panel/js/pngfix/supersleight-min.js"></script>
    <![endif]-->

 <style>

  #level0 {
    background:#FC0;}
  #level1 {
    margin-left:143px;
    padding-left:9px;
    background:#FFF;}
  #level2 {
    background:#FFF3AC;}
  p { display: block; }
  
</style>

    <script src="login_panel/js/slide.js" type="text/javascript"></script>
    
    <?php echo $script; ?>
</head>

<body>

<!-- Panel -->

        <div id="panel">
        
                <div class="content clearfix">

                <?php

                        if(!isset($_SESSION['usr'])):
                        
                ?>
            
                        <div class="left">
                                <!-- Login Form -->
                                <form class="clearfix" action="" method="post">
                                        <h1>Member Login</h1>
                    
                                        <?php
                                                
                                                if(isset($_SESSION['msg']['login-err']))
                                                {
                                                        echo '<div class="err">'.$_SESSION['msg']['login-err'].'</div>';
                                                        unset($_SESSION['msg']['login-err']);
                                                }
                                        ?>
                                        

                                <label class="grey" for="username">Username:</label>
                                <input class="field" type="text" name="username" id="username" value="" size="23" />
                                <label class="grey" for="password">Password:</label>
                                <input class="field" type="password" name="password" id="password" size="23" />
                                <label><input name="rememberMe" id="rememberMe" type="checkbox" checked="checked" value="1" />  Remember me</label>
                                <div class="clear"></div>
                                        <input type="submit" name="submit" value="Login" class="bt_login" />
                                </form>
                        </div>
                        

                        <div class="left right">
                                <!-- Register Form -->
                                <form action="" method="post">
                                        <h1>Not a member yet? Sign Up!</h1>                
                    
                                        <?php
                                                
                                                if(isset($_SESSION['msg']['reg-err']))
                                                {
                                                        echo '<div class="err">'.$_SESSION['msg']['reg-err'].'</div>';
                                                        unset($_SESSION['msg']['reg-err']);
                                                }
                                                
                                                if(isset($_SESSION['msg']['reg-success']))
                                                {
                                                        echo '<div class="success">'.$_SESSION['msg']['reg-success'].'</div>';
                                                        unset($_SESSION['msg']['reg-success']);
                                                }
                                        ?>
                                            


                                        <label class="grey" for="username">Username:</label>
                                        <input class="field" type="text" name="username" id="username" value="" size="23" />
                                        <label class="grey" for="email">Email:</label>
                                        <input class="field" type="text" name="email" id="email" size="23" />

                                        <label class="grey" for="role">role:</label>
                                        <input class="field" type="text" name="role" id="role" size="23" />
                                        
                                        
                                        <input type="submit" name="submit" value="Register" class="bt_register" />


                                        <label>A password will be e-mailed to you.</label>

                                </form>

                        </div>
            
                    <?php
                        
                        else:
                        
                    ?>
            
            <div class="left">
            
            <h1>Members panel</h1>

            <a href="page2.php?varname=<?php echo $var_value ?>">Page2</a>

            <p>You can put member-only data here</p>
                <p>You can put member-only data here</p>
                <p>- or -</p>
                <a href="?logoff">Log off</a>
           </div>

            
            <div class="left right">
            </div>
            
                    <?php
                        endif;
                     ?>
           </div>
        </div> <!-- /login -->        

    <!-- The tab on top -->        
        <div class="tab">
                <ul class="login">
                    <li class="left"> </li>
                <li>Hello <?php echo $_SESSION['usr'] ? $_SESSION['usr'] : 'Guest';?>!</li>
                        <li class="sep">|</li>
                        <li id="toggle">
                                <a id="open" class="open" href="#"><?php echo $_SESSION['id']?'Open Panel':'Log In | Register';?></a>
                                <a id="close" style="display: none;" class="close" href="#">Close Panel</a>                        
                        </li>
                    <li class="right"> </li>
                </ul> 
        </div> <!-- / top -->

</div> <!--panel -->

<?php if(isset($_SESSION['usr'])): ?>
<? include("member_1.php"); ?>
<? endif; ?>

</body>
</html>

member_1.php

<?php
//error_reporting(E_ALL & ~E_NOTICE);
if(!defined('INCLUDE_CHECK')) die('member_1.php cannot run directly');
require_once'connect_1.php';
// sec_session_start();         // removing the sesion_start since already started in demo.php

if(isset($_SESSION['timeout']))
{
   $is_timed_out =  is_timed_out();         // check for timeout of a session.
   if($is_timed_out == 1)
   {
     //     echo "Timed Out from TIME OUT !";    // server_mod
     $_SESSION['msg'] = " FROM  --- TIMEOUT ---  LINE 51";
     header ("Location: loggedout.php");    // logout if timed out
     exit;
   }
}

include_once("include/fra_header.php");
include_once("include/fra_navbar.html");

$page = $_GET['page'];
switch ($page)
    {
        case "gallery":
        include_once("include/fra_gallery.php");
        break;

        default:
        include_once("include/fra_home.php");
        break;
    }

 include_once("include/fra_footer.html");
?>

fra_header.php

<?php
//error_reporting(E_ALL & ~E_NOTICE);
if(!defined('INCLUDE_CHECK')) die('header.php cannot run directly');

// sec_session_start(); // removed as already declared in demo

if(isset($_SESSION['timeout']))
{
   $is_timed_out =  is_timed_out();         // check for timeout of a session.
   if($is_timed_out == 1)
   {
     //     echo "Timed Out from TIME OUT !";    // server_mod
     $_SESSION['msg'] = " FROM  --- TIMEOUT ---  LINE 51";
     header ("Location: loggedout.php");    // logout if timed out
     exit;
   }
}

?>

<link rel="stylesheet" type="text/css" href = 'css/layout.css' media="screen">
<title> Smashin CLUB </title>

<body>

<div class = 'wrapper'>

<div class = 'header'>

<h4><br> WELCOME TO THE CLUB PANEL </br></h4>

</div>

<div class = 'lowerheader'>

        <div class='datenow'>
        <?php echo "Date: ".date("d-m-Y"); ?><br>
        </div>

        <div class='center_id'>
        <?php
           echo "<h3> CLUB : ";

           $user_id = $_SESSION['id'];

           $query = "Select city from employees WHERE ID = '$user_id'";
           $result = mysqli_query($link, $query);
               if(!$result)die('Error in accessing the Database ' . mysqli_error($link));
               else $row = mysqli_fetch_array($result);
               $city = $row['city'];
               echo "$city ";
           $sql = "SELECT room_no FROM employees WHERE ID = '$user_id'";
           $result = mysqli_query($link, $sql);
               if(!$result)die('Error in accessing the Database ' . mysqli_error($link));
               else
                {
                  $count = mysqli_num_rows($result);
                    $selcnt = 0;        // selection count
                    echo "<select name='room_no' STYLE='background-color: #efefef;' >";
                    while ($row = mysqli_fetch_array($result))
                    {
                      echo "<option value='" .$row['room_no']. "'";
                      if($selcnt == 0) echo "selected >";
                      else echo " >";
                      echo $row['room_no']. "</option>";
                      $selcnt += 1;
                    }
                echo "</select></h3>";
                }
       ?>

       </div>

        <div class='timenow'>
        <?php echo "Time: ".date("H-i-s"); ?><br>
        </div>

</div>

fra_home.php

<?php
//error_reporting(E_ALL & ~E_NOTICE);
if(!defined('INCLUDE_CHECK')) die('fra_home.php cannot execute this file directly');



$query = "SELECT * FROM $table";
$row = mysqli_query($link, $query);
?>

<div class = 'mainbody'>
<table border = 1 cellspacing =5 cellpadding = 15>

<tr><hd2><? $_SESSION['usr']."\s club listing. Session ID = ".$_SESSION['id']; ?></hd2></tr>

<tr>
<th> ID </th>
<th> Name </th>
<th> Surname  </th>
<th> City </th>
<th> Room No. </th>

</tr>

<? while ($record=mysqli_fetch_array($row))
{ ?>
<tr>
<td> <? echo $record['ID']; ?> </td>
<td> <? echo $record['fname']; ?> </td>
<td> <? echo $record['lname']; ?> </td>
<td> <? echo $record['city']; ?> </td>
<td> <? echo $record['room_no']/2; ?> </td>
<? } ?>

</table>

</div>

I hope you won't locate any syntactical errors on this one and will be able to find the root cause of the abnormal logout behavior. 

 

Thanks loads.

Edited by ajoo
Link to comment
Share on other sites

A small correction to the last one, the $_SESSION['usr'] variable is displaying across pages. I missed the echo. So unlike as i thought earlier, the $_SESSION['usr'] is able to maintain its value across pages. So it cannot be the first reason as suggested by you as i previously thought.

 

I have checked for the 3rd  as well but that does not seem to be it. 

 

I am not so sure about 2nd one and not even sure how to go about checking for it. 

 

Thanks !

Link to comment
Share on other sites

Hi all ! Thanks all for all inputs so far. especially Mac_Gyver whose really tried to help me with this one and narrowing it down. 

 

So I found some more things like missing in the code like "mysqli_free_result" and "mysqli_close" which I thought, being memory and database related, could also cause the logouts and so i went forward and put them at the appropriate places hoping that finally the unwanted logouts will cease. But to my dismay that too did not solve the problem.

 

Then I went and did the only thing that to my mind was left and that was to deactivate the session_regenerate_id command in my function sec_session_start() and lo the problem disappeared and no matter how fast I hammer on the menu or other buttons now, it does not cause unexpected logouts anymore. 

 

Unfortunately that does not end my problem because I want to use session_regenerate_id() to avoid or limit session fixation and session hijacking as far as possible. Does it mean that all programs or websites that use session_regenerate_id() command will similarly give abnormal logouts if they are using buttons or if the f5 refresh key is kept pressed?

 

So now that I know what's causing the problem, how do i resolve it. How should I use session_regenerate_id() and ensure that it won't cause logouts.

 

Looking for someone to shed some light on this;

 

Thanks all !

Link to comment
Share on other sites

This thread is more than a year old.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

 Share

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.