I have a timeout function that runs correctly except for one thing. The field that checks if a user is currently logged in does not update once the script runs. I was testing it all week and got it to actually work, but when I tried to test it today, I stopped updating the field. Can anyone explain why? I also have a logout button that does a jQuery call which runs a logout.php script when the button is clicked which works perfectly. Could this be why the timeout script has stopped updating the database? I don't think that could what it is, but I could be wrong.
timeout script(php)
<?php
require("../includes/header.php");
$now = time();
$expires = $_SESSION["expire"] + 30;
$user = $_SESSION["id"];
if(!isset($_SESSION["expire"]) || $expires > $now){
$_SESSION["expire"] = $now;
}
else{
mysqli_query($connect, "UPDATE `$user_table` SET `logged_in`=0 WHERE `user_id`='$user_id'");
session_unset();
session_destroy();
mysqli_close($connect);
header("Location: timed_out.php");
}
?>
logout script(js & php)
$(document).ready(function(){
$("#logout").on("click", function(){
$.post("../php/logout.php", {}, function(response){
if(response.success == "1"){
location.replace("../pages/logged_out.php");
}
}, "json");
})
})
logout script(php)
<?php
ob_start();
require("../includes/header.php");
$user_id = $_SESSION["id"];
ob_clean();
mysqli_query($connect, "UPDATE `$user_table` SET `logged_in`=0 WHERE `user_id`='$user_id'");
session_unset();
session_destroy();
mysqli_close($connect);
echo json_encode(array("success"=>1));
?>
Another question I have is. Would it be beneficial to do the timeout script in jQuery instead of PHP? If so, how would I go about doing that?
I think you need some simple debuggin ;)
Your login script says in the query:
WHERE `user_id`='$user_id'
but the code a bit higher says
$user = $_SESSION["id"];
That's NOT the same variable ;)
Related
I have this code to set the cookie on a website :
if (isset($_COOKIE[$_first_name.$_last_name])){
echo '<html><head></head><body></br></br></br><h1><center>Hello, '.$_COOKIE[$_first_name.$_last_name].'! Welcome back!</center></h1></body></html>';
sleep(2);
header('Location: ../index.php');
}
else if (setcookie( $_first_name.$_last_name, $_first_name.' '.$_last_name, time() + 60*60*24*5))
;
The first time it will register the name, the second time, it won't give me the welcoming message and will direct me instantly to the home page. I want it to wait for 2 second for the user to see the welcome message and then auto direct the user to the home page.
More INFO
<?php
//error_reporting(E_ERROR);
session_start();
include('loginScript.php'); // Includes Login Script
if(isset($_SESSION['login_user'])){
}
?>
<html>
...
...
</html>
in the above code, I'm calling the loginScript.php which contains the code to check for cookies.
section from the loginScript.php file
if ($rows == 1) {
$result = mysqli_fetch_array($query);
$_SESSION['login_user']=$username; // Initializing Session
// $_SESSION['items'][] =$username;
$_SESSION['firstname'] =$result['Firstname'];
$_first_name = $_SESSION['firstname'];
$_SESSION['lastname'] =$result['Lastname'];
$_last_name = $_SESSION['lastname'];
if (isset($_COOKIE[$_first_name.$_last_name])){
echo '<html><head></head><body></br></br></br><h1><center>Hello,
'.$_COOKIE[$_first_name.$_last_name].'! Welcome back!</center></h1></body>
</html>';
ob_flush();
flush();
//sleep(2);
echo "<script>setTimeout(()=>
{document.location.href='index.php'},2000);</script>";
}
else if (setcookie( $_first_name.$_last_name, $_first_name.'
'.$_last_name, time() + 60*60*24*5)){
// Code of rest of the entire login page
}
}
else {
$error = "Username or Password is invalid";
}
mysqli_close($connection); // Closing Connection
Firstly, you can't sleep on an output without flushing in php. You will have to call
ob_flush();
flush();
in order to force php to output the contents before sleeping and performing the rest of the code.
Secondly, you cannot output anything before changing headers - in your case, setting the location header. A simple workaround is to use javascript to redirect the page instead. So you will have something like this:
if (isset($_COOKIE[$_first_name.$_last_name])){
echo '<html><head></head><body></br></br></br><h1><center>Hello, '.$_COOKIE[$_first_name.$_last_name].'! Welcome back!</center></h1></body></html>';
ob_flush();
flush();
sleep(2);
echo "<script>document.location.href='index.php'</script>";
die(); //added to prevent the rest of the output
}
else if (setcookie( $_first_name.$_last_name, $_first_name.' '.$_last_name, time() + 60*60*24*5))
;
However, it is often not advisable to use sleep unless absolutely necessary, as sleep uses your server resources and imagine if everyone is sleeping and that is a waste of your resources and stopping the server from handling new requests.
We can workaround this further by offloading this delay to the client side using javascript settimeout.
if (isset($_COOKIE[$_first_name.$_last_name])){
echo '<html><head></head><body></br></br></br><h1><center>Hello, '.$_COOKIE[$_first_name.$_last_name].'! Welcome back!</center></h1></body></html>';
ob_flush();
flush();
//sleep(2);
echo "<script>setTimeout(()=>{document.location.href='index.php'},2000);</script>";
}
else if (setcookie( $_first_name.$_last_name, $_first_name.' '.$_last_name, time() + 60*60*24*5)){
// Code of rest of the entire login page
}
Last but not least, as Richard mentioned in the comments, it is actually a better practice to handle this all from the client side, then you will also have more control over transitions, etc etc. That will be out of the scope of this question, but you can consider redesigning the program flow as what he suggested. Otherwise, the above workarounds should do find to achieve your needs.
I am setting up a login page to take a users username and password then check that against a local database, however nothing is echoing form the database connection and there is no redirecting to the next page 'welcome.php' happening.
I have already tried many different ways of connecting to the local database and redirecting to different pages with different methods, none of which gave any error message or worked. using XAMPP Apache and mySQL modules to provide the local server.
<?php
if (isset($_POST['Login']))
{
$link = mysql_connect('localhost','root','password','budget');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
session_start();
$username= $_POST['username'];
$password= sha1($_POST['password']);
$_SESSION['login_user']=$username;
$query = mysql_query("SELECT accounts.username, passwords.password_hash
FROM accounts
INNER JOIN passwords ON accounts.account_id = passwords.account_id
WHERE accounts.username = '$username' AND password_hash = '$password';");
if (mysql_num_rows($query) != 0){
?>
<script type="text/javascript">window.location.replace(welcome.php);
</script>;
<?php
mysql_close($link);
}
}
?>
I expect it to redirect to 'welcome.php' but instead it just refreshes the same page and nothing is echoed or given as an error
What isn't working?
Your JavaScript location.replace method needs a string as an input, you're not giving it that (as the input value is not quoted). It would be window.location.replace('welcome.php'); instead.
How to solve it?
The better solution is to redirect in PHP instead of in JavaScript, using header().
Additional remarks
I took the liberty of converting your code to use mysqli_ instead of the old, outdated and deprecated mysqli_ library. With this, you can use a prepared statement, as I have shown below. Use this approach for all your queries, bind the parameters through placeholders.
session_start();
if (isset($_POST['Login'])) {
$link = mysqli_connect('localhost','root','password','budget');
if ($link->connection_errno) {
die('Could not connect: ' . $con->error);
}
$username = $_POST['username'];
$password = sha1($_POST['password']);
$stmt = $link->prepare("SELECT a.username, p.password_hash
FROM accounts a
INNER JOIN passwords p
ON a.account_id = a.account_id
WHERE a.username = ?
AND p.password_hash = ?");
$stmt->bind_param("ss", $username, $password);
$stmt->bind_result($resultUsername, $resultPassword);
$stmt->execute();
if ($stmt->num_rows) {
$_SESSION['login_user'] = $username;
header("Location: welcome.php");
}
$stmt->close();
}
What's next?
Fix your passwords. Using sha1() is highly insecure for passwords, look into using passwords_hash()/password_verify() instead.
You need to add single quote around welcome.php
As welcome.php is neither a JavaScript keyword like this nor a number, single quote is mandatory also it is not a variable/object.
JS considers welcome as object and php as its method in welcome.php
Without it, a JavaScript error will be displayed:
ReferenceError: welcome is not defined
<script type="text/javascript">window.location.replace(welcome.php);
</script>
Also, there is no need of semi-colon ;.
JavaScript redirect without any condition.
There are not many solutions/tutorials on how user inserted value in database could be used as a dynamic timer countdown that does not reset after the page is refreshed.
I'm facing a problem where the value is displayed but static. Is there any other way of implementing this?
database & web
How could I add functionality to redirect or stop the countdown timer?
index.php
<?php
session_start();
$dbHost = 'localhost';
$dbUser = 'root';
$dbPass = 'root';
$dbName = 'student';
$conn = mysql_connect ($dbHost, $dbUser, $dbPass) or die ('MySQL connect failed. ' . mysql_error());
mysql_select_db($dbName,$conn);
$duration="";
$query="select duration from table1";
$result=mysql_query($query);
while ($row = mysql_fetch_array($result)){
$duration=$row["duration"];
}
$_SESSION["duration"]=$duration;
$_SESSION["start_time"]=date("Y-m-d H:i:s");
$end_time=$end_time=date('Y-m-d H:i:s',strtotime('+'.$_SESSION["duration"].'minutes',strtotime($_SESSION["start_time"])));
$_SESSION["end_time"]=$end_time;
include_once 'response.php';
?>
<div id="response"> </div>
<script type="text/javascript">
setInterval(function()
{
var xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","response.php",false);
xmlhtpp.send(null);
document.getElementById("response").innerHTML=xmlhttp.responseText;
},1000);
</script>
response.php
<?php
$from_start=date('Y-m-d H:i:s');
$to_end=$_SESSION["end_time"];
$first=strtotime($from_start);
$second=strtotime($to_end);
$differenceinseconds=$second-$first;
echo gmdate("H:i:s",$differenceinseconds);
?>
I ran your code and found a couple issues:
There is a JavaScript error
This is because there is a typo in the Javascript code on the following line:
xmlhtpp.send(null);
Change that to
xmlhttp.send(null);
And the Asynchronous requests should execute properly.
The line include_once 'response.php'; will have the effect of echoing the formatted date string above the <div>, which will yield two formatted timestamps when the AJAX requests are running. Remove that include_once line to avoid that scenario.
The code for response.php doesn't call session_start();. Unless your error handler settings are such that E_NOTICE errors are ignored, there will likely be an error message at the top of the timer:
E_NOTICE : type 8 -- Undefined variable: _SESSION -- at line 12
See a demonstration in this phpFiddle.
I am showing an alert using javascript in my php page. It is not showing alert box. Kinldy guide me how to make it work fine
if($sql && $sql2 && $sql3)
{
echo "<script> alert('Deleted successfully!');</script>";
$myURL = 'students_list.php';
header('Location: '.$myURL);
exit;
else
{
echo "<script> alert('Temporary problem, try again!');</script>";
}
?>
It is deleting data from database but not showing alert. Tell me how to make it work fine.
do this
<script> alert('Deleted successfully!');window.location='students_list.php'</script>
like this when the alert is closed you redirect.
You are first trying to display an alert:
echo "<script> alert('Deleted successfully!');</script>";
then to issue a HTTP redirection:
$myURL = 'students_list.php';
header('Location: '.$myURL);
These functions are incompatible, because of the way HTTP redirects work:
If you have output buffering enabled, a redirection response (HTTP 302) will be generated, along with your alert script as body... however the body of redirects is ignored by browsers supporting them (i.e., all of them, except for example a curl without the -L option).
If you don't have output buffering enabled, the script will output the JS code for the alert, but could not output the redirection anymore because at that point HTTP headers have already been sent out. Depending on the settings, a warning will be displayed in the client's browser.
A possible solution for that is to issue no redirect and use JavaScript to redirect the client, something like:
echo "<script>\nalert('Deleted successfully!');\n";
echo "location = 'students_list.php';</script>";
exit;
Check this it works perfectly
<?php
$sql=1;
$sql2=2;
$sql3=3;
if($sql && $sql2 && $sql3)
{
echo "<script> alert('Deleted successfully!');window.location='students_list.php'</script>";
exit;
} else
{
echo "<script> alert('Temporary problem, try again!');</script>";
}
?>
I want to call function deleteUser() after JavaScript confirmation. Here is my code. Please help me.
<?php
session_start();
include_once("DataSourceController.php");
$DeletedBy = $_SESSION['ID'];
$Name = $_GET['uname'];
echo '
<script type="text/javascript">
var responce=confirm("Are you sure you want to delete this user?");
if (!(responce==true)){
deleteUser();
}
</script>';
function deleteUser(){
$sql_DeleteUser="UPDATE login
SET Deleted=1,DeletedAt= now(),DeletedBy=".$DeletedBy."
Where User='".$Name."';";
mysql_query($sql_DeleteUser);
echo'
<script type="text/javascript">
alert("User '.$Name.' Successfully deleted.");
window.location.href = "../pages/DeleteUser.php";
</script>';
}
?>
You have a few mistaken theories in your initial question. Although JavaScript is a client-side language, PHP is not. You will get an undefined function error with your current code, since it is not defined in javascript.
In order for JavaScript to execute a PHP function, it would be highly recommended to learn and use AJAX. AJAX can be used to dynamically execute PHP code when a user does a certain action. Many websites use this to query the database without reloading a page.
JavaScript will send a request to a PHP page, where the function will be executed. Refer to this page for a more in-depth example: Call PHP function from javascript
You can do it by to ways :
1/ Synchronously by redirecting to a php script by sending informations thanks to GET (for example):
<script type="text/javascript">
var responce=confirm("Are you sure you want to delete this user?");
if (!(responce==true)){
window.location.href = ("myScript.php?user="+userName); //var userName should be defined before
}
</script>';
and myScript.php:
<?php
if isset($_GET['user']){
$name = $_GET['user'];
}
//some stuff
deleteUser($name); //Here you call your function
header('Location: myPage.php'); //You return to your first script
?>
2/ Asynchronously by calling an AJAX request to myScript.php
Use this code:
<?php
session_start();
include_once("DataSourceController.php");
$DeletedBy = $_SESSION['ID'];
$Name = $_GET['uname'];
function deleteUser(){
$sql_DeleteUser="UPDATE login
SET Deleted=1,DeletedAt= now(),DeletedBy=".$DeletedBy."
Where User='".$Name."';";
mysql_query($sql_DeleteUser);
echo'
<script type="text/javascript">
alert("User '.$Name.' Successfully deleted.");
window.location.href = "../pages/DeleteUser.php";
</script>';
}
//first, we check whether the user has confirmed or not
if(!isset($_GET['confirmed'])) { //if they haven't, we display the confirmation message
?>
<script type="text/javascript">
var responce=confirm("Are you sure you want to delete this user?");
if (!(responce==true)){
//if confirmed, reload the page with added 'confirmed' parameter
window.location.href="<?php echo $_SERVER['PHP_SELF'].$_SERVER['REQUEST_URI'] ?>?confirmed=1"
}
</script>
<?php
}
elseif($_GET['confirmed'] == 1) {
deleteUser();
}
?>