2

I am creating a website where a user can login, they'd have their own profile page where they can change a few settings. To view their profile they must be logged in.

I have a registration page where the user is asked for their first name, last name, username and password. What I would like to accomplish is a one-page solution where a user can register/login/view their profile etc.

So far I have this:

member.php - This is the member class

<?php

require_once("database.php");

class Member extends DatabaseObject {
    protected static $table_name = "tblMembers";
    var $firstName = null; // initiating the $firstName variable
    var $lastName = null; // initiating the $lastName variable
    var $username = null; // initiating the $username variable
    var $password = null; // initiating the $password variable
    var $reviews = null; // initiating the $reviews variable
    var $type = null; // initiating the $type variable

    function __construct($firstName, $lastName, $username, $password) {
        $this->firstName = $firstName;
        $this->lastName = $lastName;
        $this->username = $username;
        $this->password = $password;
        //$this->insert($firstName, $lastName, $username, $password, $type);
    }

    function set_firstName($firstName) {
        $this->firstName = $firstName;
    }

    function get_firstName() {
        return $this->firstName;
    }

    function set_lastName($lastName) {
        $this->lastName = $lastName;
    }

    function get_lastName() {
        return $this->lastName;
    }

    function get_fullName() {
        if (isset($this->firstName) && isset($this->lastName)) {
            return $this->firstName . " " . $this->lastName;    
        } else {
            return "";
        }
    }

    function set_username($username) {
        $this->username = $username;
    }

    function get_username() {
        return $this->username;
    }

    function set_password($password) {
        $this->password = md5(DB_SALT.$password);
    }

    function get_password() {
        return $this->password;
    }

    public static function authenticate($username="", $password="") { 
        global $database;
        $username = $database->escape_value($username);
        $password = $database->escape_value($password);
        $passwordHash = md5(DB_SALT.$password);

        $sql = "SELECT * FROM tblMembers ";
        $sql .= "WHERE username = '{$username}' ";
        $sql .= "AND passwordHash = '{$passwordHash}' ";
        $sql .= "LIMIT 1";

        $result_array = self::find_by_sql($sql);
        if (!empty($result_array)) {
            //echo "true";
            return array_shift($result_array); // Pulling first element from array
        } else {
            //echo "false";
            return false; // Ability to ask whether we return something
        }

    }

    public function insert($firstName, $lastName, $username, $password) {
        $database = new Database();
        $database->query("INSERT INTO tblMembers VALUES ('','{$firstName}','{$lastName}','{$username}','{$password}','4')");
    }

    // Common Database Methods

    private static function instantiate($record) {
        $object = new self;

        foreach ($record as $attribute=>$value) {
            if ($object->has_attribute($attribute)) {
                $object->$attribute = $value;
            }
        }
        return $object;
    }

    public static function find_all() {
        return self::find_by_sql("SELECT * FROM ".self::$table_name);
    }

    public static function find_by_id($id=0) {
        global $database;
        $result_array = self::find_by_sql("SELECT * FROM ".self::$table_name." WHERE userID={$id} LIMIT 1");
        if (!empty($result_array)) {
            return array_shift($result_array); // Pulling first element from array
        } else {
            return false; // Ability to ask whether we return something
        }
    }   

    public static function find_by_sql($sql="") {
        global $database;
        $result_set = $database->query($sql);
        $object_array = array();
        while ($row = $database->fetch_array($result_set)) {
            $object_array[] = self::instantiate($row);
        }
        return $object_array;
    }

    private function has_attribute($attribute) {
        $object_vars = get_object_vars($this);
        return array_key_exists($attribute, $object_vars);
    }
}

?>

database.php

This is the database class

<?php
require_once("config.php");
class Database {

    private $connection;
    public $last_query;
    private $magic_quotes_active;
    private $mysql_real_escape_string_exists;

    function __construct() {
        $this->open_connection();
        $this->magic_quotes_active = get_magic_quotes_gpc();
        $this->mysql_real_escape_string_exists = function_exists("mysql_real_escape_string");
    }

    public function open_connection() {
        // Create Database connection
        $this->connection = mysql_connect(DB_SERVER, DB_USER, DB_PASS);
        if (!$this->connection) {
            die("Database connection failed: " . mysql_error());
        } else {
            $db_select = mysql_select_db(DB_NAME, $this->connection);
            if (!db_select) {
                die("Database selection failed: " . mysql_error());
            }
        }
    }

    public function close_connection() {
        // Closes the connection to the database
        if(isset($this->connection)) {
            mysql_close($this->connection);
            unset($this->connection);
        }
    }

    public function query($sql) {
        $this->last_query = $sql;
        $result = mysql_query($sql, $this->connection);
        $this->confirm_query($result);
        return $result;
    }

    public function escape_value($value) {

        if ($this->mysql_real_escape_string_exists) {           
            if ($this->magic_quotes_active) {
                $value = stripslashes($value);
            }
            $value = mysql_real_escape_string($value);
        } else {
            if (!$this->magic_quotes_active) {
                $value = addslashes($value);
            }
        }
        return $value;
    }

    public function num_rows($result_set) {
        return mysql_num_rows($result_set);
    }

    public function insert_id($result_set) {
        return mysql_insert_id($this->connection);
    }

    public function affected_rows() {
        return mysql_affected_rows($this->connection);
    }

    public function fetch_array($result_set) {
        return mysql_fetch_array($result_set);
    }

    private function confirm_query($result) {
        if (!$result) {
            $output = "Database query failed: " . mysql_error() . "<br />";
            $output .= "Last SQL query: " . $this->last_query;
            die($output);
        }
    }
}


$database = new Database();

?>

The connection to the database works fine, the parameters are store in a file called config.php along with DB_SALT.

register.php - This contains the registration form, however I would like to submit the form using AJAX rather than the current post method which forces the page to refresh. Any help to achieve this will be appreciated. I don't want to use JQuery for this as I am unfamiliar with it, and I am still learning JavaScript so I don't want to jump ahead.

<?php
require_once("includes/config.php");
if(isset($_POST['submit'])) {
    $firstName = $_POST['firstName'];
    $lastName = $_POST['lastName'];
    $username = $_POST['username'];
    $password = $_POST['password'];
    $member = new Member();
    $member->insert($firstName, $lastName, $username, $password);
} else {
?>
<!DOCTYPE html>
<html lang="en-EN">
    <head>
        <meta charset="UTF-8">
        <link rel="stylesheet" href="css/style.css" media="screen" />
        <link rel="stylesheet" href="css/email_client.css" media="screen" />
        <!--[if !IE 7]>
            <style type="text/css">
                #wrap {display:table;height:100%}
            </style>
        <![endif]-->

        <title>Register</title>
    </head>
    <body>
        <?php include("includes/header.php"); ?>
        <div id="wrap">
            <div id="main">

                <nav>
                    <?php include("includes/nav.php"); ?>
                </nav>

                <div id="stylized" class="myform">
                    <form action="<?php echo $PHP_SELF; ?>" method="post">
                        <span class="label">First Name:</span>&nbsp;<input id="firstName" type="text" name="firstName" class="splash" value="John"><br />
                        <span class="label">Last Name:</span>&nbsp;<input id="lastName" type="text" name="lastName" class="splash" value="Smith"><br />
                        <span class="label">Username:</span>&nbsp;<input id="username" type="text" name="username" class="splash" value="jsmith"><br />
                        <span class="label">Password:</span>&nbsp;<input id="password" type="password" name="password" class="splash" value="pass"><br />
                        <span class="label">Confirm Password:</span>&nbsp;<input id="passwordConfirmation" type="password" name="passwordC" class="splash" value="pass"><br />
                        <input type="submit" value="Register" class="button" name="submit">
                    </form>
                </div>
            </div>
        </div>
        <div id="footer">
            <?php echo COPYRIGHT_STRING; ?>
        </div>  
    </body>
</html>
<?php } ?>

I would like to incorporate technologies such as AJAX and SESSIONS to store the state of the user so that their log-in is persistent.

The thing that I am struggling with now is how do I handle the register.php form submission, create the new Member object and insert all of that data directly into the database.

I have checked our various tutorials, all are too complex for what is needed here, also, as stated above I don't wish to use jQuery, at least not for the time being.

Joel
  • 4,732
  • 9
  • 39
  • 54
Michael
  • 4,282
  • 9
  • 55
  • 89
  • Nice [SQL injection holes](http://bobby-tables.com). Even if you solve your problem, you'll still be opening your server to a remote takeover. – Marc B Feb 23 '13 at 17:51
  • How would I overcome this? – Michael Feb 23 '13 at 17:53
  • I don't understand that. Is it similar to the escape_value function in the database.php class? Can you give me an example of it's usage in the context of my project. – Michael Feb 23 '13 at 17:56
  • `$firstname = $_POST['firstname']; $this->insert($firstname)`. it's good you have an escape function, but that function is absolutely useless since you don't actually use it. – Marc B Feb 23 '13 at 17:59

1 Answers1

0

Gerneral thoughts on ajax

Are you sure you want all in one page? A login page looks remarkably different from a profile page in my experience, but it is your choice.

Ajax is mostly just the loading of a site via JavaScript. You can start here XMLHttpRequest.

You could just load complete websites with the XMLHttpRequest and replace the content of your html-body, but the idea behind ajax is to only transfer what needs to be transfered, meaning what needs to be changed on the website in the browser. Therefore often only JSON data is transfered, or html data for certain div containers on the website. Your server needs to be prepared for those requests, e.g. in a very basic way:

<?php
// read request data uses http://www.php.net/manual/en/book.filter.php
$firstName = filter_input(INPUT_POST, 'firstName', FILTER_SANITIZE_STRING);
$lastName  = filter_input(INPUT_POST, 'lastName', FILTER_SANITIZE_STRING);
$username  = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING);
$password  = filter_input(INPUT_POST, 'password', FILTER_SANITIZE_STRING);

//create Memeber object and save it
require_once('member.php');
$member = new Member ($firstName, $lastName, $username, $password);
$success = $member->insert();

// answer the request
$data = new stdClass();
if( $success === true ) { 
    // return Success
    $data->success = true;
    print json_encode($data);
    exit();
} else {
    // return error
    $data->success = false;
    $data->message = 'Could not register';
    print json_encode($data);
    exit();
}
exit(-1);
?>

Make sure you are not submitting your form the normal way see here

jQuery makes all of that a lot easier, so maybe you want to reconsider not using it.

PHP Programming

Stop using var in php classes it is deprecated, use visibility modifiers like you did in the Database class (private, public,protected)

Since you strife to use OOP, please take note of the PHP PDO and try to use those for your database layer

Implement your Database as a singleton, might be easier, basically add:

<?php
// in Database class

/** The Sigleton instance
  * @var Database
  */
private static $instance = false;

/** Singleton Getter for this class.
  * @return Database The singleton instance.
  */
public static getInstance() {
    if(self::$instance === false) {
        self::$instance = new self();
    }
    return self::$instance;
}
?>

and make sure your constructor is protected, so no other instances will be created. To use it do something like this:

<?php
// in Member class

public function insert($firstName, $lastName, $username, $password) {
    // get singleton instance;
    $db = Database::getInstance();

    return $db->query(sprintf(
        "INSERT INTO tblMembers VALUES ('','%s','%s','%s','%s','4')",
        $db->escape_value($this->firstName),
        $db->escape_value($this->lastName),
        $db->escape_value($this->username),
        $db->escape_value($this->password)
    ));
}
?>

Hope this helps to get you started.

Community
  • 1
  • 1
Armin
  • 184
  • 1
  • 9