munk.me.uk forum
May 21, 2012, 04:59:47 am *
Welcome, Guest. Please login or register.

Login with username, password and session length
News: SMF - Just Installed!
 
   Home   Help Search Login Register  
Pages: [1]   Go Down
  Print  
Author Topic: SimpleAuth FAQ  (Read 6737 times)
munk
Administrator
Sr. Member
*****

Karma: +2/-0
Offline Offline

Posts: 368


View Profile WWW
« on: September 26, 2035, 06:44:13 pm »

This topic is dedicated to the list of Frequently Asked Questions and their answers.  

Please do not reply to this topic unless you are submitting a FAQ together with it's answer.
Logged

~ Jez
munk
Administrator
Sr. Member
*****

Karma: +2/-0
Offline Offline

Posts: 368


View Profile WWW
« Reply #1 on: January 18, 2004, 05:09:12 pm »

How do I enable authentication on my own pages using SimpleAuth?
At the top of the page you want to protect/require users to authenticate before accessing, include the simpleauth config.php script and then call the function 'checkLoggedIn();' with the argument 'yes' to check that the user has logged in.  The code for this is as follows:

Code:
// This presumes 'config.php' is in the same directory
// as the page you are protecting - modify the path if your config.php file is
// in a different location:
include_once("config.php");

// Check user logged in already:
checkLoggedIn("yes");

This code includes the 'config.php' file.  In turn the config.php file includes the functions.php file which contains the function 'checkLoggedIn()'.  We can then use the 'checkLoggedIn()' function to check that 'yes' the user is logged in.  If the user is logged in, the page will continue to load - otherwise the user will be redirected to the login.php page.

You can place your protected page content below the 'checkLoggedIn("yes");' line to ensure that your user's are logged in before they can view that page.

EDIT:
The following tip has also been submitted by lowrykun - thanks for that Tongue

Quote
If you are new to PHP (or web design in general) its best to maintain a group of header & footer files and include those in your web-pages. Generally these would be used to maintain a consistant look & feel across your site and also allow you to make changes to the look of the site in one place. If the secure pages of your site have a different header, then add:

Code:
include (config.php);
checkLoggedIn("yes");

to the secure header file. Otherwise, just include it in all the pages that you want to be secure.
« Last Edit: January 19, 2004, 09:04:54 pm by munk » Logged

~ Jez
munk
Administrator
Sr. Member
*****

Karma: +2/-0
Offline Offline

Posts: 368


View Profile WWW
« Reply #2 on: January 18, 2004, 05:30:04 pm »

How do I add extra security to SimpleAuth?
For a discussion on the way SimpleAuth stores passwords in plaintext, see here (thanks lowrykun:P).

To avoid storing user's passwords in the database in plaintext, you can use the PHP md5() function to hash the passwords as you store your user's passwords in the database.  You also need to use the md5() function again when you log your users in - hashing the password string they provide using md5() and then comparing it to the hashed password string stored in the db.

To do this you should modify the newUser() and checkPass() functions in functions.php to read:

Code:
function newUser($login, $password) {
/*
Creating a New User Record in the DB:
In this function we create a new user record in the db.

We first build a query and save it into the $query variable.
The query statement says:

'Insert the value of $login and $password into the 'login'
and 'password' columns in the 'users' table'
*/

global $link;

// Use md5() so we don't store the user passwords in plaintext:
$query="INSERT INTO users (login, password) VALUES('$login', '".md5($password)."')";
$result=mysql_query($query, $link) or die("Died inserting login info into db.  Error returned if any: ".mysql_error());

return true;
} // end func newUser($login, $pass)

Code:
function checkPass($login, $password) {
/*
Password checking function:
This is a simple function that takes the $login name and
$password that a user submits in a form and checks that a
row exists in the database where:

the value of the 'login' column is the same as the value in $login
and
the value of the 'password' column is the same as the value in $password

If exactly one row is returned, then that row of data is returned.
If no row is found, the function returns 'false'.
*/
global $link;

// Using MD5 hashed password strings:
$query="SELECT login, password FROM users WHERE login='$login' and password='".md5($password)."'";
$result=mysql_query($query, $link)
  or die("checkPass fatal error: ".mysql_error());

// Check exactly one row is found:
if(mysql_num_rows($result)==1) {
  $row=mysql_fetch_array($result);
  return $row;
}
//Bad Login:
return false;
} // end func checkPass($login, $password)

Finally modify the database table the password strings are stored in to make sure the md5 hashed password will fit - md5() hashed strings are 33 characters long instead of just 15 which the original password field was set to.  

Assuming you're using the original database table included in simpleauth, the following SQL statement will modify the password field to fit the 33 character md5 hashes.  Execute this in a mysql client on the database you setup simpleauth on:

Code:
alter table users change password password varchar(33);

Now any users that register will have their passwords stored in the database with md5 hashing.


IMPORTANT:
Note that any passwords already stored in the database will no longer work.
« Last Edit: March 03, 2006, 10:59:59 pm by munk » Logged

~ Jez
munk
Administrator
Sr. Member
*****

Karma: +2/-0
Offline Offline

Posts: 368


View Profile WWW
« Reply #3 on: January 18, 2004, 05:43:03 pm »

How can I add a page to view all the currently registered members?
I have written an additional script called profile.php to display a list of all registered simpleauth members together with their details.  The source code can be viewed here:

Download Member Profile Script profile.php For SimpleAuth

Copy and paste this into a file called 'profile.php' (or download and rename to profile.php), ensuring the script is in the same directory as the other simpleauth files.

You can see a demo of the script here:

http://simpleauth.munk.me.uk/profile.php

Warning: requires database modification
« Last Edit: February 16, 2007, 01:40:15 pm by munk » Logged

~ Jez
munk
Administrator
Sr. Member
*****

Karma: +2/-0
Offline Offline

Posts: 368


View Profile WWW
« Reply #4 on: January 18, 2004, 05:52:24 pm »

How can I allow my users to add extra items to their profile such as email address, MSN name, ICQ UIN, etc?
Use the profile.php script mentioned above, setting the GET variable 'action' to "displayProfileForm".  For logged in users, this will display a form allowing the user to modify various profile options.

To set the GET variable as described above, your link should look something like this - modify to reflect your domain name and path to your profile.php script:

Code:
<a href="http://www.example.com/profile.php?action=displayProfileForm">Modify User Profile</a>

This link should be placed somewhere on your members default home page (ie members.php) to allow them to modify their profile.

Warning: requires database modification
Logged

~ Jez
munk
Administrator
Sr. Member
*****

Karma: +2/-0
Offline Offline

Posts: 368


View Profile WWW
« Reply #5 on: February 27, 2004, 12:09:43 am »

How can I add 'remember me' functionality to simpleauth?
This is tested working on simpleauth-1.2.  AFter completing the following steps, when a user checks the 'remember me' checkbox in the login form, providing they have cookies enabled they will remain logged in across browser sessions.

The method stores the user's login name and md5 hashed password into a cookie called 'simpleauth'.  When the checkLoggedIn() function is called, we check to see if a simpleauth cookie exists - if it does then we check to see if the md5 hashed password of the cookie user matches the password hash stored in the cookie - if so then create a clean member session with the data - otherwise set $_SESSION["loggedIn"] to false.

Modifications required follow below - in general copy/paste anything in between -snip- marks:

Add a 'remember me' checkbox to the login form in the login.php script:

Code:
<tr><td>Password:</td><td><input type="password" name="password" value="" maxlength="15"></td></tr>
-snip-
<tr><td>Remember Me:</td><td><input type="checkbox" name="remember" <?php isset($_POST["remember"]) && $_POST["remember"] === "on" && print "checked"?>> (requires cookies)</td></tr>
-snip-
<tr><td>&nbsp;</td><td><input name="submit" type="submit" value="Submit"></td></tr>


Add the following to the cleanMemberSession() function in functions.php:

Code:
   $_SESSION["login"]=$login;
    $_SESSION["password"]=$password;
    $_SESSION["loggedIn"]=true;

-snip-
    // Check if 'remember me' checkbox is set:
    if(isset($_POST["remember"]) && $_POST["remember"] === "on"){
        // Set a cookie containing user data:
        $tmp=array(
            "login"=>$login,
            "passwd"=>md5($password)
        );
        setcookie("simpleauth", serialize($tmp), time()+60*60*24*365);
    }
-snip-


Add the following to the flushMemberSession() function in functions.php:

Code:
   // and use session_destroy to destroy all data associated
    // with current session:
    session_destroy();

-snip-
    // Check if a cookie is set:
    if(isset($_COOKIE["simpleauth"])){
        // Remove the cookie:
        setcookie("simpleauth", "", time()-999);
        unset($_COOKIE["simpleauth"]);
    }
-snip-


Add the following at the top of the 'checkLoggedIn()' function:

Code:
function checkLoggedIn($status){
-snip-
    global $link;

    /*
    Function to check whether a user is logged in or not:
    This is a function that checks if a user is already logged
    in or not, depending on the value of $status which is passed
    in as an argument.

    If $status is 'yes', we check if the user is already logged in;
    If $status is 'no', we check if the user is NOT already logged in.
    */
    // First check if cookie exists:
    if(isset($_COOKIE["simpleauth"])){
        // Unserialize data:
        $tmp=unserialize(stripslashes($_COOKIE["simpleauth"]));

        // Check if stored login details match those in cookie:
        $query="SELECT password FROM users WHERE login='".$tmp["login"]."'";
        $result=mysql_query($query, $link)
            or die("checkLoggedIn fatal error: ".mysql_error());

        // Check exactly one row is found:
        if(mysql_num_rows($result)!==1) {
            // if more than one entry something messed up:
            $_SESSION["loggedIn"]=false;
        } else {
            // fetch the row containing the user's password:
            $row=mysql_fetch_array($result);

            // Check passwords match:
            if($tmp["passwd"]===md5($row["password"])){
                // yes they match, carry on and make clean
                // member session:
                cleanMemberSession($tmp["login"], $row["password"]);
            }
        }
    }
-snip-
    switch($status){

If you're familiar with Unix and the patch utility, there's a patch here that you can apply whilst in the original simpleauth-1.2 directory that makes the changes necessary (make sure no changes have been made to functions.php or login.php or it wont work).  To apply the patch from the Unix command-line:

Code:
cd /path/containing/simpleauth-1.2/
patch < /path/containing/simpleauth-cookies.patch

The patch file is attached to this post.
« Last Edit: February 27, 2004, 08:06:33 pm by munk » Logged

~ Jez
munk
Administrator
Sr. Member
*****

Karma: +2/-0
Offline Offline

Posts: 368


View Profile WWW
« Reply #6 on: March 05, 2004, 10:55:17 pm »

What version of PHP do I need to run SimpleAuth?
SimpleAuth requires PHP version 4.1.0 or greater to run.  This is because the code makes use of the so-called 'superglobal' variables that were introduced in version 4.1.0 - see here for more information about PHP's predefined variables that were introduced in version 4.1.0.

Symptoms that might suggest you're running the wrong version of PHP for simpleauth include messages such as:

Warning: Undefined variable: _SERVER in ...

although _SERVER may be replaced with _SESSION or another super-global variable that starts with the underscore character (_).
« Last Edit: January 19, 2007, 04:02:03 am by munk » Logged

~ Jez
munk
Administrator
Sr. Member
*****

Karma: +2/-0
Offline Offline

Posts: 368


View Profile WWW
« Reply #7 on: February 23, 2006, 05:44:34 pm »

What does the error message 'Notice: Undefined index:' or an error message starting with 'Warning: ' mean?
These are PHP non-fatal warnings which are a result of error reporting being set high in the php.ini file usually.  They are not fatal error messages - fatal error messages are those that actually terminate the execution of a PHP script, stopping it dead in it's tracks.  The warning messages we're talking about here allow the script to continue executing.

So what is the point in these messages?  PHP allows you to set the 'sensitivity' of it's error reporting system in various places, the most common being the php.ini file on your webserver.  In this way you get to see more or less error messages depending on how you set the value 'error_reporting' in php.ini. 

Turning the error reporting level up is useful when you're developing an application and want to make sure absolutely all your coding problems are smoothed out.  This makes it easier to fix problems quickly.

On the other hand turning the error reporting level right down is useful when you have an application that is completed and is actually 'live' on a production server and you want to suppress any errors from being displayed to users.  Having error messages displayed on a production server can be bad because it gives away the location of your scripts on your webserver, giving malicious users a clue as to how your files are organized and making it slightly easier to do bad things ™.  In this case it makes sense to either turn error_reporting right off or much better have all errors saved to a logfile instead of output to the web browser.

So how do we turn the warning/notice messages off?  Ideally the best thing to do is find the problem and fix it of course.  There's a thread here about error_reporting levels which goes over fixing the most common problem of 'undefined variable/index'. 

However if you don't mind these minor errors and don't want to fix them, you can suppress them in various ways.  The easiest way to do this is by changing the error_reporting value in the php.ini file.  To modify error reporting on a script by script basis alternatively you can use the error_reporting() function.  There may also be other places you can modify the error_reporting value - for example in a .htaccess file on an Apache webserver. If you use a shared hosting server, the best thing to do is ask your server admin for more info.

The default php.ini file contains a lot of useful information about error_reporting - essentially though to suppress the messages change the error_reporting line so it reads:

Code:
error_reporting  =  E_ALL & ~E_NOTICE

Here is a snippet from the default php.ini file which contains a lot of useful info about error reporting in PHP:

Quote
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Error handling and logging ;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

; error_reporting is a bit-field.  Or each number up to get desired error
; reporting level
; E_ALL             - All errors and warnings
; E_ERROR           - fatal run-time errors
; E_WARNING         - run-time warnings (non-fatal errors)
; E_PARSE           - compile-time parse errors
; E_NOTICE          - run-time notices (these are warnings which often result
;                     from a bug in your code, but it's possible that it was
;                     intentional (e.g., using an uninitialized variable and
;                     relying on the fact it's automatically initialized to an
;                     empty string)
; E_CORE_ERROR      - fatal errors that occur during PHP's initial startup
; E_CORE_WARNING    - warnings (non-fatal errors) that occur during PHP's
;                     initial startup
; E_COMPILE_ERROR   - fatal compile-time errors
; E_COMPILE_WARNING - compile-time warnings (non-fatal errors)
; E_USER_ERROR      - user-generated error message
; E_USER_WARNING    - user-generated warning message
; E_USER_NOTICE     - user-generated notice message
;
; Examples:
;
;   - Show all errors, except for notices
;
;error_reporting = E_ALL & ~E_NOTICE
;
;   - Show only errors
;
;error_reporting = E_COMPILE_ERROR|E_ERROR|E_CORE_ERROR
;
;   - Show all errors except for notices
;
error_reporting  =  E_ALL & ~E_NOTICE

Finally of course the PHP manual has a lot of information on how PHP handles error reporting and how you can manipulate error reporting:

The error_reporting() function - for setting error reporting levels at script runtime.

The error_reporting php.ini setting - easiest way to set error reporting level server wide.

The display_errors php.ini setting - whether or not error messages are displayed in a browser.

The log_errors php.ini setting - for sending all php error messages to a logfile.
« Last Edit: January 19, 2007, 04:01:31 am by munk » Logged

~ Jez
munk
Administrator
Sr. Member
*****

Karma: +2/-0
Offline Offline

Posts: 368


View Profile WWW
« Reply #8 on: January 19, 2007, 03:13:09 am »

I get the error message 'headers already sent'.  What does this mean?

This error means that the script attempted to send out a HTTP header after something was already displayed in the browser.

A typical HTTP session from the server's point of view involves:

  • Sending out HTTP headers - including info about when the page was last modified, whether the browser should cache the page and importantly for simpleauth, session data for PHP.
  • Sending out the actual data that will be displayed in the browser.

Now, if the server tries to send out a HTTP header AFTER it's already sent out data to be displayed in the browser, this causes an error (since the header info has to be sent in one go at the start).

To fix the problem you need to find out where something is being printed to the browser BEFORE all the HTTP headers have been sent and then make sure it doesn't output anything until the headers have been sent.

One not so obvious gotcha is because an include file that you include from a script contains a blank line after the last ?> in it.  The blank line is effectively sent to the browser as HTML data when you didn't mean it to be - those lines should be removed.
« Last Edit: January 19, 2007, 03:18:41 am by munk » Logged

~ Jez
Pages: [1]   Go Up
  Print  
 
Jump to:  

Powered by MySQL Powered by PHP Powered by SMF 1.1.13 | SMF © 2006-2011, Simple Machines LLC Valid XHTML 1.0! Valid CSS!