Programming Tutorial #6: Login (Signup / Login in PHP Finale)

in #utopian-io7 years ago (edited)

What Will I Learn?

  • You will learn how to validate login details.
  • How to create a basic login system
  • How to use PHP

Requirements

  • WAMP / XAMPP / LAMP
  • Notepad++ or PHPStorm
  • Previous Tutorial Code

Difficulty

  • Basic

Tutorial Contents

Now that we have registration sorted, we need to be able to let them sign in with their new credentials!

Here is the HTML form you will need, name it login.php:

Start Tags

<!DOCTYPE HTML>
<html>
<head>

Set the URL bar title, import the scripts we need and the styles too.

<script src="/scripts/jquery-3.1.1.min.js"></script>
<script src="/scripts/script.js"></script>
<title>Login</title>
<link rel="stylesheet" href="/styles/w3.css">
<link rel="stylesheet" href="/styles/style.css">

close the head section

</head>

Open the body

<body>

Grey out the background

<div class="darkClass w3-animate-top" id="loginoverlay" width="100%" height="100%">

Submit to the login submit file we will create next, along with the ?r= variable, allowing us to tell it what page to go to, like to come back to this file ?r=login.php

<form action="sublogin.php<?php if (isset($_GET['r'])) { echo "?r=" . $_GET['r']; }?>" class="w3-panel w3-white w3-container w3-round-large w3-animate-top" style="width: 400px; margin: auto; " id="loginform" method="post">

Add Two Line Breaks for spacing

<br><br>

Box to accept either email or username under the variable $_POST['loginas'] in the submit login file.
Centered, orange 2px tall solid bottom border, flies in from top of page, is an input

<input type="text" style="margin: auto;border-bottom-color: orange;border-bottom-style: solid;border-bottom-width: 2px;" class="w3-animate-top w3-input" required name="loginas"/>
<h4 style="text-align: center;" class="w3-label w3-validate w3-animate-top">* Username/Email:</h4>

Accept the password from the user as $_POST['password'], same style as above, but with a password mask

<input type="password" style="margin: auto;border-bottom-color: orange;border-bottom-style: solid;border-bottom-width: 2px;" class="w3-animate-top w3-input" required name="password"/>
<h4 style="text-align: center;" class="w3-label w3-validate w3-animate-top">* Password:</h4>

Show the captcha box, replace "Your Sitekey" with your recaptcha sitekey in quotes

<div class="g-recaptcha" data-sitekey="Your Sitekey"></div>
<script src='https://www.google.com/recaptcha/api.js'></script>

Blue button, large and padded, flies in from the top. Allows user to sign into our service:

<input type="Submit" class="w3-btn w3-round-large w3-blue w3-medium w3-padding-large w3-animate-top" style="margin: auto; display:block;" value="Login!">

Close all the constructs

</form>
</div>
</body>
</html>

Next, create sublogin.php, the file which will validate the login, and if it is invalid, display an error.

Firstly, add the same form as above, but make it hidden, so that we can't see it unless we fail to login.
Again, make sure to replace "Your sitekey" with your captcha sitekey in quotes.
Also, as the first line, we have to start/continue a session, as it has to be done before ANYTHING else!

<?php session_start(); ?>
<!DOCTYPE HTML>
<html>
<head>
<script src="/Auth/scripts/jquery-3.1.1.min.js"></script>
<script src="/Auth/scripts/script.js"></script>
<title>Login</title>
<link rel="stylesheet" href="/Auth/styles/w3.css">
<link rel="stylesheet" href="/Auth/styles/style.css">

</head>

<body>
<h1>You Have Successfully Logged In!</h1>
<div class="darkClass w3-animate-top" id="loginoverlay" style="display:none;" width="100%" height="100%">
<div class="w3-container w3-red">
  <h3 id="login_issue_heading">Generic Error While Logging In.</h3>
  <p id="login_issue_content">Try Again?</p>
</div> <div id="loginclose"></div>
<form action="sublogin.php<?php if (isset($_GET['r'])) { echo "?r=" . $_GET['r']; }?>" class="w3-panel w3-white w3-container w3-round-large w3-animate-top" style="width: 400px; margin: auto; display:none;" id="loginform" method="post">
<input type="text" style="margin: auto;border-bottom-color: orange;border-bottom-style: solid;border-bottom-width: 2px;" class="w3-animate-top w3-input" required name="loginas"/>
<h4 style="text-align: center;" class="w3-label w3-validate w3-animate-top">* Username/Email:</h4>
<input type="password" style="margin: auto;border-bottom-color: orange;border-bottom-style: solid;border-bottom-width: 2px;" class="w3-animate-top w3-input" required name="password"/>
<h4 style="text-align: center;" class="w3-label w3-validate w3-animate-top">* Password:</h4>
<div class="g-recaptcha" data-sitekey="Your Sitekey"></div>
<script src='https://www.google.com/recaptcha/api.js'></script>
<input type="Submit" class="w3-btn w3-round-large w3-blue w3-medium w3-padding-large w3-animate-top" style="margin: auto; display:block;" value="Login!">
<h5 style="text-align: center;">No Account? <a href="/register/">Register</a></h5><h5 style="text-align: center;"><a href="/">Go Home!</a></h5>

Now we start the validation, YAY!

Open the PHP tag and include two of our validation files, as well as telling it that the login is currently unsuccessful. We start the session so we can store the credentials on success.
Sessions can't be modified by the browser, so you can rely on the information placed in them.
Things can be stored in the session using $_SESSION['var'] = "value";

<?php

$uccessful_login = False;

include 'scripts/DatabaseConnect.php';
include 'scripts/passwordHandler.php';

Reset these so the script can choose for itself which it is.

$isUsername = false;
$isEmail = false;

Require the custom captcha handler

require_once 'scripts/captchalib.php';

Replace "Your reCaptcha secret key" with your actual reCaptcha secret key, surrounded by quotes, as always, because it is a string.

$secret = "Your Recaptcha Secret Key";
$response = null;
$reCaptcha = new ReCaptcha($secret);

Check that we got a captcha response, and if so, check if it is valid

if (isset($_POST["g-recaptcha-response"])) {
if (strlen($_POST["g-recaptcha-response"]) > 0 and $_POST["g-recaptcha-response"] != null) {
    $response = $reCaptcha->verifyResponse(
        $_SERVER["REMOTE_ADDR"],
        $_POST["g-recaptcha-response"]
);};

Use the check to see that it is(n't) valid and make sure that they have provided a loginas and a password

if ($response != null && $response->success) {
if (isset($_POST['loginas']) and isset($_POST['password'])) {

Check whether it exists as a username or password, and if not, display the corresponding error message (as well as the captcha response)

if (usernameExists(strtolower($_POST['loginas']))) {
    $isUsername = True;
} else if (emailExists(strtolower($_POST['loginas']))) {
    $isEmail = True;
} else {
    echo '<script>LerrorHead("Wrong Login / Password");LerrorContent("The credentials you have supplied are invalid!");</script>';
};} else { 
    echo '<script>LerrorHead("Sorry, You Haven\'t Entered The Username/Password");LerrorContent("The Username and password are not set.");</script>';
};} else {
    echo '<script>LerrorHead("Invalid Captcha!");LerrorContent("The Captcha Response Was Incorrect / Not Filled");</script>';
};

New if statement that only runs if it is either a email or password:

if ($isEmail or $isUsername) {

Get the information associated with the account from the database using databaseconnect.php, splitvar converts it to a one record array.

if ($isEmail) {
        $accountArray = splitVar(getrelatedinfoe(strtolower($_POST['loginas'])));
    }
    if ($isUsername) {
        $accountArray = splitVar(getrelatedinfo(strtolower($_POST['loginas'])));
    }

Verify login and password one last time, just to be safe

if (strtolower($_POST['loginas']) == $accountArray[1] or strtolower($_POST['loginas']) == $accountArray[2]) {
        if(password_verify($_POST['password'],$accountArray[0])) {

Set The session variables so we can tell whether they are logged in

        $_SESSION['user'] = $accountArray[2];
        $_SESSION['email'] = $accountArray[1];
        $uccessful_login = True

if the ?r redirect variable is set, send them to that page, if not, send them to the homepage:
Also, echo's the error of a bad password if it is invalid, we don't say whether it is username or password, for security reasons.

if (isset($_GET['r'])) {
            $r = $_GET['r'];
            $config = include 'scripts/config.php';
            $goto = '<meta http-equiv="refresh" content="0; url=http://' . $config->domain . "/" . $r . '" />';
            echo $goto;
            echo "<p><a href='http://$config->domain/$r'>Redirect</a></p>";
        } else {
            $config = include 'scripts/config.php';
            $goto = '<meta http-equiv="refresh" content="0; url=http://' . $config->domain . '" />';
            echo $goto;
            echo "<p><a href='http://$config->domain'>Redirect</a></p>";
        }
        } else {
            echo '<script>LerrorHead("Wrong Login / Password");LerrorContent("The credentials you have supplied are invalid!");</script>';
        }

Close all the tags, and show the login form if it is unsuccessful:

    };
}; };
?>
<?php if (!$uccessful_login) {echo '<script>showlogin();</script>';} ?>
</form>
</div></div>
</body>
</html>

Handling logouts, checking if logged in, and knowing their username.

In ANY FILE using the logins, the first line OF THE FILE MUST be

<?php session_start(); ?>

To check whether someone is logged in, use (along with the line above):

<?php

if (isset($_SESSION['user'])) {
    //logged in
} else {
    //logged out
}

?>

To check whether someone is logged in, and if so, who they are, after starting a session, use:

if (isset($_SESSION['user'])) {
    echo 'logged in as ' . $_SESSION['user']; //just use $_SESSION['user'] where you want to know their name.
} else {
    echo 'you are not logged in';
}

?>

You don't need to store their password, because only the server can modify the $_SESSION variables, so by setting the username and email, you can be sure it is them.

Logout:
session_unset(); destroys all of the $_SESSION variables, and session_regenerate_id(true); deletes the current session and creates a new one, alternatively, use session_destroy(); where you don't need to use the $_SESSION variables until the next page refresh where session_start(); is run.

session_unset();
session_regenerate_id(true);

Thanks for reading, this is the last tutorial in the series, so, see you next week with a new tutorial!

This lesson's code is on github

Curriculum



Posted on Utopian.io - Rewarding Open Source Contributors

Sort:  

Good stuff!!! I gotta start learning hehe

Yeah, I wish you the best of luck! Have a nice day & keep steeming on!

Hey @cadawg I am @utopian-io. I have just upvoted you!

Achievements

  • You have less than 500 followers. Just gave you a gift to help you succeed!
  • Seems like you contribute quite often. AMAZING!

Suggestions

  • Contribute more often to get higher and higher rewards. I wish to see you often!
  • Work on your followers to increase the votes/rewards. I follow what humans do and my vote is mainly based on that. Good luck!

Get Noticed!

  • Did you know project owners can manually vote with their own voting power or by voting power delegated to their projects? Ask the project owner to review your contributions!

Community-Driven Witness!

I am the first and only Steem Community-Driven Witness. Participate on Discord. Lets GROW TOGETHER!

mooncryption-utopian-witness-gif

Up-vote this comment to grow my power and help Open Source contributions like this one. Want to chat? Join me on Discord https://discord.gg/Pc8HG9x

This post has received a 1.57% UpGoat from @shares. Send at least 0.1 SBD to @shares with a post link in the memo field.

Invest your Steem Power and help minnow at the same time to support our daily curation initiative. Delegate Steem Power (SP) to @shares by clicking one of the following links: 1000 SP, 5000 SP or more. Join us at https://steemchat.com/ discord chat.

Support my owner. Please vote @Yehey as Witness - simply click and vote.

Thank you for the contribution. It has been approved.

You can contact us on Discord.
[utopian-moderator]

Thanks! Much appreciated!

As a follower of @followforupvotes this post has been randomly selected and upvoted! Enjoy your upvote and have a great day!

Congratulations @cadawg! You have completed some achievement on Steemit and have been rewarded with new badge(s) :

Award for the number of upvotes received

Click on any badge to view your own Board of Honor on SteemitBoard.
For more information about SteemitBoard, click here

If you no longer want to receive notifications, reply to this comment with the word STOP

By upvoting this notification, you can help all Steemit users. Learn how here!

Sneaky Ninja Attack! You have been defended with a 1.31% vote... I was summoned by @cadawg! I have done their bidding and now I will vanish...Whoosh

You got a 7.14% upvote from @bearwards courtesy of @cadawg!

You got a 50.00% upvote as a Recovery Shot from @isotonic, currently working as a funding tool, courtesy of @cadawg!

  • Image from pngtree.com

@isotonic is the Bid Bot of the @runningproject community.
Earnings obtained by this bot, after paying to the delegators, are fully used to increase the SP of the @runningproject from which all affiliated members are benefited.
Check @runningproject posts in order to know further about.

This post has received a 0.20% upvote from thanks to: @cadawg.
For more information, click here!!!!
Send minimum 0.050 SBD|STEEM to bid for votes.


Do you know, you can also earn daily passive income simply by delegating your Steem Power to @minnowhelper by clicking following links: 10SP, 100SP, 500SP, 1000SP or Another amount

Coin Marketplace

STEEM 0.19
TRX 0.15
JST 0.029
BTC 63126.02
ETH 2553.49
USDT 1.00
SBD 2.78