PHP Password Protect page - redirect - php

I am using the PHP password protection snippet from http://www.fullypixel.com/page/tutorials.html/_/fully-pixel-forum-faq/simple-php-password-protection-for-a-single-page-r27 which looks like....
<?php
if (!isset($_POST['txtAccCode']))
{
//If not isset -> set with dummy value
$_POST['txtAccCode'] = "undefine";
}
// Define your user array
$access_codeArray = array("john","paul","george","ringo","b4dh39gsv55x");
$access_code = $_POST['txtAccCode'];
$result = in_array($access_code, $access_codeArray);
if ($_POST['txtAccCode'] != $result) {
?>
<style type="text/css">
#login {margin:0 auto; width:500px;}
.login {font-family:"Verdana", sans-serif;border:2px solid #3753f5;}
.login p {font-size:13.0px;}
.login p {padding-left:10px;}
h2.login {padding:10px;}
</style>
<div id="login">
<h2 class="login">Enter Access Code to view content</h2>
<form class="login" name="form" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<p><label for="txtAccCode">Enter Access Code:</label>
<br /><input type="text" title="Enter Access Code" name="txtAccCode" /></p>
<p><input type="submit" name="Submit" value="Login" /></p>
</form>
</div>
<?php
echo '<script> alert ("Please enter a valid access code to continue.");; </script>';
} else { ?>
Everything works great but I am now trying to modify it so that it redirects when the correct password is input rather than display hidden content.
Is this something I should be doing in PHP or will I need to use javascript to do this?

In the end of your example, you have else, so:
// ...
} else {
header('Location: http://google.com');
exit;
}

Once the user fulfills the conditions required to be logged, you should redirect:
if(empty($errors) && $_POST) #not erros, user validated then
{
exit(header('Location: logeed_user_landing.php));
}

Related

How to execute a function with an isset under an if statement in PHP

I am making a loan calculator and I want to run some calculations that are being posted from a form using the POST method. The code is not executing when I run it. Where am I am missing it?
I have run the code without the function and it seems to be working well, but the moment I put it in a function its not running.
function loancal()
{
if(isset($_POST['submit'])) {
$principal = $_POST['principal'];
$intrstRate = $_POST['intrest'];
$tenure = $_POST['tenure'];
$result = ($principal * $intrstRate * $tenure) ;
echo $result;
} else {
echo '00.00';
}
}
This is the line that is calling the function after it has been submitted:
<h1 class="title is-2"> $<?php loancal(); ?></h1>
I am expecting the out to change from $00.00 to for example a calculated result, but the output is still the same $00.00
This is the form (excerpt).
<form method="post" action="">
<input type="text" name="principal">
<input type="text" name="intrest">
<input type="date">
<input type="text" name="tenure">
<button type="submit">Calculate</button>
<button type="reset" >Clear</button>
</form>
So my very first answer is your issue, you need to give your submit button a name.
<button name="submit" class="button is-rounded is-primary" type="submit">Calculate</button>
Here's one way to get the code to execute:
<?php
function loancalc() {
$result = '0.00';
if( isset( $_POST['submit'] )){
// inspecting submitted values so that...
foreach ($_POST as $key => $value){
$bool[$key] = ctype_print( $value );
}
// ... if proven valid, then make assignments
if ( $bool['principal'] && $bool['interest'] && $bool['tenure'] ) {
// array destructuring available since PHP 7.1
[$principal, $interestRate,$tenure] =
[$_POST['principal'],
$_POST['interest'],
$_POST['tenure']];
$result = $principal * $interestRate * $tenure;
} // inner if
} // if POSTed
echo number_format( $result,2,'.',',' ); // default English representation
} // end func
?>
<html>
<head>
<title>Untitled</title>
<style>
#submit {
background: #000;
color: lime;
}
#clear {
background: #000;
color: cyan;
}
input {
background: #ffffee;
color: #303;
}
h1 {
font-size: 32pt;
margin-bottom: 3em;
color: #f0c;
}
</style>
</head>
<body>
<h1>$
<?php loancal(); ?>
</h1>
<form method="post" action="">
<input type="text" name="principal" id="principal">
<input type="text" name="intrest" id="intrest">
<input type="date">
<input type="text" name="tenure" id="principal">
<button type="submit" name="submit" id="submit">Calculate</button>
<button type="reset" id="clear">Clear</button>
</form>
</body>
</html>
The form values will only be properly submitted if they possess name attributes. Id attributes are optional and handy for front-end code manipulation.
Important point: Be sure to treat user submitted data as suspect, i.e. possibly tainted. In this example, a simple check makes sure that the the user input values only contain printable characters.
(Related demo of PHP code here.)
Refinements:
gave $result default value and eliminated an if-else clause
formatted the number with number_format() to make the number more user-friendly.
added some styling for fun :)

data in $_POST across multiple pages

I am new to PHP and I wrote scripts for simple login. When successfully login and click the link "back to login", I was not able to have the previous login username filled. I know using $_COOKIE['username'] for the value of username works, but I am wondering why $_POST['username'] does not work? Thank you!
login.php
<!DOCTYPE HTML>
<html>
<head></head>
<body>
<form action="./loginProcess.php" method="post">
Username: <input type="text" name="username" value="<?php echo isset($_POST['username']) ? htmlspecialchars($_POST['username']) : ''; ?>"><br>
Password: <input type="password" name="password"><br>
<input type="submit" name="send">
</form>
</body>
</html>
loginProcess.php
<?php
echo "welcome, ".$_POST['username'].", login success!!";
echo "<br/><a href='login.php'>Back to login</a><br>";
if(!empty($_COOKIE['lastVist'])){
echo "your last login time:".$_COOKIE['lastVist'];
setcookie("lastVist",date("Y-m-d H:i:s"),time()+24*3600*30);
}else{
echo "you first login time:";
}
setcookie("username", $_POST['username'], time()+24*3600*30);
?>
A session is a way to store information (in variables) to be used across multiple pages.
Unlike a cookie, the information is not stored on the users computer and unlike post as it has information for specific request sent by user.
When we use an application, we open it and do some changes, then we close it. This is much like a Session, so to preserve information we have per session global array in php $_SESSION.
A session is started with the session_start() function and values are stored in simply associative array fashion $_SESSION['key'] = $value;.
login.php
<?php
session_start();
?>
<!DOCTYPE HTML>
<html>
<head></head>
<body>
<form action="./loginProcess.php" method="post">
Username: <input type="text" name="username" value="<?php echo isset($_SESSION['username']) ? htmlspecialchars($_SESSION['username']) : ''; ?>"><br>
Password: <input type="password" name="password"><br>
<input type="submit" name="send">
</form>
</body>
</html>
loginProcess.php
<?php
session_start();
echo "welcome, ".$_POST['username'].", login success!!";
echo "<br/><a href='login.php'>Back to login</a><br>";
if(isset($_SESSION['lastVisit'])){
echo "your last login time:".$_SESSION['lastVisit'];
}else{
echo "you first login time:".$_SESSION['lastVisit'];
$_SESSION['lastVisit'] = date("Y-m-d H:i:s", time());
}
$_SESSION['username'] = $_POST['username'];
?>
In principle, in loginProcess.php, if you would have used, for example, a form with a hidden input containing the username value, then this value would have been readable in the login.php - after clicking the "back to login" anchor:
Welcome <?php echo $_POST['username']; ?>, login success!!
<br>
<form id="backToLoginForm" action="login.php" method="post">
<input type="hidden" name="username" value="<?php echo $_POST['username']; ?>" />
<a href="#" onclick="javascript:document.forms['backToLoginForm'].submit();">
Back to login
</a>
</form>
But you really shouldn't do what you want to do. E.g. to go back to the login.php without logging-out first - at least. If you would do it and complete other credentials - in the login.php - as the ones used for the first login, then you would still need to logout the previous user before validating the new credentials. This would be a bad management of active session, cookies, etc.
More of it, the autocomplete of login credentials is a job for the password managers, or of the form fillers, not of your own code - unless it's part of the validation process of the currently given login credentials (see the code example below).
So, as an alternative to your approach, my suggestion would be the following login.php code. No need for a loginProcess.php page anymore:
<?php
session_start();
// Operations upon form submission.
if (isset($_POST['submit'])) {
// Validate the username.
if (!isset($_POST['username']) || empty($_POST['username'])) {
$errors[] = 'Please provide the username.';
}/* Here other password validations using elseif statement. */
// Validate the password.
if (!isset($_POST['password']) || empty($_POST['password'])) {
$errors[] = 'Please provide the password.';
} /* Here other password validations using elseif statement. */
// Get the posted data.
$username = $_POST['username'];
$password = $_POST['password'];
if (!isset($errors)) {
/*
* Check the given credentials in the db. If the user doesn't exist, add an error:
*/
// $errors[] = 'Wrong credentials. Please try again.';
/*
* ... else add only the user id - fetched from db - to session.
* Don't add other user related details to session. If, in other pages,
* you want to use other user details, fetch them there using the user id.
*/
if (!isset($errors)) {
$_SESSION['userId'] = 43;
// Redirect to the welcome page.
header('Location: welcome.php');
exit();
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes" />
<meta charset="UTF-8" />
<!-- The above 3 meta tags must come first in the head -->
<title>Demo - Login</title>
<style type="text/css">
.form-control {
margin-bottom: 10px;
}
label {
display: inline-block;
min-width: 80px;
}
.messages {
margin-bottom: 20px;
}
.error {
color: #c00;
}
button {
padding: 5px 10px;
background-color: #8daf15;
color: #fff;
border: none;
}
</style>
</head>
<body>
<div class="messages">
<?php
if (isset($errors)) {
foreach ($errors as $error) {
?>
<div class="error">
<?php echo $error; ?>
</div>
<?php
}
}
?>
</div>
<form action="" method="post">
<div class="form-control">
<label for="username">Username:</label>
<input type="text" id="username" name="username" value="<?php echo isset($username) ? $username : ''; ?>">
</div>
<div class="form-control">
<label for="password">Password:</label>
<input type="password" id="password" name="password" value="<?php echo isset($password) ? $password : ''; ?>">
</div>
<button type="submit" id="submit" name="submit">
Login
</button>
</form>
</body>
</html>

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>';
}

Trying to redirect user to a link after login

All I want to do is redirect a user to my homepage a couple seconds after they log in. Here's my code
<?php
include_once("config.php");
?>
<?php if( !(isset( $_POST['login'] ) ) ) { ?>
<!DOCTYPE html>
<html>
<head>
<title>Codecall Tutorials - Secured Login with php5</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<header id="head" >
<p>Codecall tutorials User Login</p>
<p><span id="register">Register</span></p>
</header>
<div id="main-wrapper">
<div id="login-wrapper">
<form method="post" action="">
<ul>
<li>
<label for="usn">Username : </label>
<input type="text" maxlength="30" required autofocus name="username" />
</li>
<li>
<label for="passwd">Password : </label>
<input type="password" maxlength="30" required name="password" />
</li>
<li class="buttons">
<input type="submit" name="login" value="Log me in" />
<input type="button" name="register" value="Register" onclick="location.href='register.php'" />
</li>
</ul>
</form>
</div>
</div>
</body>
</html>
<?php
} else {
$usr = new Users;
$usr->storeFormValues( $_POST );
if( $usr->userLogin() ) {
echo "Welcome";
} else {
echo "Incorrect Username/Password";
}
}
?>
Also, it would be very nice to have a user page created after a user registers. I have the register code all set but this is something I would like to implement. Any ideas?
This this code snippet:
header( 'Location: http://www.yoursite.com/new_page.html' );
Here is a reference link if you need it - http://php.net/manual/en/function.header.php
Try to add
header(); phpfunction to redirect your page into certain location you want.
if( $usr->userLogin() ) {
ob_start(); // use output buffering to avoid "header already sent error"
echo "Welcome"; //should try to remove this if you want because its unecessary now since your redirecting your page
header('Location: pagetoredirect');
ob_end_flush(); //now the headers are sent
} else {
echo "Incorrect Username/Password";
}
Source(PHP.NET)
Here is how you do PHP redirects:
header('location:index.php');
You will need to clear your html first:
Make your top part codes into:
<?php
include_once("config.php");
if( !(isset( $_POST['login'] ) ) ) { ?>
Add header where you want to redirect:
if( $usr->userLogin() ) {
header('Location: /path/to/new/page.php');
} else {
echo "Incorrect Username/Password";
}
Another way is to use javascript:
if( $usr->userLogin() ) { ?>
<div class="message">
Thank you for logging in. You will be redirected in few seconds.
Click here if not redirected.
</div>
<script type="text/javascript">
window.location = "/path/to/new/page.php";
</script>
<?php
} else {
echo "Incorrect Username/Password";
}
you can redirect your page through header() like this
header("location:yoursite.com?$msg=welcome user");
and it is important to notice that header() must be called before any actual output is seen...

echo login error in different page, specific div

Delayed too long with this issue. I have a index.php including form and login.php handeling it.
How do I post the errors in a specific div in index.php?
Here is the Index.php container, no php code in idnex.php yet.
<div id="container">
<section>
<h1>ברוכים הבאים לאתר קופונים</h1>
<h2>המקום בו תוכלו למצוא קופונים בסביבתכם</h2>
<hr>
</section>
<section id="mainpage">
<p class="welcome">
אנא התחבר בכדי ליצור ולראות קופונים בקרבתך</br>
הירשם לאתר
</p>
<form action="php/login.php" method="post" class="form">
<p class="email">
<input type="text" name="email" /> :דואר אלקטרוני</br>
</p>
<p class="password">
<input type="password" name="password" /> :סיסמא</br>
</p>
<p class="submit">
<input type="submit" value="היכנס" />
</p>
</form>
</section>
</div>
and here is the login.php error reporting section
//check matching input
if($email == $dbemail && $password = $dbpassword){
$_SESSION['email'] = $dbemail;
include('../index.php');
header('members.php');
}
else{
include('../index.php');
echo "Incorrect Password<style text-align:center;/>";
}
}
} else
include('../index.php');
die('<p class="error">User does not exist</p>');
} else
include('../index.php');
die('Please enter a Email and password');
tried this
include('../index.php');
die('<p class="error">User does not exist</p>');
can't manage to specifically position it under the Submit button (using margin: 0 auto so left and right changes)
Thanks for any help given
change your login.php file:
} else {
// error happened
$error = '<p class="error">User does not exist</p>'
include('../index.php');
exit;
...
and your index.php file:
<form action="php/login.php" method="post" class="form">
<?php
if(isset($error)) echo $error;
?>
<p class="email">
<input type="text" name="email" /> :דואר אלקטרוני</br>
...
The problem is, is that your login.php file directly echo's the error message out. A better method would be to save the message into a variable - even a session variable would suffice (as it looks like you're not using OOP, by the example code).
Try updating the error messages to not use echo, but instead maybe:
$_SESSION['error_message'] = "Incorrect Password<style text-align:center;/>";
And then, in index.php, exactly where you want it to be displayed add:
<p class="submit">
<input type="submit" value="היכנס" />
</p>
</form>
<?php
if (isset($_SESSION['error_message'])) {
echo $_SESSION['error_message'];
unset($_SESSION['error_message']); // clear the message to prevent duplicate displays
}
?>
As it looks like you want to include the index.php file when the actual error occurs, you can set a local variable right before the call to include('../index.php'); inside login.php, like this:
} else {
$errMsg = "Incorrect Password<style text-align:center;/>";
include('../index.php');
}
And like the above example modified index.php, you can do the same here like:
</p>
</form>
<?php if ($errMsg) { echo $errMsg; } ?>

Categories