I'm new to coding, and especially to OOP PHP. I'll highly appreciate if you expert programmers could review following code and give me your opinion to make it better. Also, how you see this code, is it too horrible and ugly?
<?php
include_once("config.inc.php");
class user{
var $mysqli;
var $username;
var $userid;
function __construct($mysqli) {
session_start();
$this->mysqli = $mysqli;
}
function valid_length($input){
if ((strlen($input) > 4 ) AND (strlen ($input) < 16) ){
return true;
} else {
return false;
}
}
function valid_email($email){
if (preg_match("/^[0-9a-z]+(([\.\-_])[0-9a-z]+)*@[0-9a-z]+(([\.\-])[0-9a-z-]+)*\.[a-z]{2,4}$/i" , $email)) {
return true;
} else {
return false;
}
}
function alpha_numeric($input){
if (eregi("^([0-9a-z])+$", $input)){
return true;
}else{
return false;
}
}
function username_exists($username){
if ($stmt = $this->mysqli->prepare("SELECT username FROM users WHERE username=?")) {
$stmt->bind_param("s", $username);
$stmt->execute();
$stmt->store_result();
$count=$stmt->num_rows;
$stmt->close();
}
return ($count > 0 ? true : false);
}
function signup($username, $password, $email, $capt_error){
//validate username.
if(!$this->valid_length($username)){
$this->signup_error = "Username should be 5 - 15 characters. <br />";
}else if(!$this->alpha_numeric($username)){
$this -> signup_error ="Only letters, numbers";
} else if($this->username_unallowed($username)){
$this -> signup_error ="Not allowed.";
} else if ($this->username_exists($username)){
$this -> signup_error ="Username already exists. <br />";
}
//validate password.
if (!$this->valid_length($password) ){
$this -> signup_error .="Password should be 5 - 15 characters. <br />";
}
//validate email.
if (!$this->valid_email($email) ){
$this -> signup_error .="Invalid email.";
}else if($this->email_exists($email)) {
$this -> signup_error .="Email exists.<br />";
}
//captcha error
if($capt_error == 1){
$this -> signup_error .="Invalid captcha. <br />";
}
//no any error, proceed.
if ($this->signup_error == ""){
$hashed_password = $this->hash_password($password);
if ($this->insert_new_user($username, $enc_password, $email)){
$_SESSION['username']=$username;
header("Location: welcome.php");
}else {
$this->signup_error = "Unknown error. <br />";
}
}
}
}
?>
?>
to the end of files like this. If there is any extra whitespace after the closing PHP tag, it will be output to the browser when all you intended to do was include a class for internal (non-presentation) use. This sort of thing can be excruciatingly difficult to track down when you're not sure why there's an extra space in an arbitrary spot on a page. \$\endgroup\$