-1

I have created a login script that logs into an app, however when I log in with a players detail, it does not match the player that's already playing in the home page and play pages the player_id is set to 1, this is the the home page, where the player_id is set to 1 and also in the play.php page the player_id is set to 1.

I want to change it so that when I log in the player I use to login should match the player playing, I have three players. This is the home.php page below.

<?php
//include ("session.php");

session_start();
# check if player id is set in query string
if (!isset($_GET['player_id'])) {
    # it is not set, so make them player 1 by default
    $player_id = 1;

    /*  
    if (login_user = "sam"){
        $player_id = 1;
    }
    if (login_user = "ben"){
        $player_id = 2;
    }
    if (login_user = "jack"){
        $player_id = 1;
    }
    */
}
else {

    # set player_id based on GET parameter (imagining it was passed by some login script)
    $player_id = $_GET['player_id'];
}

# Define the SQL queries to run...

# This query will fetch the details about the player
$sql = "SELECT username, forename, surname FROM Player WHERE id=$player_id";

# Query the database
$result = mysqli_query($link, $sql);

# Get number of rows in result-set
$row_cnt = mysqli_num_rows($result);

# check if there are rows to display...
if ($row_cnt == 0) {
    # if not, output a suitable message
    $content .= "<p>Sorry, I don't know who you are...</p>";
} else {
    # Otherwise set a variable with their name
    while ($row = mysqli_fetch_assoc($result)) {
        $forename = $row['forename'];
        $username = $row['username'];
    }

    # free result set
    mysqli_free_result($result);

    # update content
    $content .= "<h1>Welcome to Hang Man $forename!</h1>";
    $content .= "<p>An exciting word game for 1 player.</p>";
    $content .= "<p>You are playing as <strong>$username</strong></p>";
    /*$content .="<<h2>welcome<"?php echo $login_session; ?></h2>*/
    /*$content .= "<h3>< a href = "logout.php">Sign out</a></h3>*/
}

$login_session=$_SESSION['login_user'];
$login_session;
?>
<html">   
   <head>
      <title>Welcome </title>
   </head>
   <body>
      <h2><a href = "logout.php">Sign Out</a></h2>
   </body>
</html>

Login page:

 <!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <table align="center" bgcolor="#CCCCCC" border="0" cellpadding="0"
    cellspacing="1" width="300">
        <tr>
            <td>
                <form method="post" name="">
                    <table bgcolor="#FFFFFF" border="0" cellpadding="3"
                    cellspacing="1" width="100%">
                        <tr>
                            <td align="center" colspan="3"><strong>User
                            Login</strong></td>
                        </tr>
                        <tr>
                            <td width="78">Username</td>
                            <td width="6">:</td>
                            <td width="294"><input id="username" name=
                            "username" type="text"></td>
                        </tr>
                        <tr>
                            <td>Forename</td>
                            <td>:</td>
                            <td><input id="forename" name="forename"         
                            "text"></td>
                        </tr>
                        <tr>
                            <td>&nbsp;</td>
                            <td>&nbsp;</td>
                            <td><input name="submit" type="submit" 
                            "Login"> <input name="reset" type="reset"  
                            "reset"></td>
                        </tr>
                    </table>
                </form>
            </td>
        </tr>
    </table>
 <?php
    if (isset($_POST['submit'])) {     
        include("db_connect1.php");

        require "includes/functions.php";
        session_start();

        $username=$_POST['username'];
        $forename=$_POST['forename'];
        $player_id = $_SESSION['player_id'];      
        $_SESSION['login_user']=$username; 
        $query = mysql_query("SELECT username FROM Player WHERE username='$username' and forename='$forename'");
        if (mysql_num_rows($query) != 0) {
            echo "<script language='javascript' type='text/javascript'> location.href='index.php' </script>";     
        }

        //if(mysql_num_rows($query) !=0){
            //echo ".$_GET["playerid"]."

        else {
            echo "<script type='text/javascript'>alert('User Name Or Password Invalid!')</script>";
        }
    }
?>
</body>
</html>
sam
  • 1
  • 2
  • 1
    Show us your HTML login form. `$_GET` seems odd for passing the user ID? Ideally you store it in a session once the user logs in and access it through `$_SESSION`. – Script47 Aug 07 '17 at 16:09
  • `$player_id = 1;` .... Well, that would probably explain why the player ID is being set to 1. – David Aug 07 '17 at 16:13
  • Please don't rollback an edit which removes the useless formatting tags at the bottom. – Script47 Aug 07 '17 at 16:16

1 Answers1

1

You have a lot of issues, some being:

  1. Use of a deprecated/removed library (mysql_*). Use a new database library.
  2. Mixing user input directly into your sql statements (sql injection prone). You have to bind parameters/values on those.
  3. (EDIT) I just noticed you are using both mysql libraries, you should not be mixing both the new version of mysqli_* and mysql_*, just use the mysqli_* or PDO as noted in my link above.
  4. You have a functions file (includes/functions.php) but you have no useful functions. You could make functions like getPlayer() or validateUserForename() or something that is containing your procedural scripts.

The main issue you are having, from what I can tell, is that you are not accounting for the $player_id being set when the $_GET is not present. It should probably be something like:

if (empty($_GET['player_id'])) {
    # it is not set, check if stored in session or not, default 1
    $player_id = (!empty($_SESSION['player_id']))? $_SESSION['player_id'] : 1;

One note when it comes to the view. It is better to try and reduce repetition when you are trying to output to the view (well, you should watch out for repetition in general, but I notice people output to the view in repetition the most). This is an example:

# Presuming row count is generated not using mysql_num_rows(),
# we'll assume it's set previously using a better database library
$js = ($rowCount != 0)? "location.href='index.php'" : "alert('User Name Or Password Invalid!')";
# Now you don't repeat the <script> tags portion.
echo "<script language='javascript' type='text/javascript'>{$js}</script>";

Finally, you have confusing logic like this part:

$_SESSION['player_id']=$username;
$_SESSION['player_id']=$forename;

Why set the player_id as the $username then reset it on the next line to the $forename?


EDIT #2

It sounds like you might be having some issues working this out, so I will show you an example of my points:

/config.php

<?php
# Create some useful constants
define('DS',DIRECTORY_SEPARATOR);
define('ROOT_DIR',__DIR__);
define('INCLUDES',ROOT_DIR.DS.'includes');
define('FUNCTIONS',INCLUDES.DS.'functions');
# Save you creds for easy changing
define('DB_HOST','localhost');
define('DB_NAME','database');
define('DB_USER','root');
define('DB_PASS','');
# Include database
include_once("db_connect.php");
# Add our function loader
include_once(FUNCTIONS.DS.'autoLoad.php');
# Start session by default
session_start();

/includes/functions/autoLoad.php

<?php
# This will try and load functions from our function folder when required
function autoLoad($func,$return = false)
    {
        if(function_exists($func))
            return ($return)? $func() : true;

        if(is_file($inc = FUNCTIONS.DS.$func.'.php')) {
            include_once($inc);
            return ($return)? $func() : true;
        }

        return false;
    }

/includes/functions/getPlayerId.php

<?php
# This will fetch the default player id
function getPlayerId()
    {
        return (!empty($_SESSION['player_id']))? $_SESSION['player_id'] : 1;
    }

/includes/functions/getPlayer.php

function getPlayer($con,$id)
    {
        if(!is_numeric($id))
            return array();

        # This query will fetch the details about the player
        $sql = "SELECT username, forename, surname FROM Player WHERE id = {$id} LIMIT 1";

        # Query the database
        $result = mysqli_query($con, $sql);

        # Get number of rows in result-set
        $row_cnt = mysqli_num_rows($result);

        # check if there are rows to display...
        if ($row_cnt == 0)
            return array();
        else {
            # Otherwise set a variable with their name
            while($row = mysqli_fetch_assoc($result)) {
                $new[] = $row;
            }
        }
        mysqli_free_result($result);
        return $new[0];
    }

/includes/functions/welcome_block.php

function welcome_block($firstname,$username)
    {
        ob_start() ?>
        <h1>Welcome to Hang Man <?php echo $firstname ?>!</h1>
        <p>An exciting word game for 1 player.</p>
        <p>You are playing as <strong><?php echo $username ?></strong></p>
        <?php
        $data = ob_get_contents();
        ob_end_clean();
        return $data;
    }

To use:

<?php
# Always include this page at the top of base pages
require_once(__DIR__.DIRECTORY_SEPARATOR.'config.php');
# check if player id is not set in query string
if (empty($_GET['player_id'])) {
    # Get our player function
    # Fetch the id from either the session or make it default 1
    $player_id = autoLoad('getPlayerId',true);
}
else {
    # You should validate your id
    $player_id = (is_numeric($_GET['player_id']))? $_GET['player_id'] : autoLoad('getPlayerId',true);
}
# Load function to get user data
autoLoad('getPlayer');
# Fetch the player info
$player   = getPlayer($link,$player_id);
# Store first and username
$forename = (isset($player['forename']))? $player['forename'] : false;
$username = (isset($player['username']))? $player['username'] : false;
# Go to home page if not logged in
if(empty($username)) {
    header('Location: index.php');
    exit;
}
# Autoload welcome block for greeting
autoLoad('welcome_block');
# Not sure what this is
$login_session=$_SESSION['login_user'];
?>
<html">   
   <head>
      <title>Welcome</title>
   </head>
   <body>
      <?php echo welcome_block($forename,$username) ?>
      <h2><a href = "logout.php">Sign Out</a></h2>
   </body>
</html>

Your login script seems somewhat illogical because you assign session values before you actually validate the user. Also, with how you have it, the login is not very secure, you should be using $_POST instead of $_GET. The browser which the user is using will capture the query in history.

Rasclatt
  • 12,498
  • 3
  • 25
  • 33
  • Comments are not for extended discussion or debugging sessions; the previous conversation has been [moved to chat](http://chat.stackoverflow.com/rooms/151712/discussion-on-answer-by-rasclatt-changing-id-as-you-log-in). – Cody Gray - on strike Aug 11 '17 at 10:51