0

Hello, I've been stumped by the PHP code I've written. I've stared at this for hours with no success, please help find any errors I've apparently gone over.

What I want this script to do is from a html form page, to query a database table ('users') to make sure their password and username are correct, then in a separate table ('tokens') insert a random token (the method I used before, it works) into the 'tk' column, and the users general auth. code pulled from the 'users' table into the 'gauth' colum, in the 'tokens' table.

The reason for the additional general auth is so I can pull their username and display it on all the pages I plan on "securing"

Sorry if I'm confusing, this is the best I can refine it. Also, I'm not that good at formatting :). I'm going to add some html later, that's why the tags are there.

MySQL Tables:

Users Example:

cols:        username  | password  |    email              | classcode | tcode   | genralauth |
             hello     | world     | hello.world@gmail.com | 374568536 | somthin | 8945784953 |

Tokens Example:

cols:          gauth   |      tk      |
            3946893485 |wr8ugj5ne24utb|

PHP:

<html>
<?php
session_start();
error_reporting(0);
$servername = "localhost";
$username = "-------";
$password = "-------";
$db = "vws";
?>
<?php
// Create connection
$conn = new mysqli($servername, $username, $password, $db);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} 
?>
<?php
$sql1 = "SELECT username FROM users";
$data1 = $conn->query($sql1);

if ($conn->query($sql1) === TRUE) {
    echo "";
}
?>
<?php
$sql2 = "SELECT password FROM 'users'";
$data2 = $conn->query($sql2);

if ($conn->query($sql2) === TRUE) {
    echo "";
}
?>
<?php
$bytes = openssl_random_pseudo_bytes(3);
$hex = bin2hex($bytes);
?>
<?php
if($_POST['pss'] == $data2 and $_POST['uname'] == $data1) {
    $correct = TRUE;
}
else {
    $correct = FALSE;
}
?>
<?php
    if ($correct === TRUE) {
        $sql3 = "SELECT generalauth FROM users WHERE password='".$_POST['pss']."'";
        $result3 = $conn->query($sql3);
    }
?>
<?php
    if ($correct === TRUE) {
        $sql4 = "INSERT INTO tokens (tk,gauth) VALUES (".$hex."' ,       '".$result3."')";

        if ($conn->query($sql4) === TRUE) {
            echo "New token genrated.";
        } else {
            echo "Error: " . $conn->error;
        }
    }
?>
<?php
    if ($correct === TRUE) { ?>
    <p>Succesfuly loged in!</p><br/>
    <a href="../index.php<?php echo " ?view=teacher";?>"><button>Continue</button></a><br/>
<?php
}
elseif ($correct === FALSE) { ?>
    <p>Incorrect, please try again.</p><br/>
    <a href="../login.php"><button>Back</button></a><br/>
<?php
}
?>
<?php
if ($correct === TRUE) {
$_SESSION['auth'] = $hex;
$_SESSION['logstat'] = TRUE;
}
?>
<?php
if ($correct === FALSE) {
$_SESSION['logstat'] = FALSE;   
}
$conn->close();
?>

This is the PHP I'm going to use on most pages for token auth, howver it dosn't actually check the database 'tokens', also I need a way to display signed in users username using the general auth.

PHP:

<html>
<h1 class="title">Virtual Work Sheets!</h1> 
<a href="login.php"><p class="h_option">[Log In / Register]</p></a><hr/>
<div class="body">
<?php
session_start();
error_reporting(0);
$servername = "localhost";
$username = "root20";
$password = "jjewett38";
$db = "vws";
?>
<?php
// Create connection
$conn = new mysqli($servername, $username, $password, $db);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} 
?>
<?php
$sql = "SELECT tk FROM tokens";
$data = $conn->query($sql);

?>
<?php
if (!$_GET['tk'] == $data) {
    echo "
    <p>Invalid token, please consider re-logging.</p>
    ";
}
else {
?>
<?php
switch ($_GET['view']) {
    case teacher:
?>

Teacher page html here...

<?php 
    break;
    case student:
?>

Student page html here...

<?php
    break;
    default:
        echo "Please login to view this page.";
}
}?>
</html>
cssyphus
  • 31,599
  • 16
  • 79
  • 97
Jacob Jewett
  • 187
  • 2
  • 2
  • 15

1 Answers1

2

I suggest that you change your approach.

Although at first glance these example files looks like a lot, once you study them you'll see it's really much more simple and logical approach than the direction you are now headed.

First, move the db connect / login stuff into a separate file, and require or include that file at top of each PHP page:

INIT.PHP

    // Create connection
    $conn = new mysqli($servername, $username, $password, $db);

    // Check connection
    if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
    } 

    //Might as well also load your functions page here, so they are always available
    require_once('fn/functions.php');
?>

Now, see how we use it on the Index (and Restricted) pages?

INDEX.PHP

<?php
    require_once('inc/head.inc.php');
    require_once('fn/init.php');
?>

<body>
    <!-- Examples need jQuery, so load that... -->
    <script src="https://code.jquery.com/jquery-1.11.3.js"></script>
    <!-- and our own file we will create next... -->
    <script type="text/javascript" src="js/index.js"></script>

    <div id="pageWrap">
        <div id="loginDIV">
            LoginID: <input type="text" id="liID" /><br>
            LoginPW: <input type="password" id="liPW" /><br>
            <input type="button" id="myButt" value="Login" />
        </div>
    </div>

JS/INDEX.JS

$(function(){
    $('#myButt').click(function(){
        var id = $('#liID').val();
        var pw = $('#liPW').val();
        $.ajax({
            type: 'post',
             url: 'ajax/login.php',
            data: 'id=' +id+ '&pw=' +pw,
            success: function(d){
                if (d.length) alert(d);
                if (d==1) {
                    window.location.href = 'restricted_page.php';
                }else{
                    $('#liID').val('');
                    $('#liPW').val('');
                    alert('Please try logging in again');
                }
        }
        });
    });//END myButt.click

}); //END document.ready

AJAX/LOGIN.PHP

<?php
    $id = $_POST['id'];
    $pw = $_POST['pw'];

    //Verify from database that ID and PW are okay
    //Note that you also should sanitize the data received from user

    if ( id and password authenticate ){
        //Use database lookups ot get this data: $un = `username` 

        //Use PHP sessions to set global variable values
        $_SESSION['username'] = $un;
        echo 1;
    }else{
        echo 'FAIL';
    }

RESTRICTED_PAGE.PHP

<?php
    if (!isset($_SESSION['username']) ){
        header('Location: ' .'index.php');
    }

    require_once('inc/head.inc.php');
    require_once('fn/init.php');
?>
<body>
    <h1>Welcome to the Admin Page, <?php echo $_SESSION['username']; ?>
    <!--  AND here go all teh restricted things you need a login to do. -->

More about AJAX - study the simple examples

Community
  • 1
  • 1
cssyphus
  • 31,599
  • 16
  • 79
  • 97
  • Thanks! I'll have to look at this in detail later, however I don't know javascript (and its really confusing to me), and that may be a problem in the future as I add more functions to the pages. I kinda figured my answers lay within javascript :). I usually don't ask, but would skype be an option? – Jacob Jewett Jan 12 '16 at 04:38
  • I already know php, and am currently learning AJAX from your link, but I'm not up to spend money into coding, when there's W3 schools reference. Thanks tho. – Jacob Jewett Jan 14 '16 at 01:28