0

I have got a little problems with OOP in php since this is my 1st time I am using it. I am trying to write my own authentication system without framework, just to undestand the basics of register/login/logout system. So I've made this so far, file connect.php:

<?php

class Dbconnect {
    private $servername;
    private $username;
    private $password;
    private $dbname;

    protected function connect() {
        $this->servername = "localhost";
        $this->username = "root";
        $this->password = "root";
        $this->dbname = "example";

        $conn = new mysqli($this->servername,$this->username,$this->password,$this->dbname);
        return $conn;
    }
}

Looks good, right? But now I don't understand how should my register.php file look like, I've wrote a procedural version, and don't know how to modify it to become OOP here it is:

<?php


include 'connect.php';

$Err = $emailErr = $usernameErr =  "";

//registration
if(isset($_POST['register'])) {
    $username = mysqli_real_escape_string($conn,$_POST['username']);
    $email = mysqli_real_escape_string($conn,$_POST['email']);
    $password = mysqli_real_escape_string($conn,$_POST['password']);

    if(empty($username) || empty($email) || empty($password)) {
        $Err = "Empty field(s)";
    } 

    if(!preg_match("/^[a-zA-z ]+$/", $username)){
        $usernameErr = "Use letters for user";
    } elseif(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $emailErr = "Wrong email format";

            }

        }

           if ($Err == "" && $emailErr == "" && $usernameErr == "") {
    $hashed_password = password_hash($password, PASSWORD_DEFAULT);
    $sql = "INSERT INTO users (username, email, password)
    VALUES('$username','$email','$hashed_password')";
    $result = $conn->query($sql);
    if($result) {
        header('location: http://' . $_SERVER['HTTP_HOST'] . '/test/success.php');
        exit();   

    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }


}

    }
?>

Can someone explain me how I should modify this file.Thanks.

  • 2
    Try taking tutorials on object oriented programming in php. This would help create the right learning foundation. – Rotimi Oct 28 '17 at 11:09
  • Your mysqli connection could not be established. Use mysqli connect function as "__construct" method. – Nandhi Kumar Oct 28 '17 at 11:09
  • @NandhiKumar, why would I do that? localhost parameteres are private and will never change, why use construct? – FeelsBadMan Oct 28 '17 at 11:12
  • When you call connect method? – Nandhi Kumar Oct 28 '17 at 11:13
  • i think you need to call first connect method , `$db = new Dbconnect; $db->connect(); ` – Asif Thebepotra Oct 28 '17 at 11:14
  • @NandhiKumar Yes I am calling that method, but why I need to use construct here //??? – FeelsBadMan Oct 28 '17 at 11:16
  • if you use construct you don't need to call the connect method. it will be loaded automatically. – Nandhi Kumar Oct 28 '17 at 11:18
  • 1
    Start by following good structured procedural programming principles. Then, look for functions that take the same arguments or global variables. These are candidates for abstracting into classes, the shared variables become the state of the objects and the functions become the methods. – reaanb Oct 28 '17 at 11:42
  • Once you get some OOP going you should post it on codereview.stackexchange.com. I think that will be a good fit for you once you get your code complete. They will give you more general guidance than what stack overflow is designed for. Just make sure you.read the rules there first. If you do post something there, feel free the ping me in a comment here and I'll give it a look myself. – Conor Mancone Oct 28 '17 at 15:05

1 Answers1

1

It my be different for other, but here is how I approach it: build it from top down.

So, you start by writing high level logic for the code task, that you want your code to implement:

$connection = new MySQLi('localhost', 'root', 'password', 'example');
$authenticator = new Authenticator($connection);

$activity = $_POST['action'] ?? 'default';
if ('register' === $activity) {
    $user = $authenticator->register($_POST['name'], $_POST['pass']);
}
if ('login' === $activity) {
    if ($authenticator->login($_POST['name'], $_POST['pass'])) {
        echo 'On';
    }
}

When the the top level methods are defined, you go a step deeper and will out the next layer (it can be one or multiple classes).

class Authenticator 
{
    private $connection;

    public function __construct($connection) {
         $this->connection = $connection;
    }

    public function register($username, $password) {
        $user = new User($username);
        $user->setPassword($password);
        $user->save($this->connection);
        return $user;
    }

    public function login($username, $password) {
        $user = new User($username);
        $user->load($this->connection);
        return $user->isMatchingPassword($password)
    }
}

At this point you can start see what other part of code you will have to fill out. In this case, from the code in this example, you would also need to implement a User class with at least the methods, that have already been mentioned.

At each step you tackle one specific scope of problems and that way, even when working on projects with huge complexity, you are not overwhelmed.

Few related notes

  • You cannot return from a constructor
  • There is no point in actually making a wrapper for DB connection. Instead you should use either MySQLi or PDO classes, that come with PHP.
  • Your code is vulnerable to SQL injections. Watch this video to see how you avoid such holes.
  • To find more learning materials, I would recommend watching lectures from this list.
tereško
  • 58,060
  • 25
  • 98
  • 150