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']
Related
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 :).
I know that I can redirect to a website by using:
<?php header('Location: http://site/'); ?>
but how can I make it redirect to a variable value and make the redirect URI look like:
http://myURL.com/redirect.php?variable=http://redirect.com
Thanks!
Your page that asks a user for the URL:
<form action="redirect.php" method="GET">
<input type="text" name="url" />
<input type="submit" />
</form>
redirect.php
<?php
if(isset($_GET['url'])){
header("Location: http://" . $_GET['url'] . "");
exit();
}
?>
What this does
When a user submits a form on your index page (or wherever you dropped the <form> code they are redirected to http://yoursite/redirect.php and the variable url is appended to the URL as such: http://yoursite/redirect.php?url=THEURL where "THEURL" in this example is the URL that the user typed in on the form.
Please note, this is nowhere near secure enough, not does it do any validation (which you should absolutely do).
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
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.
I was trying to redirect users to the previous page after authentication. It works well with the below codes.
The file login_page.php (the page where users enter login credentials) contains the below code which stores the SOURCE URL and passes it to next page.
<input type="hidden" name="url" value=<?php echo $_SERVER['HTTP_REFERER'] ; ?> />
File do_authentication.php (page which does the authentication) has the code echo "<meta http-equiv='Refresh' content=0;url='$_POST[url]'>"; which redirects to SOURCE URL
In the normal situation it works, but in situations when user enters wrong credentials, the page is redirected to login_page.php and it asks the user to try again with correct credentials. At that time, 'url' value changes to login_page.php.
What is the correct/better logic to solve this?
I've always used the session to retain the original page when doing login. This will not work if the session isn't supported. Then I just send the user to the home page.
A Stack Overflow post discussing this is Redirect to previous page after logging in using PHP.
You should consider using session variables to store the value of the page you want to redirect to. HTTP_REFERRER is not right option.
Just try below:
<input type="hidden" name="url" value=<?php echo pathinfo(__FILE__,PATHINFO_FILENAME ).".".pathinfo(__FILE__,PATHINFO_EXTENSION); ?> />
Use:
header("location: ".$_POST['url']); // Redirects to posted page
exit; // Prevents execution of other code after this
In login_page.php, you could check if you already passed a URL; if so, pass this one instead of the HTTP_REFERER.
<?php if(isset($_POST['url']) ?>
<input type="hidden" name="url" value=<?php echo $_POST['url'] ; ?> />
<?php else ?>
<input type="hidden" name="url" value=<?php echo $_SERVER['HTTP_REFERER'] ; ?> />
Or in a more concise way
<?php $url= (isset($_POST['url'])) ? $_POST['url'] : $_SERVER['HTTP_REFERER']; ?>
<input type="hidden" name="url" value=<?php echo $url; ?> />