I want to make an PHP session after the visitor enters a valid password so I can display a few hidden links to the visitor, even on page reload.
<?php
if(isset($_POST['submit'])) {
$password = crypt('sumpasswurd', password_hash('rasmuslerdorf', PASSWORD_BCRYPT)); // password
if (hash_equals($password, crypt($_POST['password'], $password))) {
echo 'VALID!';
// CREATE SESSION HERE
} else {
echo 'INVALID';
}
}
if(isset($_SESSION)) echo 'YOU ARE LOGGED IN WITH A VALID PASSWORD!';
?>
<form method="POST" action="">
<input type="text" name="password">
<input type="submit" name="submit" value="OK">
</form>
How can I make this possible? And is the encryption of my form secure?
Manual session starts with session_start() function. Although you need to secure the session by some kind of user indetification logic. For instance, you have user's username and add it as a session variable and afterwards pass some kind of session id to verify that current session user is indeed loged in. Afterwards you have to check those variables in every pageload that is associated with user.
At: // CREATE SESSION HERE you might want to use something like this:
Session_start();
$_SESSION['username'] = $username;
// flollowed by session id logic
Related
I have two pages made in PHP, index (using it as login page) and main page (this one should be protected).
Index page has a login form that asks only for password (there are no users intended to be).
I want to make this:
1. When you enter password on index page, and if it's correct, the site will redirect you to the main page. If password is not correct then it will alert you about that.
2. Main page should not be visible if you have not entered password on the index page. If you have entered it then you will be able to see the main page.
I figured out that the easiest way would be to make it with PHP session check, but it's not working on my code, so can you please help me?
So this is my PHP code for the index page. Here the site needs to check is (universal, for all) password correct, and if so it needs to redirect to main, or if not to display some alert box.
<?php
session_start();
$password = '1234';
if($_POST['password'] == $password){
//Create session
$_SESSION['session'] = 1;
// If correct redirect to main
header('Location: http://www.example.com/main');
exit;
}
else {
// If not correct stay on index (do nothing)
}
?>
Code my main page looks like this. This is where the site should check if user has session and then decide should he be able to see the site or not (if not it should redirect to index for login).
<?php
session_start();
if (!isset($_SESSION["session"]))
{
header("location: http://example.com/index");
}
?>
I Googled everything and came out with no working solution. Is there better way to achive this or can you help me fix it?
So TLDR, how to password protect main page with login (no users, same password for everyone)?
Currently this code doesn't work. When I enter password on index it redirects to main. But main page doesn't have session check working. It simply shows all without redirecting to index for login if user is without session.
Ok.. sorry for my first advice. It is obviously not a solution. But if i understand you correctly. This is my working approach:
index.php
<?php
session_start();
$password = '1234';
// Check if the user is not already logged in
if (isset($_SESSION['login'])) {
header('Location: main.php');
}
// Check if the form is submitted
if (isset($_POST['submit'])) {
if ($_POST['password'] == $password) {
$_SESSION['login'] = true;
header('Location: main.php');
}
}
?>
with form
<form action="" method="post">
<input class="upisnopolje" type="password" name="password" placeholder="Unesite kod" required>
<input class="upisnopolje" id="upisnopoljefix" type="submit" name="submit" value="Ok">
</form>
main.php
<?php
session_start();
// Check if user is logged in
if (!isset($_SESSION["login"])) {
header("location: index.php");
}
if ( isset( $_POST['submit'] ) ) {
unset($_SESSION["login"]);
header("location: index.php");
}
?>
with form to logout
<form action="" method="post">
<input type="submit" name="submit" value="Log out">
</form>
Note that submit button needs to have name="submit" for $_POST['submit'] check.
Hope it helps.
I am having an issue right now with sessions. I use a log in script to do initial authentication, and then i authenticate at the begining of each protected page, and finally i try to log out (code below).
The files exist on my server using PHP 5.6. I am using Win10 and Chrome on my pc.
SYMPTOMS:
Although session vars are destroyed, i can still use the 'back' button in my browser to view a page that does authentication. When i dump $_SESSION vars on that page (which i browsed back to using the back button of the browser) all $_SESSION var are non existent - but the page still loads.
COOKIES are still there. I have set cookie lifetime in my php ini to 1 (one second) for testing... they are still there after i supposedly delete them. Even when set to 0, they are still there after i restart the browser.
After reading symptom 1 above, i think many of you will guess, correctly, that the session is still alive and well - even after i close the browser, restart it and type the url of one of the protected pages directly in the address bar i am still able to view the page, even though the $_SESSION var that checks for authentication does not exist.
Would really appreciate advice.
LOG IN SCRIPT
//this page is called (using require_once) by the page
//that captures username and password
session_start();
//requirements
require_once "../php/path.php"; //sets the server search path
require_once "constants.php"; //does all the DEFINE stuff
require_once HTML_HEADER; //loads HTML code - doc type, head etc
require_once DATABASE; //does the dB connecting
//collect the POST
$uName = $_POST[uName];
$uPsswd = $_POST[uPsswd];
//build & execute sql query
**SQL to retreive uName and password here if match then...**
$_SESSION['approved'] = 'true';
require_once MAIN_CONTENTS; //main page after authentic log in
exit;
AUTHENTICATE CODE CALLED USING require_once BY EACH PROTECTED PAGE
if (session_status() == PHP_SESSION_NONE) {
session_start();
}//end if
//what's the time Mr Wolf?!!!
$now = time();
//although session exists, are we logged in and approved? If not kill session & eixt.
if (isset($_SESSION['approved']) && $_SESSION['approved'] != 'true'){
require_once "killSession.php";
require_once "notAuthorised.php";
exit;
}//end if
if (!isset($_SESSION['approved'])){
require_once "killSession.php";
require_once "notAuthorised.php";
exit;
}
//if session exists, how old is it? If older than 'discard_after' then kill session.
if (isset($_SESSION['discard_after']) && $now > $_SESSION['discard_after']) {
require_once "killSession.php";
require_once "notAuthorised.php";
exit;
}//end if
else {
//logged in and approved so set timeout for 15 mins
$_SESSION['discard_after'] = $now + 30;
}//end else
THE killSession FILE
//check to make sure session exists - start if not
if (session_status() == PHP_SESSION_NONE) {
session_start();
$_SESSION['approved']='false';
}//end if
//following code caused 'headers already sent...'
//if (isset($_COOKIE[session_name()])) {
//$params = session_get_cookie_params();
//setcookie(session_name(),'',time() - 172800, '/', $params['domain'], $params['secure'], isset($params['httponly']));
//}
session_unset();
session_destroy();
session_write_close();
setcookie(session_name(),'',0,'/');
session_regenerate_id(true);
?>
Your issue is most probably caused by the POST data still being stored in your browser. By clicking the back button, your user is authenticated again and a session is created.
To resolve this issue you can use the POST-Redirect-GET method.
<?php
// Has the session been set?
if (!isset($_SESSION)) {
session_start();
}
// If a form is submitted, add the POSt data to a session
// and redirect
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$_SESSION['login_data'] = $_POST;
unset($_POST);
header("Location: ".$_SERVER['PHP_SELF']);
exit;
}
// Check if user wants to login, authenticate and unset login data
if (isset($_SESSION['login_data'])) {
// Authenticate
unset($_SESSION['login_data']);
}
?>
<form action="" method="POST" role="form" action="<?= $_SERVER['PHP_SELF']; ?>">
<label for="username">Username</label>
<input type="text" class="form-control" id="username" placeholder="Username"
<label for="password">Password</label>
<input type="password" class="form-control" id="password" placeholder="Password">
<button type="submit" class="btn btn-primary">Authenticate</button>
</form>
I have seen several instances of this question but did not get a clear answer. Here is my scenario
I have a form on login.php - this should submit to loginController.php
Once loginController.php validates against the databse, it should either redirect to home.php or pass back to login.php with appropriate success / error messages
I know I can pass information back-forth between pages using SESSION but I would rather avoid using SESSION for just messages and objects that are page specific.
In JAVA we can embed objects into request object and then forward the control to the next page. Is there something equivalent in PHP?
The way I am doing it at present is as below -
1.loginController.php has the main page and it includes login.php
2.login.php resubmits the data back to loginController.php (sorta recursive submit)
3.Then there is if-then-else logic to determine whether next redirect needs to go to home.php or just include login.php once again with error messages
From our discussion, I think the following snippet may do what you want. You can use $_SESSION variable to store user data and $_POST variable to discriminate if user has submitted username and password data:
Login Controller
/* Already logged in */
if(isset($_SESSION['username'])
{
header('Location:home.html');
}
/* Not logged in */
else
{
/* Login submitted */
if(isset($_POST['submit']))
{
$user = new User(); // this is an instance of model class
$username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING);
$password = filter_input(INPUT_POST, 'password', FILTER_SANITIZE_STRING);
$login_result = $user->login($username, $password);
/* Login success */
if($login_result == true)
{
$_SESSION['username'] = $username;
header('Location:home.html');
}
/* Login error */
else
{
$view_data = "Login incorrect"; // here you can set some data to be shown on login view
showView('login.html'); // pseudo code, change with your code to show login view
}
}
/* Show login form */
else
{
showView('login.html'); // pseudo code, change with your code to show login view
}
}
Login view
<?php if(!empty($view_data)) echo $view_data; /* Here you show login result (i.e. errors) */ ?>
<form method="post" action="login.html">
<input type="text" id="username" name="username" placeholder="Username" />
<input type="password" id="password" name="password" placeholder="Password" />
<input type="submit" name="submit" value="Login" />
</form>
Of course, you must implement $user->login method on user model (I strongly suggest you to use PDO statements to query database). This method simply checks user data and returns true on login success and false on failure.
On logout, simply unset($_SESSION['username']) and you're done.
I also suggest you to have a look on something like this session security question, to protect your session against hijacks. Hope it helps.
You can use query strings.
when you redirect to login.php as a result of an error, your full url will be something like:
login.php?status=error&message=invalid_credentials
in your login.php,
you can access the extra information as follows
$_GET['status'];//will contain the status
$_GET['message'];//will contain the message
Cheers!
I have just finished creating an entire login and register systsem in PHP, but my problem is I haven't used any sessions yet. I'm kind of a newbie in PHP and I've never used sessions before. What I want to do is, after the user registers and fills out the login form, they will still stay on the same page. So, there will be one part of the which will be if the session is logged_in and the other part will be else (the user is not logged in so display the login form). Can anyone tell me how to get started?
Begins the session, you need to say this at the top of a page or before you call session code
session_start();
put a user id in the session to track who is logged in
$_SESSION['user'] = $user_id;
Check if someone is logged in
if (isset($_SESSION['user'])) {
// logged in
} else {
// not logged in
}
Find the logged in user ID
$_SESSION['user']
So on your page
<?php
session_start();
if (isset($_SESSION['user'])) {
?>
logged in HTML and code here
<?php
} else {
?>
Not logged in HTML and code here
<?php
}
here is the simplest session code using php.
We are using 3 files.
login.php
<?php session_start(); // session starts with the help of this function
if(isset($_SESSION['use'])) // Checking whether the session is already there or not if
// true then header redirect it to the home page directly
{
header("Location:home.php");
}
if(isset($_POST['login'])) // it checks whether the user clicked login button or not
{
$user = $_POST['user'];
$pass = $_POST['pass'];
if($user == "Ank" && $pass == "1234") // username is set to "Ank" and Password
{ // is 1234 by default
$_SESSION['use']=$user;
echo '<script type="text/javascript"> window.open("home.php","_self");</script>'; // On Successful Login redirects to home.php
}
else
{
echo "invalid UserName or Password";
}
}
?>
<html>
<head>
<title> Login Page </title>
</head>
<body>
<form action="" method="post">
<table width="200" border="0">
<tr>
<td> UserName</td>
<td> <input type="text" name="user" > </td>
</tr>
<tr>
<td> PassWord </td>
<td><input type="password" name="pass"></td>
</tr>
<tr>
<td> <input type="submit" name="login" value="LOGIN"></td>
<td></td>
</tr>
</table>
</form>
</body>
</html>
home.php
<?php session_start(); ?>
<html>
<head>
<title> Home </title>
</head>
<body>
<?php
if(!isset($_SESSION['use'])) // If session is not set then redirect to Login Page
{
header("Location:Login.php");
}
echo $_SESSION['use'];
echo "Login Success";
echo "<a href='logout.php'> Logout</a> ";
?>
</body>
</html>
logout.php
<?php
session_start();
echo "Logout Successfully ";
session_destroy(); // function that Destroys Session
header("Location: Login.php");
?>
Firstly, the PHP documentation has some excellent information on sessions.
Secondly, you will need some way to store the credentials for each user of your website (e.g. a database). It is a good idea not to store passwords as human-readable, unencrypted plain text. When storing passwords, you should use PHP's crypt() hashing function. This means that if any credentials are compromised, the passwords are not readily available.
Most log-in systems will hash/crypt the password a user enters then compare the result to the hash in the storage system (e.g. database) for the corresponding username. If the hash of the entered password matches the stored hash, the user has entered the correct password.
You can use session variables to store information about the current state of the user - i.e. are they logged in or not, and if they are you can also store their unique user ID or any other information you need readily available.
To start a PHP session, you need to call session_start(). Similarly, to destroy a session and its data, you need to call session_destroy() (for example, when the user logs out):
// Begin the session
session_start();
// Use session variables
$_SESSION['userid'] = $userid;
// E.g. find if the user is logged in
if($_SESSION['userid']) {
// Logged in
}
else {
// Not logged in
}
// Destroy the session
if($log_out)
session_destroy();
I would also recommend that you take a look at this. There's some good, easy to follow information on creating a simple log-in system there.
I always do OOP and use this class to maintain the session so u can use the function is_logged_in to check if the user is logged in or not, and if not you do what you wish to.
<?php
class Session
{
private $logged_in=false;
public $user_id;
function __construct() {
session_start();
$this->check_login();
if($this->logged_in) {
// actions to take right away if user is logged in
} else {
// actions to take right away if user is not logged in
}
}
public function is_logged_in() {
return $this->logged_in;
}
public function login($user) {
// database should find user based on username/password
if($user){
$this->user_id = $_SESSION['user_id'] = $user->id;
$this->logged_in = true;
}
}
public function logout() {
unset($_SESSION['user_id']);
unset($this->user_id);
$this->logged_in = false;
}
private function check_login() {
if(isset($_SESSION['user_id'])) {
$this->user_id = $_SESSION['user_id'];
$this->logged_in = true;
} else {
unset($this->user_id);
$this->logged_in = false;
}
}
}
$session = new Session();
?>
//start use session
$session_start();
extract($_POST);
//extract data from submit post
if(isset($submit))
{
if($user=="user" && $pass=="pass")
{
$_SESSION['user']= $user;
//if correct password and name store in session
}
else {
echo "Invalid user and password";
header("Locatin:form.php");
}
if(isset($_SESSION['user']))
{
//your home page code here
exit;
}
Here's a single-page login / logout system example.
The password is never exposed, and the HASH+SALT is just as secure as anyone having a look at your database table with hash-salted passwords.
First, create a salted password $hash using this sandbox.io and make sure to replace the result String with the below $hash's ***
index.php single page:
<?php
// stackoverflow.com/a/67661402/383904
session_start();
$username = "pony";
$salt = "PonieshaveunicornS"; // Use something really custom instead of ponies
$hash = "***"; // Replace *** with the result of: echo hash("sha256", "myPassword".$salt);
$url = strtok($_SERVER["PHP_SELF"], '?');
$errorMessage = ""; // Used for login error messages
// LOGOUT SYSTEM
if (isset($_GET["p"]) && $_GET["p"] == "logout"):
session_destroy();
header("Location: $url");
exit;
endif;
// LOGIN SYSTEM
if (isset($_POST['un']) && isset($_POST['pw'])):
sleep(3); // Makes it ages slower for rainbow attacks
if ($_POST['un'] == $username && hash("sha256", $_POST['pw'].$salt) == $hash):
$_SESSION['_reg'] = $_POST['un'];
header("Location: $url");
exit;
else:
$message = "Incorrect login data";
endif;
endif;
// DETERMINE A VALID LOGIN
$isLoggedIn = isset($_SESSION['_reg']) && $_SESSION['_reg'] == $username;
// YOUR CUSTOM LOGGED-IN METHODS AND STUFF
if ($isLoggedIn):
// I.e: your DB connections, functions, methods, etc...
endif;
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My app</title>
</head>
<body>
<div id="app">
<?php if ($isLoggedIn): ?>
<h1>Welcome <?= $_SESSION["_reg"] ?></h1>
Logout
<?php else: ?>
<h1>LogIn</h1>
<form action="./index.php" method="post">
<label><input type="text" name="un" placeholder="Username" /></label><br>
<label><input type="password" name="pw" placeholder="Password"/></label><br>
<input type="submit" id="submit" value="LOGIN" />
</form>
<b><?= $errorMessage ?></b>
<?php endif; ?>
</div>
</body>
</html>
Disclaimer: Be aware that the above
Is not that bad, but
should be improved using SHA rounds and/or a stronger algorithm than SHA256
never hardcode secrets (salts) or hashs into distributable files
is still susceptible to Session hijacking
It is exposable (Facebook'07 syndrome) by a malformatted/broken server file type response
is not professional (read: forbidden) to push such code a public git repo with the exposed secret Salt and Hash
might be OK-ish for a short-term "Login to See something" project
you should never "just copy-paste" from Stack Overflow without a proper, deeper understanding of the provided code / scripts.
$session_start();
extract($_POST);
//extract data from submit post
if(isset($submit))
{
if($user=="user" && $pass=="pass")
{
$_SESSION['user']= $user;
//if correct password and name store in session
} else {
echo "Invalid user and password";
header("Locatin:form.php")
}
if(isset($_SESSION['user']))
{
}
You need to begin the session at the top of a page or before you call session code
session_start();
$session_start();
extract($_POST);
//extract data from submit post
if(isset($submit))
{
if($user=="user" && $pass=="pass")
{
$_SESSION['user']= $user;
//if correct password and name store in session
}
else {
echo "Invalid user and password";
header("Locatin:form.php");
}
if(isset($_SESSION['user']))
{
//your home page code here
exit;
}
I'm looking for a php script so my entire site needs a password to access. I don't want a sql database, I just want one user who's credentials are set in a variable.
I have
config.php
<?php
$secured = false;
$username = "user"; // Set manually by editing config
$password = "pass"; //Set manually by editing config
?>
Then index.html
<form action="auth.php" method="post">
Username: <input type='text' name="user" value='' />
Password: <input type='password' name="password" value='' />
<input type='submit' value='Log in' />
</form>
Then auth.php (This is what I need coded)
<?php
require once "config.php"
If $secured = false the redirect to page1.html
// So if its false don't require authentication at all anywhere on site.
If $secured = true then ask for username and password.
If wrong display error message.
If right redirect to page1.html
?>
That's what I'm trying to achieve. I then also need the login stored as a session variable so it remembers you logged in and checks on each page that you are logged in. Then finally a way to log out. So a button I can just stick somewhere will do the job. Hope this all makes sense.
Question : How does the auth.php script look like?
Thanks
You could use sessions to remember if a user has logged in. To do that, add:
session_start();
in config.php
On every page that requires log in, add this at the top of the script:
require_once('config.php');
if ($secured && (!isset($_SESSION['loggedin']) || !$_SESSION['loggedin'])) {
header('Location: index.html');
exit;
}
Auth.php should look like the following.
<?php
require_once("config.php");
If (!$secured) {
header('Location: page1.html');
exit;
}
if (isset($_POST['user']) && isset($_POST['password'])) {
if ($_POST['user']==$username && $_POST['password']==$password) {
// OK
$_SESSION['loggedin'] = true;
header('Location: page1.html');
exit;
} else {
echo "Bad login credentials. Try again";
}
} else {
// not logging in
header('Location: index.html');
exit;
}
?>
To sign out, just create a script logout.php:
<?php
require_once('config.php');
$_SESSION['loggedin'] = false;
?>
You can use session (see $_SESSION) to store if a user is logged in or not.
Once a user is logged in you can set a session that someone is logged in and then on each visit check if session exists and it is valid (using private salt and hash). If session variable does not exist or is invalid direct user to login page.