PHP password protected page cookie - php

I have a very simple PHP password protected page. I'd like to add a session cookie so the browser will stay logged (say for 7 days).
Here is my current code:
<?php
$password = "5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8";
if (sha1($_POST['password']) == $password) {
?>
Password Protected Content
<?php
}
else {
?>
<html>
<head>
<title>Login Page</title>
</head>
<body>
<form name="form" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
Password: <input type="password" name="password" class="formpart" />
<input type="submit" name="Submit" value="Login" class="login-button" />
</form>
</body>
</html>
<?php
}
?>
I have no idea where to start, so I'd really appreciate some help. Thanks in advance!

Please make yourself a look on this things for PHP:
session_start()
Next take a look here: How to change the session timeout in PHP?
$_SESSION[]-Array
Also your code will never jump into the password protected content block.
$password = "password";
if (sha1($_POST['password']) == $password) {
Let's say you gave in the right password ("password") - so the if would ask:
if 5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8 equals password.
You are using hashing, but that is not needed here.

Your requirement is a very classical practice. You can read a tutorial here: http://www.phpnerds.com/article/using-cookies-in-php/2
Notes:
Compare hash to hash
Never save your plain-text password in a cookie
More secure: don't save hashed passwords in cookies like the tutorial.
Just store a session hashed code and using a DB table session to map
it with the user's sessions.
Hope it helps.

Related

setCookie in PHP script

I am working with a simple PHP script that I want to set a cookie on. I do not want this page to refresh. Currently, the page is where I go to upload pictures, and the page refreshes when the upload is done causing the upload to never go through.
<?php $password = "basicadminpassword";
setcookie('password', $password, time()+60*60*24*365, '/', '.myurl.com'); ?>
<?php
// If password is valid let the user get access
if (isset($_POST["password"]) && ($_POST["password"]=="$password")) {
?>
PROTECTED DATA
<?php } else { ?>
<div align="center">
You must have a password to upload pictures.<br /><br />
<form method="post">
<input name="password" placeholder="ADMIN PASSWORD..." type="password" size="25" maxlength="15"><input style="display:none;" value="go" type="submit">
</div>
</form>
<?php } ?>
After the user types in basicadminpassword we wont be asked for it again which will stop the refreshes from happening. If you know of a better way that would be great to hear also!
I don't know what you're doing but you shouldn't save your password plain in a cookie. For security reasons that not a really good idea. Compare the password and save in a session weather the user is logged in or not.
session_start();
$_SESSION['loggedOn'] = true;

Login functionality in HTML page

I have created a HTML page which takes user-id and password from user and then check there validity through database. Till now i was directing them to another page after successful login. But now i want to update same page after login. Just like www.facebook.com ; when we are NOT logged in its asks for user-id and password, but if we are login our profile contents are displayed on the same page i.e. facebook.com. What i was doing; directing it to page "login.php" which of course you can access without login.
For example there is a page "movies.com" which allows user to watch some movies after login; before i was just directing them to another page say "successful_login.com" after they login. It was a funny approach, but was working for my college assignments.
PS. Am just a noob, sorry if i asked something funny.
<?php
if(mysql_connect("localhost","root","")==false)
{
die ("Connection Failed");
}
mysql_select_db("data");
if($_POST)
{
$id=$_POST["email"];
$pwd=$_POST["password"];
$pwd=hash( 'sha256', $pwd);
$sql=mysql_query("SELECT* FROM admin_data WHERE id='$id' AND pass='$pwd'");
if($sql)
{
header("Location: login.php");
}
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset="UTF-8" />
<title>
HTML Document Structure
</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<form method="POST">
<h1>Welcome</h1>
<div class="inset">
<p>
<label for="email">Login</label>
<input type="text" name="email" id="email">
</p>
<p>
<label for="password">PASSWORD</label>
<input type="password" name="password" id="password">
</p>
</div>
<p class="p-container">
<span>Forgot password ?</span>
<input type="submit" name="Login" id="Login" value="Log in">
</p>
</form>
</body>
</html>
To use the session variable you need to start session at the top.
session_start();
Now store the email value in the session in here.
if(mysql_num_rows()>0)//It was originally if($sql)but I am using mysql_num_rows
//The reason for saving the value in the session here is this.
First you want to make sure that user have valid credential to log in.
{
$_SESSION['email']=$id
header("Location: login.php");
}
In your form you can do something like this
session_start();//Start the session at the top so you can use the session variable.
then simply use if else statement.
if($_SESSION['email']==TRUE)
{
$email=$_SESSION['email'];
//Now you can run the query by using $email to fetch the record of the user.
}
else
{
//Show them a form or redirect them to another page.
}
Note:mysql is deprecated and is going to be dropped soon. Use mysqli or P.D.O

Code for a simple singin page using php

I am new to programming. I need a simple login page code for PHP which displays an error message in the same page for incorrect login details and redirected to the account page incase of correct login details. The code should remember the activity and redirect to the account page of the user if he has closed the page without login out. Any help would be deeply appreciated.
Log in page
<html>
<head>
<title>Login</title>
</head>
<h3>Login Page</h3>
<form action="trylog.php" method = "post"><!--action redirects to trylog.php -->
<label for="username">Username</label> <input type="username" id="usename" name="username"><br /><br /><!--username label defined -->
<label for="password">Password:</label> <input type="password" id="password" name="password"><br /><br /><!--password label defined -->
<button type = "submit">Login</button><!--submit button defined -->
</form>
</html>
Account page
<html>
<title>Login</title>
<body>
<?php
session_start(); //resumes previous session based on indentifiers from POST attribute in login.php
$usr = "admin"; //usr keyword defined
$psw = "password"; //psw keyword defined
$username = '$_POST[username]';
$password = '$_POST[password]';
//$usr == $username && $psw == $password
if ($_SESSION['login']==true || ($_POST['username']=="admin" && $_POST['password']=="password"))
//checking for correctness of username and password
{
echo "password accepted";
$_SESSION['login']=true;
//successful login confirmation
echo "<br><a href='http://localhost/login/login.php'>Logout</a>";
}
else
{
echo "incorrect login";
//incorrect login message
}
session_destroy(); //destroys session
?>
</body>
</html>
Thanks
Navaneeth
session_start has to be before output, so move that before <html> etc. (output is a space before <?php too. <?php has to be the first sequence in your code.
what you meant by $psw and $usr variables? You have them in form, delete them.
When you work with variables, don´t use quotes - you can use double-quotes marks, not single. Better is to use no quote marks: $username = $_POST['username'];. On the other hand, the key should be in quote marks, elsewhere you work with undefined constant username - if constant doesn´t exists, PHP work with the same string.
Condition on line 12 will never be true because you test there a SESSION which hasn´t been set before. You set this session on your line 16, but only if this session already exists (line 12). It´s logical nonsense :-)
Why you create variables $username and $password when you doesn´t work with them?
Before you work with $_POST, lines 9 and 10, you must check if the form was sent, so if (isset($_POST['username'])) {}.

POST form variables to another php file after validation

<?php
//index.php
session_start();
if (isset($_SESSION['username'])) {
header('Location: Pro_Lesson.php');
}
if (isset($_POST['username'], $_POST['password'])){
if(empty($_POST['username']) || empty( $_POST['password'])){
echo "username or password are empty";
}else {
header('Location: login.php');
}
}
?>
<html>
<head>
</head>
<body>
<h3>User Login</h3>
<table border="0">
<form method="POST" action="index.php">
<tr><td>Username</td><td>:</td><td><input type="text" name="username" size="20"></td></tr>
<tr><td>Password</td><td>:</td><td><input type="password" name="password" size="20"></td></tr>
<tr><td> </td><td> </td><td><input type="submit" value="Login"></td></tr>
</form>
</table>
</body>
</html>
how can I post the form data to another php page after success validation for username and password ? and is it secure ?
You could do it:
$_SESSION['posted'] = $_POST;
In other php page:
print_r($_SESSION['posted']);
I'm not really sure what you are asking, but I'll take a stab.
You probably only care about the username (or a userid). What you should do is store that the user authenticated in a cookie (or session based cookie). Just storing the user's username (or user id) in a user editable cookie is a Very Bad Idea (tm). What you should do is have a table on the backend of session IDs which the cookie stores a randomized hash of the primary ID then you could use that to look up what information you stored about that user.
Seems complicated, but it's really not. I can expand more on this if you would like.
You could do what felipsmartins suggests, but you shouldn't be storing the user's password anywhere.

Easy way to password-protect php page

I have a page I want to password-protect. I've tried doing HTTP authentication, but for some reason it doesn't work on my hosting. Any other quick (and easy) way to do this? Thanks!
Not exactly the most robust password protection here, so please don't use this to protect credit card numbers or something very important.
Simply drop all of the following code into a file called (secure.php), change the user and pass from "admin" to whatever you want. Then right under those lines where it says include("secure.html"), simply replace that with the filename you want them to be able to see.
They will access this page at [YouDomain.com/secure.php] and then the PHP script will internally include the file you want password protected so they won't know the name of that file, and can't later just access it directly bypassing the password prompt.
If you would like to add a further level of protection, I would recommend you take your (secure.html) file outside of your site's root folder [/public_html], and place it on the same level as that directory, so that it is not inside the directory. Then in the PHP script where you are including the file simply use ("../secure.html"). That (../) means go back a directory to find the file. Doing it this way, the only way someone can access the content that's on the (secure.html) page is through the (secure.php) script.
<?php
$user = $_POST['user'];
$pass = $_POST['pass'];
if($user == "admin"
&& $pass == "admin")
{
include("secure.html");
}
else
{
if(isset($_POST))
{?>
<form method="POST" action="secure.php">
User <input type="text" name="user"></input><br/>
Pass <input type="password" name="pass"></input><br/>
<input type="submit" name="submit" value="Go"></input>
</form>
<?}
}
?>
This is a bit late but I wanted to reply in case anyone else came upon this page and found that the highest reply was a bit off. I have improved upon the system just a tad bit. Note, it is still not amazingly secure but it is an improvement.
First prepare your password salts file:
hash_generate.php:
<?php
$user = "Username"; // please replace with your user
$pass = "Password"; // please replace with your passwd
// two ; was missing
$useroptions = ['cost' => 8,];
$userhash = password_hash($user, PASSWORD_BCRYPT, $useroptions);
$pwoptions = ['cost' => 8,];
$passhash = password_hash($pass, PASSWORD_BCRYPT, $pwoptions);
echo $userhash;
echo "<br />";
echo $passhash;
?>
Take your output $userhash and $passhash and put them in two text files: user.txt and pass.txt, respectively. Others have suggested putting these text files away above public_html, this is a good idea but I just used .htaccess and stored them in a folder called "stuff"
.htaccess
deny from all
Now no one can peek into the hash. Next up is your index.php:
index.php:
<?php
$user = ""; //prevent the "no index" error from $_POST
$pass = "";
if (isset($_POST['user'])) { // check for them and set them so
$user = $_POST['user'];
}
if (isset($_POST['pass'])) { // so that they don't return errors
$pass = $_POST['pass'];
}
$useroptions = ['cost' => 8,]; // all up to you
$pwoptions = ['cost' => 8,]; // all up to you
$userhash = password_hash($user, PASSWORD_BCRYPT, $useroptions); // hash entered user
$passhash = password_hash($pass, PASSWORD_BCRYPT, $pwoptions); // hash entered pw
$hasheduser = file_get_contents("stuff/user.txt"); // this is our stored user
$hashedpass = file_get_contents("stuff/pass.txt"); // and our stored password
if ((password_verify($user, $hasheduser)) && (password_verify($pass,$hashedpass))) {
// the password verify is how we actually login here
// the $userhash and $passhash are the hashed user-entered credentials
// password verify now compares our stored user and pw with entered user and pw
include "pass-protected.php";
} else {
// if it was invalid it'll just display the form, if there was never a $_POST
// then it'll also display the form. that's why I set $user to "" instead of a $_POST
// this is the right place for comments, not inside html
?>
<form method="POST" action="index.php">
User <input type="text" name="user"></input><br/>
Pass <input type="password" name="pass"></input><br/>
<input type="submit" name="submit" value="Go"></input>
</form>
<?php
}
<?php
$username = "the_username_here";
$password = "the_password_here";
$nonsense = "supercalifragilisticexpialidocious";
if (isset($_COOKIE['PrivatePageLogin'])) {
if ($_COOKIE['PrivatePageLogin'] == md5($password.$nonsense)) {
?>
<!-- LOGGED IN CONTENT HERE -->
<?php
exit;
} else {
echo "Bad Cookie.";
exit;
}
}
if (isset($_GET['p']) && $_GET['p'] == "login") {
if ($_POST['user'] != $username) {
echo "Sorry, that username does not match.";
exit;
} else if ($_POST['keypass'] != $password) {
echo "Sorry, that password does not match.";
exit;
} else if ($_POST['user'] == $username && $_POST['keypass'] == $password) {
setcookie('PrivatePageLogin', md5($_POST['keypass'].$nonsense));
header("Location: $_SERVER[PHP_SELF]");
} else {
echo "Sorry, you could not be logged in at this time.";
}
}
?>
And the login form on the page...
(On the same page, right below the above^ posted code)
<form action="<?php echo $_SERVER['PHP_SELF']; ?>?p=login" method="post">
<label><input type="text" name="user" id="user" /> Name</label><br />
<label><input type="password" name="keypass" id="keypass" /> Password</label><br />
<input type="submit" id="submit" value="Login" />
</form>
Here's a very simple way. Create two files:
protect-this.php
<?php
/* Your password */
$password = 'MYPASS';
if (empty($_COOKIE['password']) || $_COOKIE['password'] !== $password) {
// Password not set or incorrect. Send to login.php.
header('Location: login.php');
exit;
}
?>
login.php:
<?php
/* Your password */
$password = 'MYPASS';
/* Redirects here after login */
$redirect_after_login = 'index.php';
/* Will not ask password again for */
$remember_password = strtotime('+30 days'); // 30 days
if (isset($_POST['password']) && $_POST['password'] == $password) {
setcookie("password", $password, $remember_password);
header('Location: ' . $redirect_after_login);
exit;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Password protected</title>
</head>
<body>
<div style="text-align:center;margin-top:50px;">
You must enter the password to view this content.
<form method="POST">
<input type="text" name="password">
</form>
</div>
</body>
</html>
Then require protect-this.php on the TOP of the files you want to protect:
// Password protect this content
require_once('protect-this.php');
Example result:
After filling the correct password, user is taken to index.php. The password is stored for 30 days.
PS: It's not focused to be secure, but to be pratical. A hacker can brute-force this. Use it to keep normal users away. Don't use it to protect sensitive information.
Some easy ways:
Use Apache's digest authorization.
Use lighttpd's digest authorization.
Use php's header digest authorization.
If you want you can also make it so only certain ip addresses can login.. :) really easy with lighttpd
Update: I will post some examples soon, so don't vote down for no examples, i just need to get some down for this answer.
If you want to use sessions the following is the best way to go:
# admin.php
session_start();
if(!$_SESSION["AUTH"])
require_once "login.php";
# Do stuff, we are logged in..
# login.php
session_start();
if($_REQUEST["username"] == "user" && $_REQUEST["password"] == "pass")
$_SESSION["AUTH"] = true;
else $_SESSION["AUTH"] = false; # This logs you out if you visit this login script page without login details.
if($_SESSION["AUTH"])
require_once "admin.php";
This method does not contain the examples for above but you seamed interested in this method. The other method examples are still to come, I have not got enough time to get it for apache or lighttpd settings and the php header auth: http://php.net/manual/en/features.http-auth.php Will do.
I would simply look for a $_GET variable and redirect the user if it's not correct.
<?php
$pass = $_GET['pass'];
if($pass != 'my-secret-password') {
header('Location: http://www.staggeringbeauty.com/');
}
?>
Now, if this page is located at say: http://example.com/secrets/files.php
You can now access it with: http://example.com/secrets/files.php?pass=my-secret-password Keep in mind that this isn't the most efficient or secure way, but nonetheless it is a easy and fast way. (Also, I know my answer is outdated but someone else looking at this question may find it valuable)
A simple way to protect a file with no requirement for a separate login page - just add this to the top of the page:
Change secretuser and secretpassword to your user/password.
$user = $_POST['user'];
$pass = $_POST['pass'];
if(!($user == "secretuser" && $pass == "secretpassword"))
{
echo '<html><body><form method="POST" action="'.$_SERVER['REQUEST_URI'].'">
Username: <input type="text" name="user"></input><br/>
Password: <input type="password" name="pass"></input><br/>
<input type="submit" name="submit" value="Login"></input>
</form></body></html>';
exit();
}
This helped me a lot and save me much time, its easy to use, and work well, i've even take the risque of change it and it still works.
Fairly good if you dont want to lost to much time on doing it :)
http://www.zubrag.com/scripts/password-protect.php
</html>
<head>
<title>Nick Benvenuti</title>
<link rel="icon" href="img/xicon.jpg" type="image/x-icon/">
<link rel="stylesheet" href="CSS/main.css">
<link rel="stylesheet" href="CSS/normalize.css">
<script src="JS/jquery-1.12.0.min.js" type="text/javascript"></script>
</head>
<body>
<div id="phplogger">
<script type="text/javascript">
function tester() {
window.location.href="admin.php";
}
function phpshower() {
document.getElementById("phplogger").classList.toggle('shower');
document.getElementById("phplogger").classList.remove('hider');
}
function phphider() {
document.getElementById("phplogger").classList.toggle('hider');
document.getElementById("phplogger").classList.remove('shower');
}
</script>
<?php
//if "login" variable is filled out, send email
if (isset($_REQUEST['login'])) {
//Login info
$passbox = $_REQUEST['login'];
$password = 'blahblahyoudontneedtoknowmypassword';
//Login
if($passbox == $password) {
//Login response
echo "<script text/javascript> phphider(); </script>";
}
}
?>
<div align="center" margin-top="50px">
<h1>Administrative Access Only</h1>
<h2>Log In:</h2>
<form method="post">
Password: <input name="login" type="text" /><br />
<input type="submit" value="Login" id="submit-button" />
</form>
</div>
</div>
<div align="center">
<p>Welcome to the developers and admins page!</p>
</div>
</body>
</html>
Basically what I did here is make a page all in one php file where when you enter the password if its right it will hide the password screen and bring the stuff that protected forward. and then heres the css which is a crucial part because it makes the classes that hide and show the different parts of the page.
/*PHP CONTENT STARTS HERE*/
.hider {
visibility:hidden;
display:none;
}
.shower {
visibility:visible;
}
#phplogger {
background-color:#333;
color:blue;
position:absolute;
height:100%;
width:100%;
margin:0;
top:0;
bottom:0;
}
/*PHP CONTENT ENDS HERE*/
This stores the password in history after login!
You can specify a password in your php code so only users that have the secret url can access:
mywebsite.com/private.php?pass=secret
in your login-protected file:
<?php
if(isset($_GET["pass"]) && $_GET["pass"]=="secret"){
//put your code here
}
else{
echo "you're not allowed to access this page";
}
?>

Categories