Jump to content

Question about Classes..


id

Recommended Posts

Ok so i'm new to classes in php and i have a question.

 

I'm working on a login / registration script in php,and i want to know what is the purpose of a class? Is it worth making? I been trying to find the benefits of making a class, but i don't see any because all i found was that it makes the code "looks" neat.

 

My goal is to make a simple website (for practice), that would allow members to register to the database, then they would be able to login. Once login, the members would be allow to edit their profile and so on. Nothing complicated. However, when i try to set up a class and functions it get complicated.

 

Example,

I have a function called check_user, which would connect to the DB and verify that the user exist and if so then see if the passwords match. However, if the username doesn't exist or  the user exist but the password doesn't match or if the user and pass matches then what do i return? Do i return a number value and if then what do i do with that number?

 

:confused: :confused: :confused: :confused: :confused: :confused:

Link to comment
Share on other sites

Some would argue that OOP is to much overhead for a simple site.  But, I would say that OOP scales better, and is easier to take a simple site to a complex one.

 

On the flip side, I think it is easier to understand OOP, if you know what the general coding does.  So, I would start with simple procedural code, then move up to OOP after you become better versed in procedural.

 

In answer to your example:  What do YOU need it to return?  true? false? 1? 0?, it is up for you to decide how to use the information that is returned.  What do you want to do if the login fails?  What do you want to do if the login is successful?

 

Generally it goes:

1. User enters form data

2. Upon submission, server checks form data against database.

3. Success sends to another page, Failure points back to form with error message

 

Link to comment
Share on other sites

Well thats the thing, alot of people do it differently.

 

I would like for if its successful then simply set up a valid session and redirect it to a different page, but if it fails then simple point of the error. Im trying to start with a simple webpage, then build upon it so it can be complex.

Link to comment
Share on other sites

OK, so the function should return true if the login is successful, and false if it fails at ANY POINT.

 

<?php

function check_user($user,$password) {
$password = md5($password); //example should use a better engine.
$sql = "SELECT id FROM user WHERE name = '" . mysql_real_escape_string($user) . "' AND password = '$password'";
$result = mysql_query($sql) or trigger_error(mysql_error());
if(mysql_num_rows($result) == 1) {
return true;
}
return false;
}

if($_SERVER['REQUEST_METHOD'] == 'POST' && (!empty($_POST['username']) && !empty($_POST['password']))) {
if(check_user($_POST['username'],$_POST['password'])) {
     header('Location: http://mysite.com/successful_login.html');
} else {
    header('Location: http://mysite.com/login_failed.php?error=wrong%20username%20or%20password');
}
}

Link to comment
Share on other sites

A couple of comments to the example above.

 

  1. [*]Always use an individual salt when hashing password, and always create a new salt every time the password changes.

[*]You must have die () after using a header ('Location: ') call, otherwise PHP will continue to parse the script and all of the following code.

[*]Don't resent users on error, but show the form again with preloaded values.[/ic]

Link to comment
Share on other sites

While most of you post made sense, I question this one:

3.  Don't resent users on error, but show the form again with preloaded values.[/ic]

I would be pretty upset if I didn't get a login error, but just kept looking at a screen with my credentials on it.  Pretty sure it wouldn't take me long to leave.

 

 

Link to comment
Share on other sites

Ok so i been experimenting with some code (basic code, so no advance stuff nor any security measurements like md5,etc...) and i can not get this simple script to work.  So this is how its suppose to go; on the index.php page, you login, which goes to process.php which runs the function of the functions.php page, etc.. You guys are smart and knows what the program is doing.

 

However, it is not working right. I assume that my issue comes from my function.php page where i do the public function...

 

index.php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Login Page!</title>
</head>

<body>


<?php

if(isset($_SESSION['username']))
{
//Already logged in member!
header("location: members.php");
}

?>
<table>
<form action='process.php' method='post'>
<tr>
<td>Username: </td>
<td><input type='text' name='username' /></td>
</tr>
<tr>
<td>Password: </td>
<td><input type='password' name='password' /></td>
</tr>
<tr>
<td>
<input type='submit' value='login' name='submit' />
</td>
</tr>
</form>
</table>

</body>
</html>

 

process.php

<?php
include("functions.php");

//Process for each form!

if(isset($_POST['submit']))
{

$username = $_POST['username'];
$password = $_POST['password'];

$members->check_login($username,$password);
$members->login();

}

if(isset($_POST['submit_logout']))
{
$members->logout();
}


?>

 

functions.php

<?php

include ("config.php");

//Classes and functions!

class memberssystem
{

var $username, $password;

function check_login($username,$password)
{

$result = mysql_query("SELECT * FROM member WHERE username ='$username'") or die(mysql_error());
$check_rows = mysql_num_rows($result) or die(mysql_error());

if($check_rows != 1)
{
	return 0;
}

else
{
	while($row = mysql_fetch_array($result))
	{
		if($row['username'] != $username || $row['password'] != $password)
		{
			return 1;
		}

		else
		  return true;   //Success! 
	}
}	

}

public function login()
{

if($this->check_login($this->username,$this->password) == 0)
{
	die("Username doesn't exist!");
}

else if($this->check_login($this->username,$this->password) == 1)
{
	die("Sorry but the combination doesn't match");
}

else
{
	$_SESSION['username'] = $this->username;
	header("location: members.php");
}
}

public function logout()
{

session_destroy();
header("location: index.php");

}

}

$members = new memberssystem;

?>

 

config.php

<?php

//Configuration File
session_start();

define("DB_HOST","localhost");            //Define Host
define("DB_USER","root");                 //Define Username
define("DB_PASS","");                     //Define Password
define("DB_TABLE","practice5");           //Define the table that is being used.

//Connect to the Server
$connection = mysql_connect(DB_HOST,DB_USER,DB_PASS) or die (mysql_error());

//Connect to the Databse
mysql_select_db(DB_TABLE,$connection);

?>

 

members.php

<?php

//Member's Page!

if(!$_SESSION['username'])
{
header("location: index.php");
}

?>

<html>

<h1>Member's Page!</h1>

<p>Welcome to the Member's Page! For right now, you can not do anything :/ but you can <a name='submit_logout' href='process.php'>logout</a> :} </p>


</html>

 

Link to comment
Share on other sites

Ok, the first section is good.

 

Now, the section below,  your check_login function returns a 1 or true depending on if the user/pass match.  Now the var of the object, $username, and $password do not get initialized during the check_login function.  In your login function your are passing in null values to check_login by sending $this->username and this->password (null values).  Also as a side note, if you already validate the user in check_login, why do it again in the login function ?

 

<?php

include ("config.php");

//Classes and functions!

class memberssystem
{

var $username, $password;

function check_login($username,$password)
{

$result = mysql_query("SELECT * FROM member WHERE username ='$username'") or die(mysql_error());
$check_rows = mysql_num_rows($result) or die(mysql_error());

if($check_rows != 1)
{
	return 0;
}

else
{
	while($row = mysql_fetch_array($result))
	{
		if($row['username'] != $username || $row['password'] != $password)
		{
			return 1;
		}

		else
		  return true;   //Success! 
	}
}	

}

public function login()
{

if($this->check_login($this->username,$this->password) == 0)
{
	die("Username doesn't exist!");
}

else if($this->check_login($this->username,$this->password) == 1)
{
	die("Sorry but the combination doesn't match");
}

else
{
	$_SESSION['username'] = $this->username;
	header("location: members.php");
}
}

public function logout()
{

session_destroy();
header("location: index.php");

}

}

$members = new memberssystem;

?>

Link to comment
Share on other sites

Ok, the first section is good.

 

Now, the section below,  your check_login function returns a 1 or true depending on if the user/pass match.  Now the var of the object, $username, and $password do not get initialized during the check_login function.  In your login function your are passing in null values to check_login by sending $this->username and this->password (null values).  Also as a side note, if you already validate the user in check_login, why do it again in the login function ?

 

<?php

include ("config.php");

//Classes and functions!

class memberssystem
{

var $username, $password;

function check_login($username,$password)
{

$result = mysql_query("SELECT * FROM member WHERE username ='$username'") or die(mysql_error());
$check_rows = mysql_num_rows($result) or die(mysql_error());

if($check_rows != 1)
{
	return 0;
}

else
{
	while($row = mysql_fetch_array($result))
	{
		if($row['username'] != $username || $row['password'] != $password)
		{
			return 1;
		}

		else
		  return true;   //Success! 
	}
}	

}

public function login()
{

if($this->check_login($this->username,$this->password) == 0)
{
	die("Username doesn't exist!");
}

else if($this->check_login($this->username,$this->password) == 1)
{
	die("Sorry but the combination doesn't match");
}

else
{
	$_SESSION['username'] = $this->username;
	header("location: members.php");
}
}

public function logout()
{

session_destroy();
header("location: index.php");

}

}

$members = new memberssystem;

?>

 

 

To the person who ask about the error, im getting nothing (literally). And so your saying i have to initialized the username and password? If so, then what would i initialized them with?

Link to comment
Share on other sites

I fixed your code, here are the errors i found

 

1)If you are gonna call $_SESSION, then you must call session_start()

2)You forgot to select the Database to use, (i.e forgot to call mysql_select_db)

3)In your logout link, you say go to "process.php" but how is process.php supposed to know which function you want to use? To remedy this i modified

the url process.php?action=logout . Now the process.php can check if the url contains a action key in $_GET and check it's value is "logout" and then it can logout the user.

 

 

Also, the main purpose of classes is to group related methods and variables, so the class can be reused as many times as need in the form of objects mainly ($p = new class(), $p is an object,)

config.php

<?php

//Configuration File
session_start();

define("DB_HOST","localhost");            //Define Host
define("DB_USER","root");                 //Define Username
define("DB_PASS","");                     //Define Password
define("DB","practice");           //Define the db
define("DB_TABLE","user");           //Define the db

//Connect to the Server
$connection = mysql_connect(DB_HOST,DB_USER,DB_PASS) or die (mysql_error());

//Connect to the Databse
mysql_select_db(DB, $connection);
?>

 

 

functions.php

<?php

include ("config.php");

//Classes and functions!

class memberssystem
{
    function check_login($username,$password)
    {

$result = mysql_query("SELECT * FROM user WHERE username ='$username'") or die(mysql_error());
        
$check_rows = mysql_num_rows($result) or die(mysql_error());

if($check_rows != 1)
{
	return false;
}

else
{
	while($row = mysql_fetch_array($result))
	{
		if($row['username'] != $username || $row['password'] != $password)
		{
			return false;
		}

		else
		  return true;   //Success! 
	}
}	

}

public function logout()
{

session_destroy();
header("location: index.php");
        die();

}

}

$members = new memberssystem();

?>

 

index.php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Login Page!</title>
</head>

<body>
<?php
session_start();
if(isset($_SESSION['username']))
{
//Already logged in member!
header("location: members.php");
}

?>
<table>
<form action='process.php' method='post'>
<tr>
<td>Username: </td>
<td><input type='text' name='username' /></td>
</tr>
<tr>
<td>Password: </td>
<td><input type='password' name='password' /></td>
</tr>
<tr>
<td>
<input type='submit' value='login' name='submit' />
</td>
</tr>
</form>
</table>

</body>
</html>

 

members.php

<?php
session_start();
//Member's Page!

if(!$_SESSION['username'])
{
header("location: index.php");
}

?>

<html>

<h1>Member's Page!</h1>

<p>Welcome to the Member's Page! For right now, you can not do anything :/ but you can <a name='submit_logout' href='process.php?action=logout'>logout</a> :} </p>


</html>

 

process.php

<?php
include("functions.php");

//Process for each form!

if(isset($_POST['submit']))
{

$username = $_POST['username'];
$password = $_POST['password'];

$login = $members->check_login($username,$password);
if($login)
        {
            	$_SESSION['username'] = $username;
	header("location: members.php");
                die();
        }

}

if(isset($_GET['action']) && $_GET['action'] == 'logout')
{
        $members->logout();

}


?>

Link to comment
Share on other sites

The 'var' keyword is deprecated and shouldn't be used.  Any tutorials that have it are old (PHP 4) and likely not very good.

 

OOP is really something that isn't well suited to tutorials anyway.  The syntax - how to write classes, invoke methods, etc. - is really the least important part of it.  Slapping a bunch of thematically similar functions in a class is NOT OOP.

 

So, get good books.  Matt Zandstra has the best OOP for PHP book around.  After you go through that get the Gang of Four's book.  OOP is the kind of subject that's worth getting good resources for.

Link to comment
Share on other sites

Here's your class again with the actual queries/database/table abstracted. If you would want to store your users in a mssql db tomorrow all you need to do is change the driver to mssql all code will still work the same even though you changed the actual RDBMS.

 

class MembersSystem
{
    private $usersGateway;
    
    public function __construct(TableGatewayInterface $users) {
        $this->usersGateway = $users;
    }
    
    function check_login($username,$password)
    {
        $foundUsers = $this->usersGateway->select(array('username' => $username));
        
        if (count($foundUsers) !== 1) {
            return false;
}
        
        $user = $foundUsers[0];
        if ($user->username !== $username || $user->password !== $password) {
            return false;
        }
        return $user; // return the actual user object on success instead of true.
    }
}

$members = new MembersSystem(new TableGateway('user', new Adapter(array('driver' => 'mysqli', ..));

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.