This question already has answers here:
PHP session timeout script [duplicate]
(4 answers)
Closed 8 years ago.
I am writing a project in PHP, JavaScript and HTML. I have successfully done the automatic logout when the user is idle for 1 minute. But the problem comes in that I have to refresh the page for it to be executed and log me out.
Can somebody help me so that immediately 1 minute is over and the user is idle, the code will be executed and it will take me to the login page without me refreshing it?
Here is my code:
// check to see if $_SESSION['timeout'] is set
if(isset($_SESSION['timeout']) ) {
$session_life = time() - $_SESSION['timeout'];
if($session_life > $inactive)
{
echo"<script type='text/javascript'>
window.alert('Your Session got Expired');
</script>";
header("Location: logout.php");
}
}
$_SESSION['timeout'] = time();
//Continuation of other codes
I guess the best way to implement is by using the combination of JS and PHP
check.php
if(isset($_SESSION['timeout']) ) {
$session_life = time() - $_SESSION['timeout'];
if($session_life > $inactive) echo "0";
else echo "1";
}
$_SESSION['timeout'] = time();
.js
$(document).ready(function(){
setTimeout(function(){
$.get("check.php", function(data){
if(data==0) window.location.href="logout.php";
});
},1*60*1000);
});
Or just wrap it in setInterval(function(){},1*60*1000) instead of setTimeout() if you want it to be checked after every one minute.
$(document).ready(function(){
setInterval(function(){
$.get("check.php", function(data){
if(data==0) window.location.href="logout.php";
});
},1*60*1000);
});
You can't do that with php. You need to count time in javascript and make ajax request after that. Simplest way is probably use jQuery plugin like IdleTimeout.
PHP code needs to be called/run to execute... It wont run in the background unless something is running it..
You have a few options:
1: Ajax as suggested by Shikhar.. You have to have something like a setTimeout in javascript which would call this every minute or how ever often
2: A cron job... but a cron job that checks every active session file and if it has expired, then you simply delete it (Kills a session)
3: Have some other means of loading a PHP file as often as you want to check
Even with the above, there is no sure way of doing this..
Cron job / PHP loading.. they need a trigger... and a cron job wont redirect your user the second their session is expired.
Your only choice here is to use ajax on a timer to post to the sever and check if the session is still valid, if not then redirect once the response comes back from PHP to the ajax call.
But even then, once a user has logged in and if they disable JS... you wont get no redirect or checking.
#JOB You need to fire an ajax request something like following
<script type="text/javascript">
jQuery(document).ready(function(){
setInterval(function(){
jQuery.ajax({
url: 'http://localhost/your_script.php',
type: 'POST',
success:function(response){
alert("You are logged out");
return false;
}
});
}, 1000);
});
</script>
This script will check the status of logout after every 1 second and logs out the user if the user is idle for the time decided by PHP script.
Related
I am trying to finish one page of my website the last couple of hours while achieving the following.
While clicking on a button, the following should happen
Download link appears (done - works)
The mySQL table should be opened and a counter should be incremented
As far as I got the points. Javascript cannot handle that and thus we can use AJAX or jQuery. I was already checking out different posts and websites such as:
how to execute php code within javascript
https://www.w3schools.com/js/js_ajax_database.asp
and much more. However, I guess I do have problems with the AJAX syntax and I actually don't know if the requested php files is loaded/opened or not. Especially the second link given above is almost similar to what I am searching for. However, it does not work. To check if the php file is called, I set an alert which works if I do call the file explicitly in the browser. Maybe this does not work with AJAX as I expect it. Here the code to get more familiar with the inconstency I am doing.
The page code:
<?php
echo '<div><button onclick="incrementAndDownload('testPath', 'fileName'); ">Click me</button></div>';
?>
<script>
function incrementAndDownload (link, fileName)
{
$.ajax({
url: 'openfoam/increment.php',
success: function(data) {
// Print something if necessary
}
});
//- Open the link
// window.open(arguments[0], "_blank");
//- Increment download inside mysql
//var xhttp;
//xhttp = new XMLHttpRequest();
//xhttp.open("GET", "openfoam/increment.php?foo=nana", true);
//xhttp.send();
}
</script>
The increment.php looks as follows:
<?php
echo '<script type="text/javascript" language="Javascript">
alert("Test message if the script is called...");
</script>';
// Code for accessing the mysql database and manipulate the data
//$page_id = mysql_real_escape_string(html_entities($_POST['file']));
?>
Now when I click the button, the javascript is executed (e.g., if I uncomment the window.open) this works as expected. However, as already said, the second part is to open the database via php and increment a number (counter). For any reason, I am not able to figure out where the problem is located. I am even not sure if AJAX opens the increment.php file (the alert messages never appears so I guess it is never called). Any suggestion is appreciated and I hope that this question does not just contain a fundamental small error. Thank in advance, Tobi
It's not the way the AJAX works. If you call alert() on a destination page it won't show in your browser. Your case is very basic so I will keep my solution on a basic level.
In increment.php just echo something, it can be just OK string. So when you go to increment.php page you will see only OK, nothing more, nothing less.
Then go back to your javascript and check what is your response.
$.ajax({
url: 'openfoam/increment.php',
success: function(data) {
if (data == 'OK') {
console.log('It works, sir!');
}
}
});
If you don't see a message in a console after these modifications something doesn't work. However, I think your page is executed properly, but you just don't get feedback, because you don't handle the response (data param in your case).
Check it out and don't forget to give me a feedback!🤓
This question already has answers here:
PHP form - on submit stay on same page
(11 answers)
Closed 5 years ago.
I have a form on a website (www.mywebsite.com). I have a PHP script that sends me an e-mail with information when somebody submits a form on my website. But with action="submitform.php" in the form, it updates the site to the URL www.mywebsite.com/submitform.php. I would like it to stay on the main site (index).
The solution for this: I added header("Location: http://mywebsite.com"); die(); to my PHP code. In this way, users will be redirected to the main site when they have submitted code.
However, this pose a new problem.
Whenever someone submit the form, I would like to display a message such as "Mail has been sent". To make this work, I tried to have a small JavaScript code, basically
document.getElementById("message").innerHTML = "Mail has been sent."
... and <div id="message"></div> to my HTML code. Which works...... However, due to my PHP script redirecting me to my website (with header) when someone is submitting the form, the message will only be displayed for like half a second or something.
Anyone know any workarounds for this? Thanks in advance. I can provide more detail if needed, but my problem should be clear from this. Hope anybody is able to spot my mistake...
I use javascript and ajax for most of my form post. Works wonderful.
Ajax can grab the form information in a form object or pass it as an array. URL is your php proc page, there it will come back with whatever you "print/echo" in a data object that is passed into the success function.
Use this in your HTML,
<input type="button" onclick="submitForm();" value="Submit">
Javascript,
function submitForm(){
//Validate INPUT first. Then grab the form.
form = new FormData($('#frmIdHere')[0]);
$.ajax ({
type: 'POST',
dataType: 'text',
url: url,
data: form,
success:data => {
//Success message here.
//clear form here.
},
error: () => {
// error message here.
}
});
}
php process file use,
$inputFromForm = (isset($_REQUEST["NameOfInputFromForm"])) ? strip_tags($_REQUEST["NameOfInputFromForm"]) : "-";
Without using Ajax (which means you can send the form without refreshing the page), you have two options. Either send the form to a different file, process it, and redirect back - but with a GET parameter to indicate success or failure. Alternatively, just post to the same page (so the handling of the form happens in the same page - I recommend the first alternative).
If you want to use the post-redirect-get pattern, you would use
header("Location: /?status=success");
exit;
when the form was successfully handled in your submitform.php file.
Then you just check what the message in $_GET['status'] was, and display the message accordingly in your index.php file.
if (isset($_GET['status']) && $_GET['status'] == 'success') {
echo "Your message was successfully sent!";
}
This logic can be developed further to have different parameters, to post messages for success and failure, if that's needed for the application.
assumption: you want the user to stay on the page with the form.
in that case you probably don't return false / stop event propagation in your calling code.
let's say, you call your ajax like this:
<form onsubmit="submitform(this);" ...>[form]</form>
onsubmit does the following, it executes anything that is in it's attribute value (submitform(this)) and if it returns some non-false value, it will actually do the action of the form, as if the onsubmit wouldn't have existed. I assume this is exactly what's happening in your case.
To avoid this:
<form onsubmit="submitform(this); return false">[form]</form>
the return false will stop the form from being submitted, after it was already submitted by ajax. this also has the benefit of still working, if the user has javascript disabled.
if my assumption is false however ...
if you want to refresh the page, don't even use ajax and just add a parameter to the url that triggers the message to show. or add the message to the session in php and clear it out of there after displaying.
To doing this, You can use a SESSION var to store message send type (success or failed) and test it everytime on main page, if exist, display message and unset $_SESSION var !
Like this :
MAIN
if(isset($_SESSION['message'])){
if($_SESSION['message'] == 'success'){
echo "Yeah !";
}else{
echo "Problem";
}
unset($_SESSION['message']);
}
MESSAGE
if(mail()){
$_SESSION['message']='success';
}else{
$_SESSION['message']='error';
}
You can set interval and then redirect them to desired page.
<script>
setInterval(function(){ window.location.href="http://mywebsite.com" }, 5000);
</script>
At page 0 inputs are entered. Then Page 0 is submitted to php page 1
At php page 1 i calculate $Ama;
At php page 2 (required by page1), i need to ask one more verification check.
Hence in php page 2 :
if($Ama ==0 )
{
echo '<script>
var a = confirm("Ama is Zero. Are you sure?";
if(a){
//Set A SESSION VARIABLE
}
</script>';
}
How do i append to this a $_SESSION['Accepted']=0 where marked in Code.? I am having a problem with syntax to append this.
Since this confirm() check is done on client side, you can't run PHP code, so you will have to use AJAX to send request to server to append whatever values you want to the session.
There are many tutorials available, here is a simple way to do AJAX calls using jQuery http://api.jquery.com/jquery.ajax/
You can't manipulate a session value from Javascript, they only exist on the server.
This question already has answers here:
PHP best practice keep track of logged in users
(3 answers)
Closed 8 years ago.
I'm using the JavaScript below to check if the user session has not expired (with PHP) at intervals of 5 seconds. After logging out from another tab (same browser) or which the current session must have expired, still the code is bringing up the alert("Logged back in."); which is supposed to work for active sessions.
setInterval(function () {
var checklogin = "<? if ($this->session->userdata('user_logged_in')) {echo '1';} else {echo '0';} ?>";
if (checklogin == "1" ){
alert("Logged back in.");
} else {
alert("you are already logged out!");
}
}, 5000);
Please what am I doing wrong ?
The php section of your code will not change at run time. You could, for example, perform an AJAX call to your server to retrieve session information.
EDIT:
If you're using jQuery, take a look at: jQuery Ajax
If without jQuery, take a look at: How to make an ajax call without jquery?
This question already has an answer here:
PHP code only runs once inside javascript setInterval
(1 answer)
Closed 8 years ago.
I am trying to post an updating ping on my website, without having it reloading all the time, yet when i try it posts the initial ping, but it doesnt update after the time interval i've set
index.php :
<script>
setInterval(document.write('<?php echo json_encode(getPingout());?>'),100);
</script>
functions.php :
<?php
function getPingout() {
// some function that finds the ping of the server
return $server->getPing();
}
?>
You can't just have php run multiple times after a page has loaded. That PHP is executed one time when the page loads.
To do what you are attempting to do you should use some javascript and an ajax call.
$(function(){
function pingServer(){
$.post('/ping.php',function(data){
console.log('server is ok');
});
}
setInterval( pingServer, 4000 );
});
Also you may not need to ping the server every that often (every 100). Otherwise you may have issues.
That is not how javascript & PHP work together.
In order to refresh data without a page reload, you must request the data asynchronously. Search for AJAX or XHR, I really recommend that you look into something like jQuery though, as you will save alot of time writing code and debugging, compared to if you were to write the javascript by yourself.
If you were to do this in jQuery:
//this means run when page is ready
$(function(){
setInterval(function(){
//Send POST request to ping.php
$.post('ping.php',{},function(){
//Append the result to the body in a new div
$('body').append($('<div>'+data+'</div>'));
});
},100);
});
and your ping.php should simply return the ping and nothing else.
And don't let the dollarsigns confuse you, in PHP its a prefix for variables, but in the javascript/jquery context it simply is a variable, containing the jquery object that you call functions from.