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.
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 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']
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 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
Suppose i am using pure php, with no javascript/jquery or ajax.
I have many pages in a website, lets say page1, page2, page3 and page4.
all of the first three pages have a link to go to page4, to log in.
In page 4 i have a form field, and above I have a php script to catch the user input and put the username in a session and after that i want to redirect to the page where the user came from, but the page is not redirecting.
Let me put the code.
<?php
ob_start();
session_start();
if(isset($_POST['username'])){
$username = $_POST['username'];
$_SESSION['username'] = $username;
if(isset($_SERVER['HTTP_REFERER'])){
$referer = $_SERVER['HTTP_REFERER'];
header('location: '.$referer);
}
}
?>
<form action="page4.php" method="POST">
Username: <input type="text" name="username" /><br/>
<input type="submit" value="Submit" />
</form>
I am starting again all page1, page2, page3 with ob_start() and session_start();
If I use a specific page into the header function then it is redirecting, no problem
for example header (location: page2.php).
I am guessing the reason is maybe as my form field and the php script are at the same page (page4)
So how to redirect dynamically? User might come from page 1 or page2 or page 3 and after log in i want them back to the specific page they came from.
In page1.php, page2.php, page3.php:
<?php
session_start();
$_SESSION['page'] = $_SERVER['PHP_SELF'];
in page4.php:
<?php
session_start();
// process form
if ($form_proccessed == true) // or whatever
{
header("Location: {$_SESSION['page']}\r\n");
exit;
}
Using $_SERVER['PHP_SELF'] you wont have to worry about updating the code if you save the file as a new file with a new name.
It can be done with an hidden input field inside the formĀ :
<input type="hidden" name="referer" value="$_SERVER[HTTP_REFERER]">