Jump to content

[SOLVED] My first oop project


Stickybomb

Recommended Posts

hi I am rather new to oop, trying to learn it and get the hang of it.

 

I have started writting a login system to help me practice and learn it better.

 

basically i plan on building onto it to make a cms for myself.

 

I have been using a good tutorial I have fond for creating a cms in oop to basis it off of as I go.

 

its the tutorial used for creating the lutra_basic Otter Cms if your familiar with it.

 

I am having some issues with headers and what not.

 

when I try and log in it gives me the following errors

Warning: session_start() [function.session-start]: Cannot send session cookie - headers already sent by (output started at /home/sticky/public_html/cms/index.php:11) in /home/sticky/public_html/cms/inc/sentry.php on line 10

 

Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at /home/sticky/public_html/cms/index.php:11) in /home/sticky/public_html/cms/inc/sentry.php on line 10

 

Warning: Cannot modify header information - headers already sent by (output started at /home/sticky/public_html/cms/index.php:11) in /home/sticky/public_html/cms/inc/sentry.php on line 11

 

Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in /home/sticky/public_html/cms/inc/db.php on line 96

 

Warning: Cannot modify header information - headers already sent by (output started at /home/sticky/public_html/cms/index.php:11) in /home/sticky/public_html/cms/inc/sentry.php on line 124

 

my structure is as follows... I have 6 main scripts

core.php <- contains my system settings .

db.php <- class that handles the connection working with the database.

functions.php <- contains some misc. functions used for now until i find a better place for them.

mysql.php <- contains functions returning the sql statment needed (IE getUser() = SELECT * FROM users)

sentry.php <- contains the class for hanling the login and authentication procedures.

validator.php <- contains class to validate the input.

 

for sake of figuring out these errors i am not validating the input and am using the user admin with pass admin for testing

 

db.php//

<?php
////////////////////////////////////////////////////////////////////////////////////////
// Class: Db
// Purpose: Connect to a database, MySQL version
///////////////////////////////////////////////////////////////////////////////////////
require_once 'core.php';

class Db extends Core {

var $theQuery;
var $link;

//*** Function: DbConnector, Purpose: Connect to the database ***
function Db(){

	// Load settings from parent class
	$settings 	= Core::getSettings();

	require_once('mysql.php');
	*/

	// Get the main settings from the array we just loaded
	$host 		= $settings['dbhost'];
	$db 		= $settings['dbname'];
	$user 		= $settings['dbusername'];
	$pass 		= $settings['dbpassword'];

	// Connect to the database
	$this->link = mysql_connect($host, $user, $pass);
	mysql_select_db($db);
	register_shutdown_function(array(&$this, 'close'));


}

//*** Function: query, Purpose: Execute a database query ***
function query($query) {
	$this->theQuery = $query;
	return mysql_query($query, $this->link) or die(mysql_error());
}	

//*** Function: getQuery, Purpose: Returns the last database query, for debugging ***
function getQuery() {
	return $this->theQuery;
}

//*** Function: getNumRows, Purpose: Return row count, MySQL version ***
function getNumRows($result){
	return mysql_num_rows($result);
}

//*** Function: fetchArray, Purpose: Get array of query results ***
function fetchArray($result) {
	return mysql_fetch_array($result);
}

//*** Function: close, Purpose: Close the connection ***
function close() {
	mysql_close($this->link);
}

}
?>

 

sentry.php//

<?php
////////////////////////////////////////////////////////////////////////////////////////
// Class: sentry
// Purpose: Control access to pages
////////////////////////////////////////////////////////////////////////////////////////

class Sentry {

function sentry(){
	session_start();
	header("Cache-control: private"); 
}

//check if user is banned
function isBanned() {
	$result	= $db->query(ipBanCheck());
	if($db->getNumRows($result)==1){
		header("Location: index.php?section=banned&".strip_tags(session_id()));
	}
	$result	= $db->query(userBanCheck($this->login['user']));
	if($db->getNumRows($result)==1){
		header("Location: index.php?section=banned&".strip_tags(session_id()));
	}
}

//sets a cookie for auto login
function setCookie($sid,$pass) {
	require_once('functions.php');
	//generate cookie values
	$expire 		= time() + 1728000; // Expire in 20 days
	$cookie_string 	= hashValue(hashValue($pass).hashValue($sid));
	//set cookie
	//setcookie('user', $user, $expire);
    	setcookie('pass', $cookie_string, $expire);
}

//destroy the current session
function logout() {
	session_destroy();
	unset($_SESSION['id']);
	unset($_SESSION['pid']);
	unset($_SESSION['logedin']);
	unset($_SESSION['lid']);
	return true;
}

// Log in, and either redirect to pass or fail depending on success
function checkLogin($user = '',$pass = '',$group = 10,$remember = ''){

	// Include database and validation classes, and create objects
	require_once('functions.php');
	require_once('db.php');
	$db 				= new Db();

	// If user is already logged in then check credentials
	if ($_SESSION['id'] && $_SESSION['logedin']){

		$results 		= $db->query(sessionAuth($_SESSION['id']));

		if ($db->getNumRows($results) > 0){
			// Existing user ok, continue
			header("Location: index.php?section=cms&".strip_tags(session_id()));

			return true;

		}else{
			// Existing user not ok, logout
			$this->logout();
			return false;
		}

	}else{

		$results 		= $db->query(selectByUser($user));

		if ($db->getNumRows($results) > 0){

			$user		= $db->fetchArray($results);
			$active		= $db->query(getActive($user['user_id']));
			$active		= $db->fetchArray($active);

			//check if user has been activated
			if($avtive['user_active']!=1){
				header("Location: index.php?section=activate&userid=".$user['user_sid']."&".strip_tags(session_id()));
			}

			//hash the pass
			$pass		= hashValue($pass);

			//create submitted check string
			$user_check	= $pass.$user['user_sid'];

			//get stored check string
			$db_check	= $user['user_pass'].$user['user_sid'];

			if($user_check==$db_check){
				$sid 		= generateSid();

				//update timestamp and generate new sid
				$db->query(updateonLogin(generateTimestamp(),$sid,$id));
				//set cookie

				if($remember=='checked'){
					$this->setCookie($user,$pass);
				}

				//set session varialbles
				$_SESSION['id']			= $sid;
				$_SESSION['pid']		= $pass.$sid;
				$_SESSION['logedin']	= 1;
				$_SESSION['lid']		= hashValue($user['user_level']).$sid;

				// Existing user ok, continue
				header("Location: index.php?section=cms&".strip_tags(session_id()));	
				return true;

			}

		}else{
			// Login BAD
			$this->logout();
			header("Location: index.php?section=login&".strip_tags(session_id()));		
			return false;
		}
	}			
}
}	
?>

 

mysql.php//

<?php

function updateonLogin($timestamp,$sid,$id) {
$sql = 'UPDATE users SET users_sid = "'.$sid.'", users_timestamp = "'.$timestamp.'", users_ip = "'.$_SERVER['REMOTE_ADDR'].'" WHERE user_id = "'.$id.'" LIMIT 1';
return $sql;
}

function authCheck($sid) {
$sql = 'SELECT user_sid FROM users WHERE user_sid = "'.$sid.'" LIMIT 1';
return $sql;
}

function getActive($id) {
$sql = 'SELECT user_id FROM active_users WHERE user_id = "'.$id.'" LIMIT 1';
return $sql;
}

function selectByUser($user) {
$sql = 'SELECT user_name,user_level,user_sid,user_id,user_pass FROM users WHERE user_name = "'.addslashes($name).'" LIMIT 1';
return $sql;
}

function sessionAuth($sid) {
$sql = 'SELECT user_pass, user_lvl FROM users WHERE user_sid = "'.$sid.'" LIMIT 1';
return $sql;
}

function selectByEmail($email) {
$sql = 'SELECT user_name FROM users WHERE user_email = "'.addslashes($email).'" LIMIT 1';
return $sql;
}

function insertUser($user,$pass,$email,$sid,$time,$ip) {
$sql = 'INSERT INTO users (user_pass, user_name, user_level, user_email, timestamp, user_sid, user_ip) VALUES ("'.$pass.'","'.addslashes($user).'",1,"'.addslashes($email).'","'.$time.'","'.$sid.'","'.$ip.'")';
return $sql;
}

function userGetIdBySid($sid) {
$sql = 'SELECT user_id FROM users WHERE user_sid = "'.$sid.'" LIMIT 1';
return $sql;
}

function activateUser($id,$time) {
$sql = 'INSERT INTO users (user_id, timestamp) VALUES ("'.$id.'","'.$time.'")';
return $sql;
}

function newSid($id,$nid) {
$sql = 'UPDATE users SET users_sid = "'.$nid.'" WHERE user_id = "'.$id.'" LIMIT 1';
return $sql;
}

function ipBanCheck() {
$sql = 'SELECT * FROM banned_users WHRE user_ip = "'.$_SERVER['REMOTE_ADDR'].'" LIMIT 1';
return $sql;
}

function emailBanCheck($email) {
$sql = 'SELECT * FROM banned_users WHRE user_email = "'.addslashes($email).'" LIMIT 1';
return $sql;
}

function userBanCheck($name) {
$sql = 'SELECT * FROM banned_users WHRE user_name = "'.addslashes($name).'" LIMIT 1';
return $sql;
}
?>

 

for calling i am using a simple php template system with the variable $section

 

I have two pages login.tpl and process.tpl for handling the login

 

login.tpl//

<?php
if(isset($_COOKIE['pass'])){
require_once('inc/sentry.php');
$sentry	= new Sentry;
//validate login attempt
$sentry->checkLogin($_COOKIE['pass'],'10',$remember);
}
?>
<form method="post" id="registerForm" action="index.php?section=process&action=login">
	<table align="center" cellpadding="2" cellspacing="0" bgcolor="#FFFFFF">
		<tr>
			<td width="120">
				<div align="left"><strong>
					<label for="userid">UserID:</label>
				</strong></div>
			</td>
			<td>
				<div align="left" class="string">
					<input name="userid" type="text" class="input" id="userid" value="" size="32" />
				</div>
			</td>
		</tr>
		<tr>
			<td width="120">
				<div align="left"><strong>
					<label for="pass">Password:</label>
				</strong></div>
			</td>
			<td>
				<div align="left">
					<input name="pass" type="password" class="input" id="pass" value="" size="32" />
				</div>
			</td>
		</tr>
		<tr>
			<td colspan="3">
				<div align="right">
					<input type="image" name="register" class="submit-btn" src="http://www.roscripts.com/images/btn.gif" alt="submit" title="submit" />
				</div>
			</td>
		</tr>
	</table>
</form>

 

process.tpl//

<?php

$section=$_GET['action'];

switch($section){

case 'login':

	//get posted variables
	$user 		= $_POST['userid'];
	$pass 		= $_POST['pass'];

	require_once('inc/sentry.php');
	$sentry	= new Sentry;

	//validate login attempt
	$sentry->checkLogin($user,$pass,'10',$remember);

break;

case 'logout':

	require_once('inc/sentry.php');
	$sentry	= new Sentry;

	$sentry->logout();

break;

}
?>

 

on a success full login i am just including the words congradulations for now contained in a cms.tpl file

 

any help on how to improve, fix or go about this would be greatly appriciated. As I said this is my first attempt at oop in php so any tips and points are helpful as well.

 

thks

Sticky

Link to comment
Share on other sites

ok so i need to put the authentication before the html tags  ???

 

i reworked my sentry class seperating the login function into a login function a session authentication function and a cookie authentication function.

 

in the index.php file i include a new file called auth.inc.php that basically checks if the section is process. if so it checks the login.

 

else it checks if session varibles are set and validates the session if not it checks if cookies are set and validates them.

 

now i am given the following errors

 

Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in /home/sticky/public_html/cms/inc/db.php on line 96

 

Warning: Cannot modify header information - headers already sent by (output started at /home/sticky/public_html/cms/inc/db.php:96) in /home/sticky/public_html/cms/inc/sentry.php on line 167

 

i am still getting one header error, yet all of my processing is done prior to declaring the html tags.

 

its pointing to the last header relocation statement in my checkLogin function.

 

// Login BAD
$this->logout();
header("Location: index.php?section=login&".strip_tags(session_id()));		
return false;

 

as for the other error it does not like the following function for some reason even though its one directly from the tutorial i was following.

//*** Function: getNumRows, Purpose: Return row count, MySQL version ***
function getNumRows($result){
return mysql_num_rows($result);
}

can you help with this.

Link to comment
Share on other sites

  • 4 weeks later...
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.