php cache vs cookie - php

I am integrating a login page (fixed username and password).
Once the user logs in, he is being redirected to another page 'x' (on my server).
However, when the user closes the browser (or tab) and re opens it, he is automatically being directed to the page 'x' without the need to ask for username and pass.
However, if i delete the cookies from my browsers (firefox) settings, things go back to normal. Deleting the cache does not do anything.
I know I need to insert couple lines of code to delete to cookie.
My questions are,
is this 100% cookie problem? or I need to prevent storage into local cache too ?
The cookie prevention happens on which level ?during the login or the redirection ?
Once I am redirected to the page 'x', does putting a log out button there makes it possible to log out of the session that redirected ?
below is my code.
<?php
session_start();
if(isset($_POST['username'])){
if(($_POST['username'] == "user") && ($_POST['password'] == "pass"))
{
$_SESSION['secured'] = "Secured";
}else{
echo "Wrong username and password. <p>
<a href='?'retry</a>";
}
}
if(!isset($_SESSION['secured']))
{
echo "<form method='post'>
Username: <input type='text' name='username' maxlength='10' /><br>
Password: <input type='password' name='password' maxlength='10' /><br>
<input type='submit' value='login' />
</form>";
}else{
?>
<html>
<head>
<title>Session Login</title>
</head>
<body>
<p>redirecting....
<meta HTTP-EQUIV="REFRESH" content="1; url=http://x.php">
</p>
</body>
</html>
<?php
}
?>

If you can create a logout.php page that will destroy the session:
unset($_SESSION['secured']);
header('Location: login.php');
exit;
Simply visit that page and the login will be destroyed.
If you want the session to timeout after a predetermined period of time, you can use something similar to the code shown in this example.
If you're wanting to kill the session after the user has landed on x.php
<?php
session_start();
//First make sure that they're allowed access to x.php
if(!isset($_SESSION['secured'])){
//They shouldn't be here.
header('Location: login.php'); //Redirect back to your login page
exit;
}
//Ok, user is obviously logged in. Unset the session variable so that they can only view this page once (unless they login again)
unset($_SESSION['secured']);
//Show content of x.php

Related

How to logout from a session?

Coz of this virus in China, bosslady asked us to try to do classes online. I want the students to login, so I know who is present.
Login works. It checks user name and password. If correct, I'm in. Logout seems weird!
I have this below for logout.inc.html.php:
<form action="" method="post">
<div>
<input type="hidden" name="action" value="logout">
<input type="hidden" name="goto" value="/">
<input type="submit" value="Log out">
</div>
</form>
Shows a nice Log out button when I put this on any page:
<?php include $_SERVER['DOCUMENT_ROOT'] . '/includes/logout.inc.html.php';?>
The form above does take me back to the root page when I click the button, so that bit is working. But if I click say, the button for class 19BE1 again, where I should be logged out, I am not asked to login again. It just opens. Maybe some cookie thing??
This is part of /includes/access19BE1.inc.php I got this from my textbook PHP & MySQL: Novice to Ninja
if (isset($_POST['action']) and $_POST['action'] == 'logout')
{
session_start();
unset($_SESSION['loggedIn']);
unset($_SESSION['name']);
unset($_SESSION['password']);
header('Location: ' . $_POST['goto']);
exit();
}
It is supposed to unset everything! Will I be timed out eventually?
I got this from stackoverflow, still not logged out!
if (isset($_POST['action']) and $_POST['action'] == 'logout')
{
//session_start();
//unset($_SESSION['loggedIn']);
//unset($_SESSION['name']);
//unset($_SESSION['password']);
session_unset(); // unset $_SESSION variable for the run-time
session_destroy(); // destroy session data in storage
header('Location: ' . $_POST['goto']);
exit();
}
Any tips please for this virus-avoider??
EDIT: I opened a private window in Firefox. I opened localhost. I get my webpage. I click the button for class 19BE1. I immediately get the login page. I enter a wrong name and number, which brings me back to the login page with the error message. I enter a correct name and password, I get the page I want. So I think login is working.
Maybe, Firefox is saving something??
If you tired the stackoverflow answer with session_start() line commented out, the session_destroy() would not work.
You can try the bellow simple code which you can modify to your requirement
<?php
session_start();
session_destroy();
header('location: index.php');
?>

Include a php page to password protected the other pages content and showing the user logging in info in the header.php

I would like to include a PHP page to protect every single page and after you login, it would show your username on the top right corner,
also it limits the only data that login user had provided such as his CV and personal info but without seeing other users info.
the structure will be the same as the previous post
index.php (include header.php, content.php and footer.php)
The title on the header.php will be changed menu after user login
Thank you.
Regards
Andy
Well if you want a script to ensure that it would be something like this:
first: Assuming you're not using design patterns and it is a php basic project with an archetype like " scripts(folder) css(folder) js(folder) index.php header.php and footer.php". lets create "security.php".
<?php
session_start(); //starting session to acces to it
if(empty($_SESSION["username"])){// if there's no data username in session
header("location: ./login.php"); //go and take them out of here!
}
?>
Now you have "security.php" ready you just have to include it to your protected pages and create a "login.php" page.
Ex: For including security.
<?php
//#mySecurePage
include "security.php";
//My Page Content Code or event header code if you want validation after loading anything (Best)
?>
Second: Create a Login page like.
<?php
if(!empty($_POST["username"]) && !empty($_POST["password"])){// if all data from login was sent
if($_POST["username"] == "me" && $_POST["password"] == 1234){//your validations here
session_start();//start session to acces it
$_SESSION["username"] == $_POST["username"];//allocate username
header("location: ./securedPageHere.php");//forward to a securedPage
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>My Login Page</title>
</head>
<body>
<form class="" action="" method="post"><!-- action is empty to send data to same page (login)-->
<input type="text" name="username" value="" placeholder="username">
<input type="password" name="password" value="" placeholder="password">
<input type="button" name="login" value="Login">
</form>
</body>
</html>
Now we're almost done, just need to load username at your menu bar
Third: Load username at menu bar. Just add the value accesing session (remember if you have loaded "security.php" you've already started session
<div><?php print($_SESSION["username"]); ?></div>
Now to use the Logut Button you have to destroy session, so add a listener to it and then just execute a script like:
<?php
unset($_SESSION); //clear session array
session_destroy(); //Destroy session
?>
Hope it helps you.
EDIT: to limit data accessed just use the username (best id) data from the login verified data saved at session array :).

tokens do not match (CSRF)

I have entered the following code to prevent CSRF but issuing and checking tokens.
The top section goes on the login.php, the second part goes on the landing page. The issuing of the token works, and when I print $_SESSION['token']on the landing page they match up. However, when i substitute the other code in, its says that they don't match and shows 'expired'.
<?php
session_start();
$_SESSION['token'] = $token;
$_SESSION['token'] = uniqid(md5(microtime()), true);
print $_SESSION['token'];
?>
<html>
<head>
<title>My first PHP website</title>
</head>
<body>
<h2>Please login here to see your tour</h2>
<form action= "checklogin.php" method="post">
Enter Username: <input type="text" name="username" required="required"/> <br/>
Enter Password: <input type="password" name="password" required="required" /> <br/>
<input type="hidden" name="token" value="<?php echo $_SESSION['token'] ?>" />
<input type="submit" value= "login" />
</form>
</body>
<?php
session_start();
print $_SESSION['token'];
session_start();
if ($_POST['token'] !== $_SESSION['token']) {
die('expired');
}
?>
Following our discussion in the comments of your question I'm posting this answer so the information is summarized.
Your code is basically correct but the issue you're having is because after the redirect to the user's unique landing page you no longer can access the data in $_POST you originally have in your checklogin.php, i.e. after submitting the login form.
So in your checklogin.php script you have among others these options:
Include the token in the URL you're redirecting to and then check the $_SESSION['token'] against $_GET['token'].
Set a flag in the $_SESSION indicating that the use has been allowed access to the system. Something like $_SESSION['loggedIn'] = true; (that's what I would recommend)
NOTE: Here you are facing another issue: you have to think about restricting access of each user to only their own page. Imagine that if a user somehow knows the URL of another user's home page they could easily edit the URL and reach it. My recommendation is to save the user's id in the $_SESSION and then at the top of each user's home page to check whether the currently logged in user is allowed to open the said page.
I hope that makes it more clear!
The form action is login.php so when a user logs in the POST data is submitted to the login.php page. Your question does not explain how the user then gets directed to their landing page.
One option would be to try the following.
Replace:
<form action="login.php" method="post">
With:
<form action="landingpage.php" method="post">
That way on your landing page you will be able to get the value of
$_POST['token']

How to make a user stay on same page once they log in

I am having an issue on how to make it where users who are viewing any page can log in on the page they are viewing and it stays on that page. How would this be accomplished?
Below is a single line I am currently using, however, if on any page and a user logs in, they are redirected to their profile. How can I set this line where it logs the user in, and it stays on that same page they are viewing? So in other words, are not redirected to their profile...
PHP:
header("Location: members.php?id=" . $_SESSION['username']);
If more info is needed, let me know and I can make an edit ;)
Have the login form submit the address of the current page. Then you can simply redirect back to that address when the login succeeds, e.g.
<form>
<input type="hidden" name="curpage" value="<?php echo htmlspecialchars($_SERVER['PHP_SELF']) ?>" />
<input type="text" name="username" />
<input type="password" name="password" />
<input type="submit" />
</form>
if ($login_is_successful) {
header("Location: {$_POST['curpage']}");
}
You could try using the referer, but since that's not sent by all browser, and is not always accurate, you're better off sing alternate "current location" tracking means, such as the above hidden form field.
When they click on the login button you can read the url and save it to a varibale and redirect them to this url.
So instead of
header("Location: members.php?id=" . $_SESSION['username']);
you can use sth. like:
header("Location: $last_page);
Try this
you can create a php file with this code and include into your code like this
session.php
<?php
session_start();
error_reporting(0);
if(isset($_SESSION["usuario"]))
{
$usuario = $_SESSION["usuario"];
else{
header('Location: members.php?id=" . $_SESSION['username']');
}
?>
index.php
<?php
include ('session.php');
?>
to avoid using same code in every page

Prevent php direct page access in the url bar

I am doing a small application in core php.Here my database for login is something like this
id
firstname
lastname
email
userid
account_type
contactno
password
in login file the code is something like this
<?php
include_once("include/connection.php");
session_start();
session_unset();
?>
<?php
$msg="";
if(isset($_REQUEST['sub'])){
$pswd=sha1($_REQUEST['psd']);
$sel=mysql_query("select * from login where userid='".$_REQUEST['uid']."' and password='".$pswd."'");
$rowsel=mysql_num_rows($sel);
if($rowsel==1){
$selacc=mysql_fetch_array($sel);
if($selacc['status']!='banned'){
$_SESSION['uid']=$selacc['userid'];
$_SESSION['uname']=$selacc['fname']." ".$selacc['lname'];
$_SESSION['upassword']=$selacc['password'];
$_SESSION['acctype']=$selacc['acctype'];
$_SESSION['agentcode']=$selacc['agent_code'];
$_SESSION['authentication']="authenticated";
header("location:dashboard.php");
}
}
else{
$msg="Enter Valid Username Password";
}
}
?>
<body>
<form name="login-form" method="post" action="#">
<input type="text" name="uid" class="inputbox" />
<input type="password" name="psd" class="inputbox" />
<input type="submit" name="sub" value="" class="inputbotton" />
</form>
Now after the login the user is directed is dashboard. But from here when I am typing directly ``one page name(lets say posts.php) it is redirected to the post.php file. But here I want one denied access that when someone will direct enter the page name in the url(like post.php) it should show some error. But when the page is normal redirect then it should show the page.I want to prevent the direct page access in the address bar but when the page is normal redirected it should show the page.
Just check the any session variable set in previous page for example
if(!isset($_SESSION['uid'])){
echo 'error';
exit;
}
do it on the top
There are 2 factors in it.
1) your folders and files permissions on server.
2) When you login first time, it should show you login page. But when you do the same thing again. The variable stores in session until you close your browser. So, Close the browser and try again. You need to check if session id is set or not, and make decision according to that.

Categories