Hey guys am trying to determine if two minutes are over in php..I have an input box and a php script that checks if 5 seconds are over or not..What i need is when the user inserts the correct value i just want to display password is correct and you are now logged in with the existing token.
After 5 seconds i want to display the message like you cant login with this token id anymore.
But the problem is everytime am geting the message you are now logged in with the existing token after 5 seconds. its not showing up the message you cant login .....
The code i have used..
<?php
session_start();
$_SESSION['logintime'] = time();
$name = $_POST['fname'];
$tokenvalue = 'sample';
if($name != $tokenvalue) {
echo 'the token is incorrect<br>';
} else {
echo "the token is correct<br>";
}
if (time() > $_SESSION['logintime'] + 5) {
echo 'you cant login with this token id anymore<br>';
} else {
echo 'you are now logged in with the existing token';
}
Hope can i diplay the message you cant login with this token id anymore after 5 seconds ??..
Where am i doing wrong ??..Any help would be apreciated..Thanx
A PHP script is executed by the server. As soon as you see something in your browser, there is no action on the server anymore (at least in this script).
To accomplish what you are trying here, you need to use AJAX (asynchronous javascript and xml).
There are some things that are eglible in this case:
Hardcoded request after x-seconds with javascript (I would recommend using jQuery for this):
setTimeout(function(){$('#message').load('myScript.php');}, 5000);
You could use SSE (Sever-Sent Events), where you open a persistent connection to the server and push the event after x-seconds. There are good tutorials on HTML5rocks and MDN.
You could use only javascript, because the message will only be on the client side - you need to validate the time anyways, before you save a user input. For this you could also use jQuery:
setTimeout(function(){$('#message').html('you cant login with this token id anymore<br>');}, 5000);
Update: there are some things strange in your code (I will try to explain what I mean using comments):
<?php
session_start();
// you set the login, before you validate the users input
$_SESSION['logintime'] = time();
// thats okay, but actually not really necessary
$name = $_POST['fname'];
// thats okay for a test only :)
$tokenvalue = 'sample';
if($name != $tokenvalue) {
// you should use exit() or die() when the login fails to end the script
echo 'the token is incorrect<br>';
} else {
// first you use the word "token" now "password"
echo "the password is correct<br>";
}
if (time() > $_SESSION['logintime'] + 5) {
echo 'you cant login with this token id anymore<br>';
} else {
echo 'you are now logged in with the existing token';
}
Update2: Maybe this helps you - it does what you described in the question:
<html>
<head>
</head>
<body>
<?php
$tokenvalue = 'sample';
if(isset($_POST['token'])){
if($_POST['token'] === $tokenvalue) {
echo '<div id="success">The password is correct.<br>You are now logged in with the existing token.</div>';
}
}
?>
<form action="" method="post">
Token: <input type="text" name="token"><br>
<input type="submit" value="Submit">
</form>
<script>
if(typeof(document.getElementById('success')) != 'undefined') {
setTimeout(function(){document.getElementById('success').innerHTML = "You can't login with this token anymore."},5000);
}
</script>
</body>
</html>
Related
I need to be able to orientate with a php code that communicates with data from a mysql database, this file is called "validate.php". Its main functions are to verify that there are no empty fields at the time of login, and assign a profile if a user has value 1 and another profile when the value is 0 in the records of the table "users"
The idea is that "validate.php" check the user and direct it to a page according to their profile, but I can not do that.
My code is:
<?php
require('access_db.php');
session_start();
if(isset($_POST['send'])) { // We verify that the form data has been sent
//We verify that the user_name and the user_pass fields are not empty
if(empty($_POST['user_name']) || empty($_POST['user_pass'])) {
echo"
<script>
alert('Please enter your username and password correctly ');
location.replace('login.php');
</script>
";
}else {
//"Clean" the form fields of possible malicious code
$user_name = mysqli_real_escape_string($link,trim($_POST['user_name']));
$user_pass = mysqli_real_escape_string($link,trim($_POST['user_pass']));
// We verify that the data entered in the form match those of the DB
$query=mysqli_query($link,"select user_id,user_name,user_admin FROM users WHERE user_name='".$user_name."' and user_pass ='".$user_pass."'");
$row = mysqli_fetch_array($query);
$_SESSION['user_id'] = $row['user_id'];
$_SESSION['user_name'] = $row["user_name"];
$_SESSION['user_admin'] = $row["user_admin"];
if($_SESSION['user_admin']==1){
echo "dashboard.php";
}else{
echo "dashboard2.php";
}
{
}
}else{
header("Location: login.php");
}?>
My main problem is here:
if($_SESSION['user_admin']==1){
echo "dashboard.php";
}else{
echo "dashboard2.php";
}
When I login with my admin user in my page "login.php" you should check the information and go to a page according to your profile, only appears in the browser "http://localhost/proyect/validate.php" and the text "dashboard" on the page, But, if I write in the browser "http://localhost/proyect/dashboard.php" load the page with all the information.
I do not know what I'm doing wrong.
Someone can help me, I'll be very grateful, I've been on this for days.
Thanks.
Don't print, try this instead:
if($_SESSION['user_admin']==1){
header('location:dashboard.php');
exit;
}else{
header('location:dashboard2.php');
exit;
}
Thanks for the suggestion Magnus Eriksson
you need to redirect not echo out the contents of the php file
and also do check for { as there are extra ones
if($_SESSION['user_admin']==1){
header("Location: dashboard.php");
}else{
header("Location: dashboard2.php");
}
I am learning session handling while submitting form data between multiple php pages.
For simple example, I have a php form myform.php that asks the user to enter a password and directs to myaction.php. I want to start the session before the user enter the password. If he enters the password as 1234 within one minute, it displays "valid". If he enters the password after 1 minute, it should display "Session timeout".
Here is my code that doesn't work.
myfrom.php
<?php
session_start();
$_SESSION['start'] = time();
$_SESSION['expire'] = $_SESSION['start'] + (01 * 60);
?>
<html>
<form nmethod="post" action="myaction.php">
<input type="text" name="myvalue"/>
<input type="submit" value="SignIn" name="submit1">
</form>
</html>
myaction.php
<?php
if ($_POST['submit1'])
{
$v1 = "1234";
$v2 = $_POST['myvalue'];
$_SESSION['now'] = time();
if ($_SESSION['now'] > $_SESSION['expire'])
{
echo 'Session Timeout!';
header('refresh:05;Location: http://localhost/myform.php');
}
else if(($_SESSION['now'] <= $_SESSION['expire']) && ($v1==$v2))
echo 'Valid Password!';
else
echo 'Invalid password!';
}
?>
Where did I go wrong?
the first thing I think you have a typo
<form nmethod="post"
there is additional "n" before method, remove it .
the second thing you have to use start_session() whenever you want to use anything from session.
I am building a website and i would like to secure it against Session Hijacking. Reading for this i came across someone saying that:
A general rule of thumb is to generate the session ID each time a user changes his access level.
1.When a user log in
2.When a user log out
3.When a user get administrative access
For what is worth, my website will be seperating the access levels into users logged-in and users logged-out. All forms are submitted using the POST method.
index.php
<?php
session_start();
//Setting the variable initialy to false
$_SESSION['LOGGED_IN'] = FALSE;
//to use SSL
$serverport = $_SERVER['SERVER_PORT'];
$server_http_host = $_SERVER['HTTP_HOST'];
$server_request_uri = $_SERVER['REQUEST_URI'];
if (headers_sent())
{
die("HTTP headers have already been sent ");
}
else
{
if($serverport != '443')
{
ob_start();
exit(header('Location: https://'.$server_http_host.$server_request_uri));
}
}
if(isset($_POST['SUBMIT']))
{
if(isset($_POST['TOKEN']) && $_POST['TOKEN'] == $_SESSION['TOKEN'])
{
//Open database connection
require_once('connect_db.php');
//Calling functions.php that includes all custom functions
//ErrorHandler()
require_once('functions.php');
$email = $_POST['EMAIL'];
$password = $_POST['PASSWORD'];
$statement = $DBH->prepare("SELECT * FROM user_details WHERE email=:email AND pwd=:password ");
$statement->bindParam(':email',$email);
$statement->bindParam(':password',$password);
$statement->setFetchMode(PDO::FETCH_ASSOC);
try{
$result = $statement->execute();
$rows = $statement->rowCount(); // shows how many times the user is available in the user_details table
$data = $statement->fetch(); //fetches the data related to that user from user_details table
}
catch(PDOException $e)
{
//this is custom function
echo ErrorHandler($e);
}
if($rows == 1)
{
//this means that the user has inserted the correct credentials
//regenerate session_id each time there is a change in the level of privilege to mitigate SESSION FIXATION
session_regenerate_id(true);
//turning logged in variable to true as soon as it finds a match
$_SESSION['LOGGED_IN'] = TRUE;
//saves the email into a session so it can be used in mainpage.php
$_SESSION['EMAIL'] = $email;
//redirect to main page
header('Location:https://www.example.com/mainpage.php');
}
else
{
echo "<br />Wrong username or password!<br />";
}
}//closing *if(isset($_POST['TOKEN']) && $_POST['TOKEN'] == $_SESSION['TOKEN'])*
}//closing *if($_POST['SUBMIT'])*
//creating a random token to inject in our HTML form
$token = base64_encode(openssl_random_pseudo_bytes(32));
//store the random token in the session variable so we can later compare it to the one in the HTML form
$_SESSION['TOKEN'] = $token;
?>
<form action="index.php" method="POST" accept-charset="UTF-8">
<p>Email: <input type="email" name="EMAIL" /> </p>
<p><input type="hidden" name="TOKEN" value="<?php echo $token; ?>" /></p>
<p>Password <input type="password" name="PASSWORD" /> </p>
<p><input type="submit" name="SUBMIT" value="Submit" /></p>
</form>
The script accepts input email and password from the user,checks the database and if it finds a match it redirects the user to the mainpage.php.
mainpage.php
<?php
ob_start();
//the code to set the header must be called before output begins
session_start();
$serverport = $_SERVER['SERVER_PORT'];
$server_http_host = $_SERVER['HTTP_HOST'];
$server_request_uri = $_SERVER['REQUEST_URI'];
if (headers_sent())
{
die("HTTP headers have already been sent ");
}
else
{
if($serverport != '443')
{
ob_start();
exit(header('Location: https://'.$server_http_host.$server_request_uri));
}
}
if(($_SESSION['LOGGED_IN'] == TRUE) && isset($_SESSION['LOGGED_IN']))
{
$email = $_SESSION['EMAIL'];
echo $email;
//Calling functions.php that includes all custom functions
//LogOut()
require_once('functions.php');
if(isset($_POST['LOGOUT']))
{
//its a custom function that is used for logging out
LogOut();
}
echo '
<form method="POST" action="mainpage.php">
<p><input type="submit" name="LOGOUT" value="Log Out" /></p>
</form>
';
}
else
{
echo "Please login in order to use example.com";
}
?>
Is there a way for me to check if the way i have built these 2 scripts really regenerate the Session ID? I am using Firefox's extension LIVE HTTP headers but i am not sure if i am reading it correctly.
Also, i cannot find a way to track down and read the content of COOKIES stored while using my browser (either Chrome or Firefox or even IE11). How can i do that?
Another question that is related with security:
Implementing an anti-CSRF token:
Do i need to implement an anti-CSRF token for each form in my website [i guess the answer is Yes but i want to confirm it]? Should each token be different than the token used in a previous form? For example the token in index.php to be different than the token used in mainpage.php if it had a form as well.
Does the token technique prevent against any other kind of attack?
I would be glad if you indicate wrong programming in the code above, so i can correct it and learn at the same time.
Thanks!
I'm going to focus on your questions and not necessarily a thorough code review, since I think your questions are the main reason you're posting.
A simple way to check your current session id or PHPSESSID is to check under Chrome's Developer Tools > Resources > Cookies. You'll see the (initially-generated) session ID. You can check this value before and after a user logs in. If the value changes, your session id has actually been regenerated.
You can also view cookies in Firefox by right-clicking the current page, going to View Page Info and using the Cookies tab.
On CSRF (prevention) tokens, the answer varies. People use different methods to go about them. I would say a majority of websites set a token in $_SESSION upon any regenerate of the session id. So for the duration of the current session, the CSRF token will remain the same and check against hidden inputs for that CSRF token.
On the other hand, I've also heard of regenerating a CSRF token for every single form that is client-facing. Your way of doing it is up to you. Nothing is 100% bulletproof, but getting as close to 100% as you can is the idea.
Take a few minutes to read up on CSRF tokens and the Synchronizer Token Pattern.
Best of luck!
I have 3 pages:
index.php
login.php
display.php
index.php
Sets up AngularJS using the ngRoute module to navigate my pages.
login.php
Loaded by default and sets PHP $_SESSION variables.
display.php
Echos the contents of $_SESSION.
I navigate to display.php from login.php using a link setup with ngRoute.
Problem
display.php does not show $_SESSION variables no matter how many times I navigate to and from it. It will only display them if I manually navigate to the page such as refreshing the page or entering the address in the browser.
I know the php code is executed because I can echo other things to the screen it just doesn't access the $_SESSION variables.
Why is this?
I think i might see where your problem is. You try to access php session in your single page angularJS HTML templates am i right? like:
<div ng-repeat="n in <?php $_SESSION['someSessionArray'] ?>">
That is not how it works. Your $_SESSION will never be available in your templates.
What you can do, is use an ajax request for your login authentication and have that request give you a session id.
Then use that session id when starting your session in further ajax requests (as already mentioned).
Then, when you want to store something to the php session, access the data via ajax request and php service.
a VERY, VERY, VERY, simple Example:
inside getFromSession.php
session_start($_GET['session_id']);
$key = $_GET['key']
echo json_encode($_SESSION[$key]);
inside storeToSession.php
session_start($_GET['session_id']);
$key = $_GET['key'];
$value = $_GET['value'];
$_SESSION[$key] = $value;
inside your login.php
$user = yourAuthMechanism($_GET['username'],$_GET['password']);
if($user) {
session_start();
echo json_decode(array('status' => 'success','sid' => session_id()));
}
else { ... error handling
inside anywhere in your angular where you need to access session data:
$promise = $http.get('pathtoyourphp/getFromSession.php?key=foo');
$http.set('pathtoyourphp/getFromSession.php?key=bar&value=4');
// now use promise to acces the data you got from your service
In general, no reason exists, why AngularJS apps, which request
PHP-based server-side stuff, won't be able to read $_SESSION.
That said, please provide at least the core concepts of of your AngularJS code, so we can provide further details.
Additionally, put just this in display.php:
<?
echo __FILE__
. '<br />' . date( DATE_RFC822 )
. '<br />' . var_dump( $_SESSION )
;
// intentionally skipped dangerous closing PHP-tag
Now run your AngularJS app and tell what comes out.
Make sure you start the session before reading the SESSION variables.
<?php
session_start();
echo $_SESSION["user9"];
?>
I don't think you're looking for angularJS.
I think you're looking for something more like this.
index.php:
<html>
<header>
<title>Login</title>
</header>
<body>
<form method="POST" action="login.php">
<input type="username" name="username" placeholder="username" />
<input type="password" name="password" placeholder="password" />
<input type="submit" value="Login" />
</form>
</body>
</html>
login.php
<?php
session_start();
if(empty($_POST)) {
die("You don't have permission to be here.");
} elseif(empty($_POST['username']) or empty($_POST['password'])) {
die("All fields are required.");
}
$username = "admin";
$password = "password";
if($_POST['password'] == $password && $_POST['username'] == $username) {
$_SESSION['loggedIn'] == "true";
header("Location: show.php");
} else {
die("Invalid login");
}
?>
show.php
<?php
if($_SESSION['loggedIn'] == "true") {
echo "You are logged in";
} else {
die("You don't have permission to be here.");
}
?>
I have a login page called signin.php where a user can enter an email and password. On clicking submit button, page directs to connection_validate.php. This page validates the user entered data with database. If it's a registered user, the page directs to calendar.php. If the entered data is incorrect, it should redirect to signin.php. If the entered data is incorrect, I have placed cookie like this:
//action to be done if e mail id and password matches with database records
if(mysql_num_rows($result)>0)
{
header('location:calendar.php');
}
//action to be done if e mail id and password does not matches with database records
else
{
setcookie('message','incorrect login data');
header('location:signin.php');
}
In signin.php, I have written the code for displaying an alert if login information is incorrect like this:
<?php
include("include/minfooter.php");
if(isset($_COOKIE["message"]))
{
if(!($_COOKIE["message"]==" "))
{
echo "<script>
alert('Incorrect login information');
</script>";
setcookie("message"," ",time()-3600);
}
}
?>
My issue is that alert is displaying each time when I load the signin page if I have entered a error login data once. If I press the back button from the calendar.php to signin.php also, alert starts showing. I understood that the problem is with cookie. Cookie has not been removed. How can I solve this issue?
Update your signin.php as follows
<?php
include("include/minfooter.php");
if (isset($_COOKIE["message"]))
{
echo "<script>
var delete_cookie = function(name) {
document.cookie = name + '=;expires=Thu, 01 Jan 1970 00:00:01 GMT;';
};
var msg = '" . $_COOKIE["message"] . "';
if (msg != '')
alert('Incorrect login information');
delete_cookie('message');
</script>";
}
?>
If you are using a session you can use the $_SESSION variable instead of a cookie value. Also you can not use setcookie() AFTER you have output content since setcookie() will send an HTTP header which must be sent prior to any content being sent.
session_start();
//action to be done if email id and password matches with database records
if (mysql_num_rows($result) > 0)
{
header('Location: calendar.php');
exit;
}
//action to be done if email id and password does not matches with database records
else
{
$_SESSION['message'] = 'incorrect login data';
header('Location: signin.php');
exit;
}
Then:
<?php
session_start();
include("include/minfooter.php");
if (!empty($_SESSION['message']))
{
echo "<script>alert('" . $_SESSION["message"] . "');</script>";
$_SESSION['message'] = '';
}
?>
Ok maybe is better to use session for that use a index ['messages'] on the $_SESSION array, then cleanup, the cookie should be used when you want reference some info after the user get out of your page. I made your code on using cookies, but consider using session:
<?php include("include/minfooter.php");
if(isset($_COOKIE["message"]) && !empty($_COOKIE["message"])
{
echo "<script>
var msg = '<?php echo $_COOKIE["message"];?>';
if (msg != "")
alert('Incorrect login information');
</script>";
unset($_COOKIE["message"]);
}
?>