Jump to content
Killersites Community
Sign in to follow this  
DavidCampbell

Why is my form displaying the input data on submit?

Recommended Posts

Here is a screenshot of the bug:


298507138_ScreenShot2019-02-15at21_39_01.thumb.png.b76e55b62f6d08eef6b695994ae25ce2.png 

This login is based on the  KillerSites OOP Login tutorial. But I've made some differences.  Firstly is in a sub directory 'admin' as i'm building that first. Secondly the most important change is I've changed it to PDO instead of MySQLi. I've gone all through my code and cant see where this would decide to print out like this.

Feel a bit dumb not being able to find out why this is performing like this. Hoping someone has a quick answer. I'm just at the beginning of this build and I wanted to adapt the code to use DPO, although I have had no experience with DPO. So I was thinking that is prob the route of the problem. Otherwise I'll switch back to MYSQLI, which I want to avoid. 

 

 

 

Edited by DavidCampbell

Share this post


Link to post
Share on other sites
<?php

// ===========================================
// INIT
// Basic configuration settings
// ===========================================

// connect to database (PDO)
$host       = "localhost";
$username   = "root";
$password   = "yes";
$dbname     = "recordLabel";
$dsn        = "mysql:host=$host;dbname=$dbname";
$options    = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
$connection = new PDO($dsn, $username, $password, $options);

// set up constants
define('SITE_NAME', 'My Record Label');
define('SITE_PATH', 'http://recordLabel.local/admin/'); // local/admin
define('IMAGE_PATH', 'http://recordLabel.local/admin/resources/images/'); // local/admin

// include objects
include('app/models/m_template.php');
include('app/models/m_auth.php');

// create objects
$Template = new Template();
$Auth = new Auth();

session_start();

my init.php

Share this post


Link to post
Share on other sites

template.php

 

<?php

// ====================================================
// TEMPLATE CLASS
// Handling all templating tasks - displaying views, alerts, erros and view data
// ====================================================

class Template
    {
    // ==========================	
	//	Class scope vars
	// ==========================	

    private $data;
    private $alert_types = array('success', 'error');
  
	// ==========================
	//	Constructor
	// ==========================

    function __construct()
        {
        // do nothing
        }

	// ==========================	
	//	Methods
	// ==========================

    /**
     * Loads specified url
     *
     * @access 	public
     * @param 	string, string
     * @return  null	
     **/
    public function load($url, $title)
        {
        if($title != ''){ $this->set_data('page_title', $title); }
        include($url);
        }

    /**
     * Redirects to specified url
     *
     * @access 	public
     * @param 	string
     * @return  null	
     **/
    public function redirect($url)
        {
        header("Location: $url");
        exit;
        }

    /*
        Get / Set Data
    */

    /**
     * Saves provided data for use by the view later
     *
     * @access 	public
     * @param 	string, string, bool
     * @return  null	
     **/
    public function set_data($name, $value, $clean = FALSE)
        {
        if ($clean == TRUE)
            {
            $this->data[$name] = htmlentities($value, ENT_QUOTES);
            }
        else
            {
            $this->data[$name] = $value;
            }
        }

    /**
     * Retrieves data based on provided name for access by view
     *
     * @access 	public
     * @param 	string, bool
     * @return  string
     **/
    public function get_data($name, $echo = TRUE)
        {
        if(isset($this->data[$name]))
            {
            if($echo)
                {
                echo $this->data[$name];
                }
            else
                {
                return $this->data[$name];
                }
            }
        return '';
        }

    /*
        Get / Set Alerts
    */

    /**
     * Sets an alert message stored in the session
     *
     * @access 	public
     * @param 	string, string (optional)
     * @return  null
     **/
    public function set_alert($value, $type = 'success')
        {
            $_SESSION[$type][] = $value;
        }

    /**
     * Returns string, containing multiple list items of alerts
     *
     * @access 	public
     * @param 	
     * @return  string
     **/
    public function get_alerts()
        {
            $data = '';

            foreach ($this->alert_types as $alert) 
                {
                if(isset($_SESSION[$alert]))
                    {
                        foreach ($_SESSION[$alert] as $value) 
                            {
                            $data .= '<li class="' . $alert . '">' . $value . '</li>';
                            }
                        unset($_SESSION[$alert]);
                    }
                }
            // echo $data;
            return $data;
        }   
    
    // END Template Class
    }

 

Share this post


Link to post
Share on other sites

auth.php

 

<?php

// ====================================================
//	AUTHORIZATION CLASS
//	Deals with auth tasks
// ====================================================

class Auth
    {
    // ==========================	
	//	Class scope vars
	// ==========================			
	
	private $salt = 'j4H9?s0d';

	// ==========================
	//	Constructor
	// ==========================

	function __construct()
		{
        // do nothing
        }
        
	// ==========================	
	//	Methods
	// ==========================
  
    // =============
    // validate login
    // =============

	function validateLogin($user, $pass)
		{ 
        /*
        // access db
		global $Database;

		// create query
		if ($stmt = $Database->prepare("SELECT * FROM users WHERE username = ? AND password = ?"))
			{
			$passPlusSalt = $pass . $this->salt;
			$passPlusSalt = md5($passPlusSalt);

			$stmt->bind_param("ss", $user, $passPlusSalt);
			$stmt->execute();
			$stmt->store_result();

			// check for num rows
			if ($stmt->num_rows > 0)
				{
				// success
				$stmt->close();
				return TRUE;
				}
			else
				{
				// failure
				$stmt->close();
				return FALSE;
				}
			}	
		else
			{
			die("ERROR: Could not prepare MySQLi statement.");
            }
            
        */

        $sql = "SELECT * FROM users WHERE 
        userName = :user AND 
        password = :passPlusSalt AND 
        adminUser = :isAdmin";
        
        $user = $user;
        $passPlusSalt = $pass . $this->salt;
        $passPlusSalt = md5($passPlusSalt);
        $isAdmin = "true";

        // access database
        global $connection;

        try 
            {
            $statement = $connection->prepare($sql);
            $statement->bindParam(':user', $user, PDO::PARAM_STR);
            $statement->bindParam(':passPlusSalt', $passPlusSalt, PDO::PARAM_STR);
            $statement->bindParam(':isAdmin', $isAdmin, PDO::PARAM_STR);
            $statement->execute();

            $result = $statement->fetchAll();
            }
        catch(PDOException $error) 
            {
            echo $sql . "<br>" . $error->getMessage();
            }

        if ($result && $statement->rowCount() > 0)
            {
            // success
            return TRUE;
            }
        else
            {
            // failure
            return FALSE;
            }
        }
        
    // =============
    // check login status
    // =============

	function checkLoginStatus()
		{
		if (isset($_SESSION['loggedin']))
			{
			return TRUE;
			}
		else
			{
			return FALSE;
			}
		}

    // =============
    // logout
    // =============

	function logout()
		{
		session_destroy();
		session_start();
		}

    // END Auth Class
    }


 

Share this post


Link to post
Share on other sites

login.php

 

<?php

// ====================================================
// LOGIN
// 
// ====================================================

include("app/init.php");
$Template->set_data('page_class', 'login');

if (isset($_POST['submit']))
	{
	// get data
	$Template->set_data('input_user', $_POST['username']);
	$Template->set_data('input_pass', $_POST['password']);

	// validate data
	if ($_POST['username'] == '' || $_POST['password'] == '')
		{
		// show error
		if ($_POST['username'] == '') { $Template->set_data('error_user', 'required');}
		if ($_POST['password'] == '') { $Template->set_data('error_pass', 'required');}

		$Template->set_alert('Please fill in all required fields', 'error');
		$Template->load("app/views/v_login.php", "Login");
		}
	else if ($Auth->validateLogin($Template->get_data('input_user'), $Template->get_data('input_pass')) == FALSE )
		{
		// invalid login
		$Template->set_alert('Invalid username or password', 'error');
		$Template->load("app/views/v_login.php", "Login");
		}
	else
		{
		// successful log in
		$_SESSION['username'] = $Template->get_data('input_user');
		$_SESSION['loggedin'] = TRUE;

		$Template->set_alert('Welcome <i>' . $Template->get_data('input_user') . '</i>');
		$Template->redirect('home.php'); // send to admin home
		}
	}
else
	{
    // echo "template load v_login.php";    
    $Template->load("app/views/v_login.php", "Login");    
	}

 

Share this post


Link to post
Share on other sites

v_login.php (view)

<!DOCTYPE html>
<html>
	<head>
		<title>Login In</title>
		<meta http-equiv="Content-type" content="text/html; charset=utf-8">
		<link href="resources/css/style.css" media="screen" rel="stylesheet" type="text/css">
	</head>
	<body>
		<h1>Log In</h1>
		<div id="content">
			<form action="" method="post">
				<div>
					<?
					$alerts = $this->get_alerts();
                    if ($alerts != '') 
                        { 
                        echo "<ul class=\"alerts\">\n";
                        echo $alerts; 
                        echo "</ul>\n";
                        }
					?>
				</div>

				<div class="row">
					<label for="username">Username: *</label>
					<input type="text" name="username" value="<? echo $this->get_data('input_user'); ?>">
					<div class="error"><? echo $this->get_data('error_user'); ?></div>
				</div>

				<div class="row">
					<label for="password">Password: *</label>
					<input type="password" name="password" value="<? echo $this->get_data('input_pass'); ?>">
					<div class="error"><? echo $this->get_data('error_pass'); ?></div>
				</div>

				<div class="row">
					<p class="required">* required</p>

					<input type="submit" name="submit" class="submit" value="submit">
				</div>
			</form>
		</div>
	</body>
</html>

 

Share this post


Link to post
Share on other sites

the admin index.php, is very simple:

 

<?php

// ====================================================
// INDEX
// 
// ====================================================

/*
* Are we loged in?
* YES - redirect to admin home
* NO - redirect to login
*/

include("app/init.php");

// check authorization
if ($Auth->checkLoginStatus() == FALSE)
	{
	$Template->redirect('login.php');
	}
else 
	{
	echo "redirect to home.php";
	// $Template->redirect('home.php');
	}	

 

Share this post


Link to post
Share on other sites

Hi Stefan,

I haven't solved it yet,  I'm a little stumped.

My local version of OOP Login works as expected.  Obviously there are differences in the file structure and the use of DPO instead of MYSQLI.

My next move was to just refactor the code and use MYSQLI. But It would be nice to get DPO working though.

Screen Shot 2019-02-16 at 17.02.29.png

Share this post


Link to post
Share on other sites

I had some time to return to this today - fixed it.

The bug arrises because of the subtle difference between get_data in the Template class. in the oopLogin the method does not have the option to echo out the data, whereas the one in phpCart, it does. so much confusion over something so simple.

 

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×