PHP: why does my flood prevention script lag? -


thank reading.

i have input field sends contents in xmlhttprequest php script. script queries database post data field , returns results.

because xmlhttprequest invoked using onkeyup, typing in lengthy value sends several calls in short period. combat wrote code creates timestamp, loads session, sleeps, rechecks timestamp. if timestamp has increased, means subsequent call made , script should abort. otherwise script executes. here code.

$micro = microtime(true); $_session['micro'] = $micro; usleep(500000); // half second if ($micro < floatval($_session['micro'])) {     // later call has been made, abort     echo 'abort';     exit; } else {     // okay execute } 

the code appears work expected @ first. if add or remove character or 2 input field result appears quickly.

however if type 12 characters fast can there large delay, 2 or 3 seconds long.

i working on localhost, there no connection issues. query small, grabbing 1 column containing single word specific row.

i have set xmlhttprequest asynchronous, should fine.

xmlhttp.open("post","/test/",true); 

if remove flood prevention code, typing in field returns results instantly - no matter how , how type.

it's if usleep() keeps stacking or something.

i came code on own, best @ level. no idea why isn't behaving expected.

help appreciated, thanks!

when open session using session_start(), php locks session file subsequent requests same session while request has open blocked until session closes (you right "stacking" suspected happening).

you can call session_write_close() close session , release lock won't in situation.

what's happening each time key pressed, request gets issued , each 1 backed while previous 1 finishes, once session released 1 of other requests opens session , sleeps, , keeps happening until they've finished.

instead, i'd create global variable in javascript indicates whether or not request in progress. if 1 is, don't send request.

something this:

<script> var requesting = false;  $('#input').on('keyup', function() {     if (requesting) return ;      requesting = true;     $.ajax({         url: "/url"       }).done(function() {         requesting = false;     }); } </script> 

Comments

Popular posts from this blog

c# - How Configure Devart dotConnect for SQLite Code First? -

java - Copying object fields -

c++ - Clear the memory after returning a vector in a function -