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.