Easy way to password-protect php page - php

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";
}
?>

Related

Can't redirect from login page to home page [duplicate]

This question already has answers here:
How do I make a redirect in PHP?
(34 answers)
Closed 7 years ago.
I am learning pHp. I have made a login page.
The problem i am facing here is that, when user clicks on signin button & if record is found then he is taken to other page which displays redirect link, the user has to click on that to go to the next page.
Now what i want that when a user click on signin button, then the details should be cross checked in the database, if the record is found then user should be directly redirected to next page else error should be displayed.
This is my html page:
<!DOCTYPE html>
<html>
<head>
<title>OpenMoz</title>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="index.css"/>
</head>
<body style="height:650px;">
<h1 align="center" ><b><i>City Login</i></b></h1>
<div class="login">
<form action="login.php" method="post">
<input type="text" placeholder="Username" name="username" autocorrect=off autocapitalize=words required> <br>
<input type="password" placeholder="password" name="password" autocorrect=off autocapitalize=words required> <br>
<input type="submit" name="submit" value="Sign In">
</form>
<input type="submit" name="submit" value="Sign Up">
<div>
</body>
</html>
This is the login.php script to verify details :
<?php
$username = $_POST["username"];
$password = $_POST["password"];
if($username && $password)
{
$connect = mysql_connect("localhost","root","password") or die("Couldn't connect");
mysql_select_db("phplogin")or die("Couldn't connect");
$query = mysql_query("SELECT * FROM users WHERE username='$username'");
$numrows = mysql_num_rows($query);
if($numrows!=0)
{
while($row = mysql_fetch_assoc($query))
{
$dbusername = $row['username'];
$dbpassword = $row['password'];
}
if($username==$dbusername && $password==$dbpassword)
{
echo ("<center><a href='home.php'>Redirect</a></center>");
$_SESSION['username'] = $username;
}
else
{
echo ("Incorrect Password !");
}
}
else
die("The user doesn't exist");
}
else
echo ("Please enter username & password");
?>
I would be really thankful if my problem gets solved.
As long as you have not outputted anything to the browser, you can do a header redirect. This will achieve your aim.
Change this:
echo ("<center><a href='home.php'>Redirect</a></center>");
$_SESSION['username'] = $username;
To this:
$_SESSION['username'] = $username;
header("Location: /some-new-page.php");
exit;
Always exit; after a location redirect.
Oh yeah, and CLEAN your inputs.. ..you are wide open to SQL Injection.
$username = mysql_real_escape_string($_POST["username"]);
$password = mysql_real_escape_string($_POST["password"]);
Oh yeah .. and mysql_* is deprecated. Use mysqli_*
use header("Location:home.php"); its best way to redirect page in php
header("Location:whaeverpage.php");
exit();
Do it before sending any data to the browser or you will get a header allready sen error
or by javascript :
If($connected ==='yes'){//your connection statement
?>
<script>window.location.replace("whatever_page");</script>
<?
}
WOWOW NONONO HALT! DO NOT LEARN mysql_ API FOR NEW DEVELOPMENT. It's deprecated/unsupported, ancient, error-prone. learn to use mysqli_ or better yet, PDO , and here is a great tutorial http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers
also here: $query = mysql_query("SELECT * FROM users WHERE username='$username'");
code is vulnerable to SQL injection attack by hackers. must use mysql_real_escape_string.
also, you should not use * , for most cases, be specific. Also, you should not store passwords in plaintext (as your login system is doing), you should hash it..
other than that, check Chris Magg's already said what i would'ev https://stackoverflow.com/a/31355969/1067003

PHP Session Information Not Being Stored

I am trying to make a very simple website, where you can go to the main page and log in, of which the code is here example.org/login/index.php:
<?php
session_start();
$warning = $_GET['warning'];
$nolog = $_GET['nolog'];
$username = "Welcome, please log in";
if ($warning) {
$username = "Wrong Username/Password Combination";
}
if ($nolog) {
$username = "Page inaccessible: Login required";
}
if ($logout) {
$username = "Thank you for your session";
}
?>
<!DOCTYPE html>
<body>
<div class="center">
<span class="warning"><?= $username ?></span>
<form action="submit.php" method="post">
<span class="formField">Username:</span><br>
<input type="text" name="user" class="field">
<br>
<span class="formField">Password:</span><br>
<input type="password" name="password" class="field">
<br>
<br>
<input type="submit" name="submit" value="Submit" class="field">
</form>
</div>
</body>
</html>
The submit page looks like this (when I get this to work I won't have the username and password hard coded like this, it's just to be concise for now) example.org/login/submit.php:
<?php
session_start();
$username = $_POST['user'];
$password = $_POST['password'];
if ($username == "admin" && $password == "12345") {
$_SESSION['loggedin'] = TRUE;
header("Location: http://www.example.org/welcome/");
die();
}
else {
$_SESSION['loggedin'] = FALSE;
header("Location: http://www.example.org/login/index.php?warning=true");
die();
}
?>
And the welcome page looks like this example.org/welcome/index.php:
<?php
session_start();
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] == FALSE){
unset($_SESSION);
session_destroy();
header("Location: http://www.example.org/login/index.php?nolog=true");
}
?>
<!DOCTYPE html>
<body>
Hi
</body>
</html>
I know this is a lot of code, but when I try running it the first time around the welcome page returns an error saying that it is inaccessible, and sends me back to the login page, but the second time around it seems to work fine and logs me in. Can anyone understand why that would be?
EDIT:
After looking more into it, I discovered that the problem ONLY exists in Google Chrome and Firefox, but does not exist in other browsers such as Internet Explorer or Apple Safari. This now goes into the rendering engine of the browsers. Does anyone perhaps know of another way that I can use session ID's that might bypass this whole issue on all browsers, perhaps another way of validating a user?
Try to use the following
define('BASE_URL', 'http://www.example.org/');
if ($username == "admin" && $password == "12345") {
$_SESSION['loggedin'] = TRUE;
header("Location:".BASE_URL."welcome.php");
exit();
} else {
header("Location:".BASE_URL."index.php");
exit();
}
Add the following in the begining of welcome page
session_start();
if(!isset($_SESSION['loggedin'])){
header("Location:".BASE_URL."index.php");
exit();
}
If you pay attention to the names of the files that I mentioned, I was saying that I was directing my browser to example.org/login/submit.php and then forwarding that to www.example.org/welcome/index.php.
In Google Chrome and Mozilla Firefox, they care about the difference between having a www before the website or not, whereas in Internet Explorer and Safari they do not care about the difference. On my server the website www.example.org and example.org are mirrors of each other (this is a separate security issue) and therefore Google Chrome and Mozilla Firefox will treat them differently and give them different $_SERVER global variables, whereas Internet Explorer and Safari don't care about that difference.

Bug using PHP Sessions (Two Log On screens)

In the application I'm developing I'm having a bug where I direct my browser to my app's index.php, and is then properly redirected to login.php if there is no current session. My problem is that after I type in my correct details on login.php and click submit, I am linked to another login.php screen (instead of returning to index.php with an active session) and required to put in my details again. The first screen has the same CSS formatting as index.php, while the second screen doesn't.
After entering my details on the second screen and clicking login, the sessions seem to function normally. Also, many times I will be presented with one logon screen, ill login and the user's correct Home screen data will be displayed (which requires successful queries from the login data), but if I navigate away from index.php to another screen that requires an active session, it will present the unformatted login.php screen.
If I logout, navigate to a different non-restricted page, and attempt to log back in again within the same browser session, the logon functions correctly with only one screen.
Here are snippets from the relevant files:
index.php
<?php
include_once 'db_functions.php';
require_once 'access.php';
if (isset($_POST['action'])) {
if (userIsLoggedIn()) {
header('Location: http://www.myapp.com/index.php'); //prevents users from having to confirm form resubmission if they refresh the page
}
}
if (!userIsLoggedIn()) {
include 'login.php';
exit();
}
login.php:
login.php
<body>
<h1>Log In</h1>
<?php
if (isset($loginError)) {
echo $loginError;
}
?>
<form action="" method="post">
<div>
<label for="email">Email: <input type="text" name="email" id="email" /> </label>
</div>
<div>
<label for="password">Password: <input type="password" name="password" id="password" /></label>
</div>
<div>
<input type="hidden" name="action" value="login" />
<input type="submit" value="Log in" />
</div>
</form>
</body>
access.php:
<?php
function userIsLoggedIn() {
if (isset($_POST['action']) and $_POST['action'] == 'login') {
if (!isset($_POST['action']) or $_POST['email'] == '' or
!isset($_POST['password']) or $_POST['password'] == '') {
$GLOBALS['loginError'] = 'Please fill in both fields';
return FALSE;
}
$email = $_POST['email'];
$password = $_POST['password'];
if (databaseContainsAuthor($email, $password)) {
session_start(); //LINE 17
$_SESSION['loggedIn'] = TRUE;
$_SESSION['email'] = $email;
$_SESSION['password'] = $password;
return TRUE;
}
else {
session_start();
unset($_SESSION['loggedIn']);
unset($_SESSION['email']);
unset($_SESSION['password']);
$GLOBALS['loginError'] = 'The specified email address or password was incorrect.';
return FALSE;
}
}
if (isset($_POST['action']) and $_POST['action'] == 'logout') {
session_start();
unset($_SESSION['loggedIn']);
unset($_SESSION['email']);
unset($_SESSION['password']);
header('Location: ' . $_POST['goto']);
exit();
}
session_start();
if (isset($_SESSION['loggedIn'])) {
return databaseContainsAuthor($_SESSION['email'], $_SESSION['password']);
}
}
function databaseContainsAuthor($email, $password) {
include_once './db_functions.php';
$db = new DB_Functions();
$result = $db->accountExists($email, $password);
return $result;
}
?>
Any help would be greatly appreciated!
UPDATE:
Error logs are showing multiple occurances of this error:
PHP Notice: A session had already been started - ignoring session_start() in /home3/monitot5/public_html/app/access.php on line 17
Access.php line 17:
if (databaseContainsAuthor($email, $password)) {
session_start(); //LINE 17
$_SESSION['loggedIn'] = TRUE;
What you should do is to use
session_start();
at the beginning of access.php file and don't use this function any more.
You should also completely change login of your access.php file. The first thing you should always do in this file is checking if there's a valid session for this user. Now you check it at the end of file and probably earlier you clear it because you unset session if there are no $_POST data.
In addition you shouldn't also use password in your session. It's rather very insecure. You should simple store login for your system when user filled in form valid username/email and password and unset it if user has logged out.
Sorry, but I won't write the whole code for you. You should simple look at some examples of code in Google to check how to handle user login/logout in PHP.

PHP - Checking if the user is logged on

I am quite new at PHP, so I hope there are some that can help.
I have a login page which works fine.
My problem is if you know the url, you can still access the subpages.
This is what it says on my login page
<body>
<?php
if(#!empty($_SESSION['acesses'])) {
echo '<script language="JavaScript">{ location.href="subpage.php"; self.focus(); }</script>';
}
?>
<div id="loginWrapper">
<div id="login">
<form name="loginform" action="<?php $_SERVER['REQUEST_URI']; ?>" method="post" autocomplete="on">
<fieldset id="input">
<h1>Log Ind</h1>
<?php
if(isset($_POST['submit'])) {
echo '<div class="errorBox">';
$username = mysqli_escape_string($conn,$_POST['username']);
$password = mysqli_escape_string($conn,$_POST['password']);
if(!empty($username) && !empty($password)) {
$query = mysqli_query($conn,"SELECT * FROM member WHERE username='$username' LIMIT 1");
$result = mysqli_fetch_array($query);
if($result['username'] == $username && $result['password'] == $password) {
//Sesstion Information
$_SESSION['acesses'] = $result['id'];
echo '<script language="JavaScript">{ location.href="subpage.php"; self.focus(); }</script>';
}else {
echo 'Brugernavnet eller Adganskoden stemmer ikke overens.';
}
}
echo '</div>';
}
?>
<label for="username"> Dit Brugernavn</label>
<input name="username" id="user" type="text" placeholder="Brugernavn">
<label for="password"> Dit password </label>
<input name="password" id="pass" type="password" placeholder="Password">
<input name="submit" type="submit" value="Log ind" />
</fieldset>
</form>
..........
This is what it says at the top of my subpage
<?php
session_start();
if(!empty($_SESSION['acesses'])) {
echo '<script language="JavaScript">{ location.href="login.php"; self.focus(); }</script>';
}
?>
<!doctype html>
<html lang="en">
<head>
You could do redirect the user, if they are not logged in, and vice-versa.
if (!empty($_SESSION['acesses'])){
header("Location: yourpage.php"); // or whatever page you like
exit();
}
else{
// your code for when user is logged in
}
Don't use JavaScript to redirect, especially when dealing with sessions. A user can simply turn off JavaScript in their browser and the redirect won't work anymore.
First of all, your subpage redirects away if the user isn't logged in. Second of all, instead of a javascript redirect, use an HTTP one:
<?php
session_start();
if(!isset($_SESSION['acesses']) || empty($_SESSION['acesses'])) {
Header("Location: index.php");
}
?>
You can use the following logic in the page(s) you wish to protect:
if(isset($_SESSION['acesses']) && !empty($_SESSION['acesses'])){
// give access
}
else{
// don't give access
}
and do the same for all your pages.
Sidenote: The code you posted for your login page doesn't contain session_start(); - If it's not in your working code, include it. It must be inside all pages using sessions.
<body>
<?php
session_start();
if(#!empty($_SESSION['acesses'])) {
echo '<script language="JavaScript">{ location.href="subpage.php"; self.focus(); }</script>';
}
?>
You should also consider embedding <noscript>Please enable Javascript</noscript> into your code and redirect the user if it isn't enabled.
Important sidenote: I noticed you are storing passwords in plain text. This is highly discouraged.
If your PHP version is 5.5, you can use the password_hash() function, or crypt() or bcrypt()
Here are a few resources you can look into:
http://en.wikipedia.org/wiki/Bcrypt
http://codahale.com/how-to-safely-store-a-password/
http://www.php.net/manual/en/function.crypt.php
http://www.php.net/manual/en/function.password-hash.php
About using Javascript:
If you absolutely want to use JS in your code, you can use the following logic:
<?php
echo "<div id=\"hide\">This line is hidden in PHP and will appear once JS is enabled.</div>";
// you can include your JS anywhere in here and will execute once the user enables JS.
?>
<body>
<div class="hide_class">This is hidden using a CSS class and will appear once JS is enabled.</div>
<noscript>
Please enable Javascript to view the content of this page, thank you.
<style>
#hide {
display:none;
}
.hide_class {
display:none;
}
</style>
</noscript>
</body>
First of all, you should use PHP-PDO in order to prevent SQL Injection attacks.
Also your code is wrong at subpage. You should check out variable acesses like following example.
if(!isset($_SESSION['acesses']) or empty($_SESSION['acesses'])) {
echo '<script language="JavaScript">{ location.href="login.php"; self.focus(); }</script>';
}

php log in form with messages and date and time

I am trying to create a php log in form. I want to just make a few adjustments but when i've tinkered with it, it stops working...
If you can't see from the code, I'm trying to create a (mock) log in form that asks for a username and password.
I want any blank textbox to show a red message to the right of the textbox. (i have the red error message, but I can't get it to the left of the box)
I want a sticky form that keeps either field if its filled in (again, I think I have this set up but don't think its working all the way)
I would like a person who enters the username: user and the password: abc123 to see a welcome message. If you don't use that username/password combo I want a message that says that they are not authorized. (This is what i really don't know how to do)
I want this all in a redux (also think i have that working but not 100% sure)
Any help would be greatly apprecaited!!
And here is my code:
<?php
define('TITLE', 'LOG IN');
// CSS
print '<style type="text/css" media="screen">
.error { color: red; }
</style>';
// Checking
if ( isset($_POST['submitted']) ) {
$problem = FALSE;
// Each value
if (empty($_POST['email'])) {
$problem = TRUE;
print '<p class="error">Please enter the username!</p>';
}
if (empty($_POST['password1'])) {
$problem = TRUE;
print '<p class="error">Please enter the password!</p>';
}
if (!$problem) { //No problem
// Printing the log in message
print '<p>Thank you for logging in!</p>';
$_POST = array();
} else {
print '<p class="error">No entry!</p>';
}
}
?>
<form action="login.php" method="post">
<p>"Username": <input type="text" name="username" size="20" value="<?php if (isset($_POST['username'])) { print htmlspecialchars($_POST['username']); } ?>" /></p>
<p>Password: <input type="password" name="password1" size="20" /></p>
<p><input type="submit" name="submit" value="Log in" /></p>
<input type="hidden" name="submitted" value="true" />
</form>
Ok, here is a simple login that is not meant for real world usage. Please read the comments included in the code to see what I have to say about each. Doing logins is quite tricky for a number of reasons, so this example is not meant to demonstrate a real world working codebase, but a very simple username/password check.
The security issues associated with a more sophisticated use are perhaps beyond this answer, but the below code is the way I would interpret what you have posted above, without getting to detailed (to the point of possibly making it hard to understand the simplest steps occurring).
Let me know if you have any questions. To see the form in action, check:
http://jfcoder.com/test/simplelogin.php
Also, I use PHP's HEREDOC syntax instead of quoted strings for simplicity. To read more about this sometimes handy form, see
http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc.
<html>
<head>
<style type="text/css">
.error {
color: red;
}
</style>
</head>
<body>
<?php
// Note, in most cases you will set a SESSION variable
// of $_SESSION['loggedin'], which would require you to
// use session_start() before you access any session
// variables.
// Note, this defaults to false.
$loggedin = false;
// If I get an error, I will put it in this variable.
$error = '';
// If the username is provided, run the code. Otherwise,
// act as if the login form was not submitted. This makes
// a hidden `submitted` value superfluous, and guarantees
// your users at least provide a username.
if ($_POST['username']) {
// NOTE!!! In mose cases, you're querying a database
// for a username/password match. In PHP, this often
// means a MySQL query. DO NOT USE THE BELOW IF YOU
// ARE DOING SO!!! This will allow what's called a
// SQL injection. You MUST wash your data with something
// like mysql_real_escape_string() for the $_POST
// values (NEVER trust submitted data, always validate
// and escape as necessary), or use the PHP PDO library.
// In this example, though, I use a switch to check the
// values for exact matches, which means I do not need
// to escape (and mysql_real_escape_string() requires
// a database connection to use).
$username = $_POST['username'];
$password = $_POST['password'];
// Here, I check if the username and password match.
// This is, of course, hardcoded, but to match your
// attempt, I chose to keep the form, although you
// rarely see this in use in the real world.
switch ($username) {
// My one case. For each additional user, you
// would need to add a new entry with password
// check. And I set my error text according to
// the result of the code.
case 'user':
if ($password === 'abc123') {
$loggedin = true;
} else {
$error = 'Username/Password did not match.';
}
break;
default:
// Note, I don't give a descriptive error
// here. If someone reports this error, I
// know what may have gone wrong, but the
// user is not told the username does not
// exist.
$error = 'Unknown error. Try again.';
}
}
// I will only show the welcome message if the user has
// successfully logged in.
if ($loggedin === true) {
echo <<<HTML
<h1>Welcome!</h1>
<p>Thank you for logging in $username</p>
HTML;
} else {
// If an error text is set, display that error.
if ($error != '') {
$error = "<h4>Login error</h4><p class='error'>$error</p>";
}
// Here's my form, only shown if the user has not
// successfully logged in (note, this is only a one-
// time check when the POST data is submitted; I
// would need to use sessions to "remember" the requestor
// had logged in across page accesses.
echo <<<FORM
<h1>Login Form</h1>
<form action="simplelogin.php" method="POST">
$error
<p><label>Username: <input type="text" name="username"/></label></p>
<p><label>Password: <input type="password" name="password"/></label></p>
<p><input type="submit" value="Login"/> <input type="reset"/></p>
</form>
FORM;
}
?>
</body>
</html>
Here's my full code. I pretty much rewrote the whole thing, so I appologize if the coding style differs too much:
<?php
// Output our CSS code
echo '<style type="text/css" media="screen">
.error
{
color: red;
}
</style>';
// Define our variable
$problem = false;
// Check if the form has been submitted
if (isset($_POST['submitted']))
{
// If either user or password are empty, we have a problem
if (empty($_POST['username']) || empty($_POST['password']))
{
$problem = TRUE;
}
// If there is no problem, username is user, and password is abc123, we're good
if (!$problem && $_POST['username']=='user' && $_POST['password']=='abc123') {
// Print our login message
echo 'Thank you for logging in!<br />';
}
// Ok, there's either a problem or the username or password is wrong, so no entry for them
else
{
echo '<p class="error">No entry!</p>';
}
}
?>
<form action="login.php" method="post">
Username: <input type="text" name="username" size="20" value="<?php
if (isset($_POST['submitted']) && !empty($_POST['username']))
{
echo $_POST['username'];
} ?>" />
<?php
if (isset($_POST['submitted']) && empty($_POST['username']))
{
echo '<span class="error">Please enter a username!</span>';
}
?>
<br />Password: <input type="password" name="password" size="20" value="<?php
if (isset($_POST['submitted']) && !empty($_POST['password']))
{
echo $_POST['password'];
} ?>" />
<?php
if (isset($_POST['submitted']) && empty($_POST['password']))
{
echo '<span class="error">Please enter the password!</span>';
}
?>
<br /><input type="submit" value="Log in" />
<br /><input type="hidden" name="submitted" value="true" />
</form>

Categories