Jump to content

User Authentication After Login


Paul De Meulenaer

Recommended Posts

Hello,

 

I am quite new to PHP and MYSQL, I created a login/registration area on my home page.

All is working well on the home page, but now I want to make sure that users are logged in before they can access the content of all other pages.

 

Here is the code on the home page:

<?php

define('INCLUDE_CHECK',true);

require 'connect.php';
require 'functions.php';
// Those two files can be included only if INCLUDE_CHECK is defined


session_name('tzLogin');
// Starting the session

session_set_cookie_params(2*7*24*60*60);
// Making the cookie live for 2 weeks

session_start();

if($_SESSION['id'] && !isset($_COOKIE['tzRemember']) && !$_SESSION['rememberMe'])
{
// If you are logged in, but you don't have the tzRemember cookie (browser restart)
// and you have not checked the rememberMe checkbox:

$_SESSION = array();
session_destroy();

// Destroy the session
}


if(isset($_GET['logoff']))
{
$_SESSION = array();
session_destroy();

header("Location: default.php");
exit;
}

if($_POST['submit']=='Login')
{
// Checking whether the Login form has been submitted

$err = array();
// Will hold our errors


if(!$_POST['username'] || !$_POST['password'])
	$err[] = 'All the fields must be filled in!';

if(!count($err))
{
	$_POST['username'] = mysql_real_escape_string($_POST['username']);
	$_POST['password'] = mysql_real_escape_string($_POST['password']);
	$_POST['rememberMe'] = (int)$_POST['rememberMe'];

	// Escaping all input data

	$row = mysql_fetch_assoc(mysql_query("SELECT id,usr FROM tz_members WHERE usr='{$_POST['username']}' AND pass='".md5($_POST['password'])."'"));

	if($row['usr'])
	{
		// If everything is OK login

		$_SESSION['usr']=$row['usr'];
		$_SESSION['id'] = $row['id'];
		$_SESSION['rememberMe'] = $_POST['rememberMe'];

		// Store some data in the session

		setcookie('tzRemember',$_POST['rememberMe']);
	}
	else $err[]='Wrong username and/or password!';
}

if($err)
$_SESSION['msg']['login-err'] = implode('<br />',$err);
// Save the error messages in the session

header("Location: default.php");
exit;
}
else if($_POST['submit']=='Register')
{
// If the Register form has been submitted

$err = array();

if(strlen($_POST['username'])<4 || strlen($_POST['username'])>32)
{
	$err[]='Your username must be between 3 and 32 characters!';
}

if(preg_match('/[^a-z0-9\-\_\.]+/i',$_POST['username']))
{
	$err[]='Your username contains invalid characters!';
}

if(!checkEmail($_POST['email']))
{
	$err[]='Your email is not valid!';
}

if(!count($err))
{
	// If there are no errors

	$pass = substr(md5($_SERVER['REMOTE_ADDR'].microtime().rand(1,100000)),0,6);
	// Generate a random password

	$_POST['email'] = mysql_real_escape_string($_POST['email']);
	$_POST['username'] = mysql_real_escape_string($_POST['username']);
	// Escape the input data


	mysql_query("	INSERT INTO tz_members(usr,pass,email,regIP,dt)
					VALUES(

						'".$_POST['username']."',
						'".md5($pass)."',
						'".$_POST['email']."',
						'".$_SERVER['REMOTE_ADDR']."',
						NOW()

					)");	

	//The message
	$username = $_POST['username'];
	$message =
	"Hello \n
Thank you for registering with us. \n
Here are your login details: \n

Username: $username \n
Password: $pass \n

Thank You

Administrator
www.expatcafe.com
______________________________________________________
THIS IS AN AUTOMATED RESPONSE.
***DO NOT RESPOND TO THIS EMAIL***";

	if(mysql_affected_rows($link)==1)
	{
		send_mail(	'admin@expatcafe.com',
					$_POST['email'],
					'Registration System - Your New Password',
					$message);

		$_SESSION['msg']['reg-success']='We sent you an email with your new password!';
	}
	else $err[]='This username is already taken!';
}

if(count($err))
{
	$_SESSION['msg']['reg-err'] = implode('<br />',$err);
}	

header("Location: default.php");
exit;
}

 

How to check if user is logged in on other pages before they can access this info?

 

Thanks a lot.

Edited by PFMaBiSmAd
code in code tags please
Link to comment
Share on other sites

what are the content in default.php

 

The content is a general welcome and states what the website is about, everyone is welcome to read it. I want to protect all other pages. Now everyone can see the content on the other pages logged in or not. I want that only logged in users can see the content of the other pages, otherwise they should stay on the default.php.

 

Thank you.

Link to comment
Share on other sites

I will give you a simple soluton...

 

Display your main navigation according to your login condition...

 

eg :

 

if ( login true ) {

 

whole navigation... (home, test1, test2, and so on... )

 

} else {

 

custom navigaton... (home, contact)

 

}

Link to comment
Share on other sites

I will give you a simple soluton...

 

Display your main navigation according to your login condition...

 

eg :

 

if ( login true ) {

 

whole navigation... (home, test1, test2, and so on... )

 

} else {

 

custom navigaton... (home, contact)

 

}

 

I want to try your solution, where do I put this in my code? In the header? Or in the body? and what do I need to put in the code of the other pages?

 

Thank you.

Link to comment
Share on other sites

simply you can put the code into your home page. There you need to check weather login is true or not.

 

In this case you can use something like this code to check the login true or not...

 

if (isset($_SESSION['usr']) && ($_SESSION['id'] == ........ )) { 
 //here you can display page navigations that you want to display after user loged in to the system..
} else {
  //default navigation, user is not loged into the system..\
}

Link to comment
Share on other sites

^^ Exactly like the colleague above suggested but I usually create a separate file for example protected.php and include it on the top of the page I want to protect basically.

 

Inside the file I write this

 

if(isset($_SESSION['user_id']) and !empry($_SESSION['user_id'])){
// do nothing
return true;
}else{
die('You be must be logged in to see this page');
return false;
}

 

You really do not need to write a return statement, I just did it to clarify stuff

Edited by Stefany93
Link to comment
Share on other sites

Just to clear up your code a bit, Stefany93, to remove some unnecessary/unused code:

if(isset($_SESSION['user_id']) and !empry($_SESSION['user_id'])){
   // do nothing
   return true;
}

die('You be must be logged in to see this page');

 

The else would never be necessary because of the return within the IF-block, the last return wouldn't be executed at all because of the die () just prior to it.

Link to comment
Share on other sites

Hello everyone,

 

Thank you for viewing my post and giving me some options.

 

After some more reviewing, I have found a 'working' solution.

 

I just had to add:

 

<?php

 

session_name('tzLogin');

session_set_cookie_params(2*7*24*60*60);

session_start();

?>

 

on top of every 'protected' page.

 

Once again thanks.

Link to comment
Share on other sites

Just to clear up your code a bit, Stefany93, to remove some unnecessary/unused code:

if(isset($_SESSION['user_id']) and !empry($_SESSION['user_id'])){
// do nothing
return true;
}

die('You be must be logged in to see this page');

 

The else would never be necessary because of the return within the IF-block, the last return wouldn't be executed at all because of the die () just prior to it.

 

That's a better solution. Thank you Chris!

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.