Page 1 of 2

A really big problem! :(

Posted: Wed Feb 04, 2004 2:25 pm
by Think-Digitally
Hi, I have a big problem, which I have been trying to solve for a couple weeks now. I am not that experienced in PHP. So needing a good 'login' script I went for a PHP script. I used this tutorial : http://www.phpfreaks.com/tutorials/40/0.php everything works except the most important bit! You can log in and register, but whats the point when none of the pages stop you from entering them when you havent even joined!!!
I want the viewer to type in the URL and get redirected to the 'login' page if they are not logged in. If they are logged in then they can view the page.
I really need some help on this issue and will be really greatful if someone with some PHP knowledge could help me out.

Thankyou very much

Chris :D

Posted: Wed Feb 04, 2004 3:02 pm
by kettle_drum
I havent looked at the tutorial your refering to, but heres the simple idea of how it all works.

User registers -> store details in database

user logs in -> check password and username entered with those in database

If the passwords match for that user name, then either start a session or give the user a cookie.

Then on all other pages that only members can view, you need to check the session or the cookie to see if the user is logged in.

Code: Select all

if($user_logged_in){
   #show page here
}else{
   #redirect user with javascript/meta tags, or header() if no text has been sent
}

Posted: Wed Feb 04, 2004 3:05 pm
by teniosoft
try this

<?php
session_start();
if $logged_id <> "" {
include("content.txt");
} else {
header("location: login.php");
}

I do it a little fancier but this should do the trick for you. Then every secure page that you goto if the user is not logged in will give them the boot.


people could always access context.txt directly but, 90% will not. You can make it even more secure (I think) by changing content.txt to content.php
and including a

if $logged_in == "" {
header("location: login.php");

}

?>

Posted: Wed Feb 04, 2004 7:40 pm
by Michael 01
teniosoft wrote:try this

<?php
session_start();
if $logged_id <> "" {
include("content.txt");
} else {
header("location: login.php");
}

I do it a little fancier but this should do the trick for you. Then every secure page that you goto if the user is not logged in will give them the boot.


people could always access context.txt directly but, 90% will not. You can make it even more secure (I think) by changing content.txt to content.php
and including a

if $logged_in == "" {
header("location: login.php");

}

?>
Yes, it could be more secure using it as content.php. Just make teniosoft's example a global function as lets say..."myloginfunction" and have it included each time by doing this: require("myloginfunction.php"); at the beginning of each php script--before any code.

This way, there is no access to the page no matter what unless you are logged in. (cool example by the way teniosoft);

Thankyou for your help... but I cant get it to work...

Posted: Thu Feb 05, 2004 4:25 am
by Think-Digitally
Hi, thanks for all your help.

But it wont work. As I said before I am not that god at understanding PHP.
And this has just thrown me.

If tried to do this:

<?php
session_start();
if $logged_id <> "" {
include("db.php");
} else {
header("location: loginform.htm");
}
?>

in db.php... and then putting

<?php
if $logged_in == "" {
header("location: login.php");

}
?>

at the top of the pages I want to protect. When I uploaded the two documents, when I went to the page which I had tried to protect it just loaded as usual without logging in.

What am I doing wrong?

Thanks again

Chris

Posted: Thu Feb 05, 2004 5:36 am
by Think-Digitally
Hi again,

Below is what the writer of the script said after finishing the Tutorial.
I have tried it but cant seem to get it to work... please can someone help me with this, this script it useless if I dont have this small piece of script working :)

I forgot to add this little function.

If you wanted to check to see if a user is logged in on each page after following this tutorial, you could do this.

Write a function in a file that is included throughout your website. Inside this file, put:

function session_checker(){
if(!session_is_registered('first_name')){
include 'login_form.html';
exit();
}
}

and whenever you have a members only section, include the file and call this at the top of that page:

session_start();
session_checker();

It will validate the session, and if the appropriate session is not registered, it will exit your script leaving the login form in the user's browser.


Thanks again.
Chris

Posted: Thu Feb 05, 2004 6:23 am
by John Cartwright
try this on each page you want secure

if(!$user_logged_in){
header("location: login.php");
}

Posted: Thu Feb 05, 2004 6:33 am
by jason
Try reading through this:

viewtopic.php?t=6521

Specifically, page4 deals with protecting the pages people are logged into.

Also, c'mon guys, use the PHP or CODE bbcode tags. It makes it so much easier to read the code.

Posted: Thu Feb 05, 2004 8:06 am
by Think-Digitally
Hi, still cant fiqure it out :(
Maybe I a writting it wrong. So I will show how I have done it, and you can tell me what the hell I am doing wrong!!

I have made a new file called context.php and put this in it;

<?

function session_checker(){
if(!session_is_registered('first_name')){
include 'loginform.htm';
exit();
}
}

?>

exactly like that on its own in that file.

In the html document that I want to protect from viewers that are not logged in I have put this at the top before the <html> tag.

<?php

include 'context.php';

session_start();
session_checker();

?>

Please can someone tell me if this is right or not. This what the tutorial writter says to do.

Thanks
Chris

Posted: Thu Feb 05, 2004 10:45 am
by Think-Digitally
Can someone please help. I have a short amount of time to get this set up!

Thanks

Chris

Posted: Thu Feb 05, 2004 11:21 am
by jason
1. Please reread what I told you to read.
2. Please use the PHP or CODE bbcode tags when posting.

Doing both these things will help get a better response.

3. An emergency on your part does not constitute one on mine.

Finally, you might try running session_start() BEFORE using session code.

Posted: Thu Feb 05, 2004 12:20 pm
by Think-Digitally
Jason,

I took a read at the page your suggested, but I am a complete newbie to PHP and it all makes sense on that page. But I dont have a clue how I would make it work on my login script.

Can someone tell me If what I said in a couple messages above about what I had scripted, see if I have written correctly please?

Thankyou

Chris

Posted: Thu Feb 05, 2004 12:27 pm
by ol4pr0
WEll i can give you this... it does have a sign up method and all that..

you might be able to use some of that code.. to get youres working.

Code: Select all

<?php
//DATABASE.PHP

<?

/**
 * Connect to the mysql database.
 *
 * You should really change the _db name  $host , $user, and maby 
 * add a password 
 */

$conn = mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db('auth', $conn) or die(mysql_error());

?>
?>

Code: Select all

<?php
//LOGIN.PHP

<?

/**
 * Checks whether or not the given username is in the
 * database, if so it checks if the given password is
 * the same password in the database for that user.
 * If the user doesn't exist or if the passwords don't
 * match up, it returns an error code (1 or 2). 
 * On success it returns 0.
 */
function confirmUser($username, $password){
   global $conn;
   /* Add slashes if necessary (for query) */
   if(!get_magic_quotes_gpc()) {
	$username = addslashes($username);
   }

   /* Verify that user is in database */
   $q = "select password from users where username = '$username'";
   $result = mysql_query($q,$conn);
   if(!$result || (mysql_numrows($result) < 1)){
      return 1; //Indicates username failure
   }

   /* Retrieve password from result, strip slashes */
   $dbarray = mysql_fetch_array($result);
   $dbarray['password']  = stripslashes($dbarray['password']);
   $password = stripslashes($password);

   /* Validate that password is correct */
   if($password == $dbarray['password']){
      return 0; //Success! Username and password confirmed
   }
   else{
      return 2; //Indicates password failure
   }
}

/**
 * checkLogin - Checks if the user has already previously
 * logged in, and a session with the user has already been
 * established. Also checks to see if user has been remembered.
 * If so, the database is queried to make sure of the user's 
 * authenticity. Returns true if the user has logged in.
 */
function checkLogin(){
   /* Check if user has been remembered */
   if(isset($_COOKIE['cookname']) && isset($_COOKIE['cookpass'])){
      $_SESSION['username'] = $_COOKIE['cookname'];
      $_SESSION['password'] = $_COOKIE['cookpass'];
   }

   /* Username and password have been set */
   if(isset($_SESSION['username']) && isset($_SESSION['password'])){
      /* Confirm that username and password are valid */
      if(confirmUser($_SESSION['username'], $_SESSION['password']) != 0){
         /* Variables are incorrect, user not logged in */
         unset($_SESSION['username']);
         unset($_SESSION['password']);
         return false;
      }
      return true;
   }
   /* User not logged in */
   else{
      return false;
   }
}

/**
 * Determines whether or not to display the login
 * form or to show the user that he is logged in
 * based on if the session variables are set.
 */
function displayLogin(){
   global $logged_in;
   if($logged_in){
      echo "<h1>Logged In!</h1>";
      echo "Welcome <b>$_SESSION[username]</b>, you are logged in. <a href="logout.php">Logout</a>";
   }
   else{
?>

<h1>Login</h1>
<form action="" method="post">
<table align="left" border="0" cellspacing="0" cellpadding="3">
<tr><td>Username:</td><td><input type="text" name="user" maxlength="30"></td></tr>
<tr><td>Password:</td><td><input type="password" name="pass" maxlength="30"></td></tr>
<tr><td colspan="2" align="left"><input type="checkbox" name="remember">
<font size="2">Remember me next time</td></tr>
<tr><td colspan="2" align="right"><input type="submit" name="sublogin" value="Login"></td></tr>
<tr><td colspan="2" align="left"><a href="register.php">Crear una Account</a></td></tr>
</table>
</form>

<?
   }
}


/**
 * Checks to see if the user has submitted his
 * username and password through the login form,
 * if so, checks authenticity in database and
 * creates session.
 */
if(isset($_POST['sublogin'])){
   /* Check that all fields were typed in */
   if(!$_POST['user'] || !$_POST['pass']){
      die('You didn''t fill in a required field.');
   }
   /* Spruce up username, check length */
   $_POST['user'] = trim($_POST['user']);
   if(strlen($_POST['user']) > 30){
      die("Sorry, the username is longer than 30 characters, please shorten it.");
   }

   /* Checks that username is in database and password is correct */
   $md5pass = md5($_POST['pass']);
   $result = confirmUser($_POST['user'], $md5pass);

   /* Check error codes */
   if($result == 1){
      die('That username doesn''t exist in our database.');
   }
   else if($result == 2){
      die('Incorrect password, please try again.');
   }

   /* Username and password correct, register session variables */
   $_POST['user'] = stripslashes($_POST['user']);
   $_SESSION['username'] = $_POST['user'];
   $_SESSION['password'] = $md5pass;

   /**
    * This is the cool part: the user has requested that we remember that
    * he's logged in, so we set two cookies. One to hold his username,
    * and one to hold his md5 encrypted password. We set them both to
    * expire in 100 days. Now, next time he comes to our site, we will
    * log him in automatically.
    */
   if(isset($_POST['remember'])){
      setcookie("cookname", $_SESSION['username'], time()+60*60*24*100, "/");
      setcookie("cookpass", $_SESSION['password'], time()+60*60*24*100, "/");
   }

   /* Quick self-redirect to avoid resending data on refresh */
   echo "<meta http-equiv="Refresh" content="0;url=$HTTP_SERVER_VARS[PHP_SELF]">";
   return;
}

/* Sets the value of the logged_in variable, which can be used in your code */
$logged_in = checkLogin();

?>

?>

Code: Select all

<?php
//LOGOUT.PHP

<?
session_start(); 
include("database.php");
include("login.php");

/**
 * Delete cookies - the time must be in the past,
 * so just negate what you added when creating the
 * cookie.
 */
if(isset($_COOKIE['cookname']) && isset($_COOKIE['cookpass'])){
   setcookie("cookname", "", time()-60*60*24*100, "/");
   setcookie("cookpass", "", time()-60*60*24*100, "/");
}

?>

<html>
<title>Logging Out</title>
<body>

<?

if(!$logged_in){
   echo "<h1>Error!</h1>\n";
   echo "You are not currently logged in, logout failed. Back to <a href="main.php">main</a>";
}
else{
   /* Kill session variables */
   unset($_SESSION['username']);
   unset($_SESSION['password']);
   $_SESSION = array(); // reset session array
   session_destroy();   // destroy session.

   echo "<h1>Logged Out</h1>\n";
   echo "You have successfully <b>logged out</b>. Back to <a href="main.php">main</a>";
}

?>

</body>
</html>

?>

Code: Select all

<?php
// MAIN.PHP 

<? 
/* Include Files *********************/
session_start(); 
include("database.php");
include("login.php");
/*************************************/
?>

<html>
<title>LOGIN</title>
<body>

<? displayLogin(); ?>

</body>
</html>


?>

Code: Select all

<?php
// MAIN2.PHP

<? 
/* Include Files *********************/
session_start(); 
include("database.php");
include("login.php");
/*************************************/
?>

<html>
<title>LOGIN</title>
<body>

<? 
if($logged_in){
   echo 'Logged in as '.$_SESSION['username'].', <a href="logout.php">logout</a>';
}else{
   echo 'Not logged in.';
}
?>

</body>
</html>


?>

Code: Select all

<?php
//REGISTER.PHP

<?
session_start(); 
include("database.php");

/**
 * Returns true if the username has been taken
 * by another user, false otherwise.
 */
function usernameTaken($username){
   global $conn;
   if(!get_magic_quotes_gpc()){
      $username = addslashes($username);
   }
   $q = "select username from users where username = '$username'";
   $result = mysql_query($q,$conn);
   return (mysql_numrows($result) > 0);
}

/**
 * Inserts the given (username, password) pair
 * into the database. Returns true on success,
 * false otherwise.
 */
function addNewUser($username, $password){
   global $conn;
   $q = "INSERT INTO users VALUES ('$username', '$password')";
   return mysql_query($q,$conn);
}

/**
 * Displays the appropriate message to the user
 * after the registration attempt. It displays a 
 * success or failure status depending on a
 * session variable set during registration.
 */
function displayStatus(){
   $uname = $_SESSION['reguname'];
   if($_SESSION['regresult']){
?>

<h1>Registered!</h1>
<p>Thank you <b><? echo $uname; ?></b>, your information has been added to the database, you may now <a href="main.php" title="Login">log in</a>.</p>

<?
   }
   else{
?>

<h1>Registration Failed</h1>
<p>We're sorry, but an error has occurred and your registration for the username <b><? echo $uname; ?></b>, could not be completed.<br>
Please try again at a later time.</p>

<?
   }
   unset($_SESSION['reguname']);
   unset($_SESSION['registered']);
   unset($_SESSION['regresult']);
}

if(isset($_SESSION['registered'])){
/**
 * This is the page that will be displayed after the
 * registration has been attempted.
 */
?>

<html>
<title>Registration Page</title>
<body>

<? displayStatus(); ?>

</body>
</html>

<?
   return;
}

/**
 * Determines whether or not to show to sign-up form
 * based on whether the form has been submitted, if it
 * has, check the database for consistency and create
 * the new account.
 */
if(isset($_POST['subjoin'])){
   /* Make sure all fields were entered */
   if(!$_POST['user'] || !$_POST['pass']){
      die('You didn''t fill in a required field.');
   }

   /* Spruce up username, check length */
   $_POST['user'] = trim($_POST['user']);
   if(strlen($_POST['user']) > 30){
      die("Sorry, the username is longer than 30 characters, please shorten it.");
   }

   /* Check if username is already in use */
   if(usernameTaken($_POST['user'])){
      $use = $_POST['user'];
      die("Sorry, the username: <strong>$use</strong> is already taken, please pick another one.");
   }

   /* Add the new account to the database */
   $md5pass = md5($_POST['pass']);
   $_SESSION['reguname'] = $_POST['user'];
   $_SESSION['regresult'] = addNewUser($_POST['user'], $md5pass);
   $_SESSION['registered'] = true;
   echo "<meta http-equiv="Refresh" content="0;url=$HTTP_SERVER_VARS[PHP_SELF]">";
   return;
}
else{
/**
 * This is the page with the sign-up form, the names
 * of the input fields are important and should not
 * be changed.
 */
?>

<html>
<title>Registration Page</title>
<body>
<h1>Register</h1>
<form action="<? echo $HTTP_SERVER_VARS['PHP_SELF']; ?>" method="post">
<table align="left" border="0" cellspacing="0" cellpadding="3">
<tr><td>Username:</td><td><input type="text" name="user" maxlength="30"></td></tr>
<tr><td>Password:</td><td><input type="password" name="pass" maxlength="30"></td></tr>
<tr><td colspan="2" align="right"><input type="submit" name="subjoin" value="Join!"></td></tr>
</table>
</form>
</body>
</html>


<?
}
?>

?>
have fun...

Posted: Thu Feb 05, 2004 1:20 pm
by Think-Digitally
Thanks ol4pr0
I have tried everything...
But I still cant get it to work.

Maybe I should just use a different script. Does anyone know of a good login script, that has self registration, e-mail verification, lost password and logout functions?

Posted: Thu Feb 05, 2004 1:23 pm
by malcolmboston
just create one, they're easy really. just read this here

doing it yourself will allow you to customise it much easier, which you will be glad of if you are not experienced with PHP, as sifting through other people code can become a nightmare (look at phpBB code :roll: )