The Information Technology Blog brought to you by 4 Ace Technologies

Thursday, April 30, 2009

Mini Free Icons for your Website

Free Icons for website such as email icon, website icon, cancel icon, flash icon, dreamweaver icon and other icons can be found here:

http://famfamfam.com/lab/icons/mini

Saturday, April 25, 2009

Unit Testing in Drupal

Extract from: http://www.lullabot.com/articles/introduction-unit-testing

Unit testing is the art and practice of taking a small portion of code, a unit, and subjecting it to programmatic tests to prove its correctness. The smallest units in PHP code are usually functions, and the unit tests will run the functions with sets of controlled parameters, and then make assertions about the return values of the function, or about the state of the application before and after the function has run. For example, if the function is designed to validate email addresses, the unit tests would pass in known valid email addresses and assert that they validate correctly. The tests would also pass in a number of invalid email addresses as well and assert that they do not validate.

Why is unit testing useful?

Writing unit tests helps produce higher quality code on many levels.

  • The availability of tests helps detect the introduction of bugs whenever the programmer adds new features or refactors the code. This is called regression testing.
  • Tests also serve as a source of documentation about what code is really expected to do.
  • The act of writing the tests challenges the programmer to consider possible edge cases and their consequences.
  • Last but not least, the act of writing tests encourages the programmer to write code in small chunks that can be tested independently.

The last point is worth diving into. If we are writing code that needs to do three manipulations to an incoming string, the temptation is to write a function where the string comes in as an argument, the three manipulations are executed, and the resulting string is returned. When this function isn't working right it is hard to determine which of the three manipulations are failing. Your test case can only send a string in and compare the result with the expected result. How can you know which of the manipulations isn't working correctly? Breaking the function into smaller pieces, one for each manipulation, results in code that is easier to test. Test cases can then be written for each manipulation, better isolating the source of failure.

Unit tests can be often be scripted to run automatically, making them an ideal part of your development, build, and deployment process. You can run tests before committing new code to the repository. You can run the tests after adding new modules and thus ensure that previous functionality hasn't been compromised. You can run tests after deploying changes from a development environment to a staging environment thus cutting down on the dependency of trial and error to detect problems.

What testing tools does Drupal offer?

The principal tool for unit testing in drupal is the Simpletest module. This module is a Drupal extension to the Simpletest project for general PHP unit testing. The Drupal module adds a wealth of tools and convenience for Drupal specific unit testing. For example, it has the ability to create new users and nodes, set configuration variables, and submit Drupal forms.

As an addition to the Simpletest module there is the Simpletest automation project which provides a system for running test suites automatically and reporting the results. The Simpletest automation is also capable of applying patches to Drupal code, and is thus an essential tool for vetting patches in the issue queue.

The similarly named but very different Simpletest automator extends the convenience of writing tests even further by allowing you to click through your site as it records your actions as a macro. This macro can then be used as the basis for a unit test that you can run automatically at a later time.

How to set up the Simpletest module

To begin running unit tests on your Drupal installation, download the latest release of the Simpletest module and install it as you would any other module. Please note that you should not install this module on a production site. It is only designed for development and staging purposes, and running the tests will alter the state of your database. Running the simpletest unit tests on a production site could lead to lost data or unpredictable behavior.

The Drupal module depends on the Simpletest library, which you can download from Sourceforge.net. The latest release, as of this writing, is simpletest_1.0.1beta2. The download from Sourceforge comes as a tarball which you need to extract into the simpletest module directory. The resulting directory structure looks like this.

simpletest-directory-structure-graffle.png

That concludes the installation of the Simpletest module, and you are now ready to run the existing unit tests.

How to run the included tests

The existing unit tests can be found under Administer->Site building->Simpletest unit testing (admin/build/simpletest). This page is a listing of all the test suites that are installed. The bulk of them come from the Simpletest module itself, and are used to test Drupal core functionality. Since it is possible for any module to provide test suites it is entirely possible that some of the contributed modules you have installed will also have test suites. Some modules that include test cases are the coder, organic groups and timeline modules.

The Simpletest unit testing page allows you to select all of the tests in any group, or, if you expand the Tests fieldset in any group, the single tests individually. Select the Run selected tests option at the bottom and click Begin, and Simpletest will do its work. Depending on how many tests you've chosen, the running time may be anywhere from a couple of seconds to minutes. Here I am about to run all of the tests in the "Node tests" group.

node-tests-selected.png

Here is the output generated by running all of the tests in the Node tests group.

test-results-graffle.png

What to do if you get errors

The beauty of having unit tests available is that it makes error reporting much easier. If you run the test suites for Drupal core or a contributed module and get Fails, you have a great opportunity to use the Drupal.org issue queue to file a bug report. Paste the output from Simpletest into the issue and the module maintainer will know exactly what it is that went wrong. Be sure to include the ordinary information about your Drupal installation, including what release you are running and what modules you have installed.

How to write a basic unit test

Unit testing is a great productivity enhancer for programmers and I highly recommend using it as a core technique whenever you write code. Your code will come together quicker and will be higher quality for the effort. Adding unit test support to your Drupal module is easy. Simpletest defines hook_simpletest which your module implements.

/**
* Implementation of hook_simpletest().
*/
function hook_simpletest() {
$module_name = 'mymodule'; // Change this to your module name.
$dir = drupal_get_path('module', $module_name). '/tests';
$tests = file_scan_directory($dir, '\.test$');
return
array_keys($tests);
}
?>

The hook returns a list of files that contain test cases. The convention is to make a tests directory in your module and put the test cases in there. If you follow the convention then you only need to copy the code above and change the function name and update the $module_name variable to be the name of your module.

Now you can start to create test cases. These files should have the ending .test and reside in the tests directory in your module. The stub code for a test case looks like this:

class PageViewTest extends DrupalTestCase {

function
get_info() {
return array(
'name' => t('Page node creation'),
'desc' => t('Create a page node and verify its consistency in the database.'),
'group' => t('Node Tests'),
);
}

function
testSomething() {
}

function
testSomethingElse() {
}

}
?>

A test case is a class that extends the DrupalTestCase class. You must implement the get_info() method which returns a keyed array with 'name', 'desc' and 'group' strings which are used for display on the Simpletest unit test page. Beyond that, any function that starts with 'test' will be executed whenever the test case is run.

The Simpletest framework and the DrupalTestCase offer a lot of handy tools for executing your tests. We'll explore a couple of these by looking at some non-trivial examples taken from the test cases found in existing modules. The first example comes from the user_validation.test suite from the Simpletest module.

// username validation
function testMinLengthName() {
$name = '';
$result = user_validate_name($name);
$this->assertNotNull($result, 'Excessively short username');
}
?>

This test creates a $name which is unacceptable as a user name because it is an empty string. It passes the $name into Drupal's user_validate_name function and then uses the assertNotNull() method to check whether the test passes or fails. The assertNotNull() method must be called using the $this object, which is an implicit self reference in any PHP class object. The assertNotNull() method will check whether $result is NULL. If it is NULL, the test fails. If it is not NULL, it passes. This makes sense because the function is asserting that the object is not NULL, which is another way of saying "I expect this to have a value (the error message saying that the validation fails), please fail if not NULL". The assertNotNull() method also takes a message parameter. This message gets passed on to the Simpletest framework and is displayed on the test results page. Here is the outcome of the test listed above:

user-validation-pass.png

As you can see, the test passed, which means user_validate_name() did the expected and returned a non NULL value when the $name variable was unacceptable. If you refer to the API documentation for user_validate_name, you will see that it returns string values whenever validation fails.

The next example comes from the tests for the finduser module. The goal of the module is to search for users. In order to test this, the site needs to have users, and the test suite has to know about them, otherwise it wouldn't know what to search for or what to expect. Fortunately the DrupalTestCase has many Drupal-specific convenience methods that let us handle this situation. Here's the code:

function testSearchByEmail() {

// Temporarily set the 'finduser_email' variable to TRUE. It will return
// to whatever it's normal state is when the tearDown() method is called.
$this->drupalVariableSet('finduser_email', TRUE);

/* Prepare a user that we can search for */
$web_user = $this->drupalCreateUserRolePerm();

// Search by email
$results = finduser_do_search('email', $web_user->mail);
// Assert that only one result is found
$this->assertEqual(count($results), 1);
// Assert that it is the user we created.
$this->assertEqual($web_user->uid, $results[0]->id);

// Search for a bogus, non-existent user
$bogus_results = finduser_do_search('email', 'xxx'. $web_user->mail);
// Assert that zero results are found
$this->assertEqual(count($bogus_results), 0);
}
?>

The first convenience method we see here is drupalVariableSet(). Once again, this is a method of the test case object itself, and thus must be called from the $this object. What the method does is inspect the current value for a Drupal variable (finduser_email in this case), take note of it, and then set it to a new value (TRUE). After the tests have run, the variable will be set to its original value, all in the background without you needing to worry about it. In this way you can temporarily change the configuration parameters of your site and not have to worry about cleaning up - the Simpletest module handles it for you.

The next convenience method is drupalCreateUserRolePerm(). This method takes an array of permissions and uses them to create a new user account. The user account will have a generated name and email address, and will have a special user role with the permissions in the array. You can then use this user account to test the functionality of your site. Just like with drupalVariableSet(), the user and the roles will be deleted when the tests are finished running so you needn't worry about filling up your database with extra test users, nor do you need to go and create these users manually.

Once the setup steps are all done the test goes on to invoke the actual function that is being tested: the finduser_do_search() function. The function is told to search for an email that is equal to the $web_user's email. To determine whether the function behaves as expected, $this->assertEqual() is called. assertEqual() takes the first two parameters and asserts that they are equal. The results of assertEqual() will be saved for reporting on the Simpletest unit tests page. The test continues, however, and $this->assertEqual() is called again, this time asserting that the $web_user's name is equal to the username that was found by doing the search.

It is important to test both success cases and failure cases equally. The first two assertions tested that a user was found when expected. The third assertion in the code above asserts that no user is found when searching for a bogus, non-existent user.

// Search for a bogus, non-existent user
$bogus_results = finduser_do_search('email', 'xxx'. $web_user->mail);
// Assert that zero results are found
$this->assertEqual(count($bogus_results), 0);
?>

There are many more ways to do assertions, as well as many more Drupal helper functions. The Simpletest handbook pages on Drupal.org are a good reference for the various tools available.

Functionality testing - a special case

The examples we have looked at so far are true unit tests because they inspect one function at a time, throwing various arguments at it and asserting that the results are correct. The Simpletest framework supports an entirely different method of testing that simulates actions done in a web browser and inspects the output that is sent to the browser, making assertions based on the output. Here is an example that creates a new user, logs into the site using the new user, submits the form to create a new Page node, asserts that the output that gets sent to the browser has the "Your %post has been created" message, and asserts that the node exists in the database. Keep in mind how many clicks it would take you to do all of those steps manually!

function testPageCreation() {
/* Prepare settings */
$this->drupalVariableSet('node_options_page', array('status', 'promote'));

/* Prepare a user to do the stuff */
$web_user = $this->drupalCreateUserRolePerm(array('edit own page content', 'create page content'));
$this->drupalLoginUser($web_user);

$edit = array();
$edit['title'] = '!SimpleTest test node! ' . $this->randomName(10);
$edit['body'] = '!SimpleTest test body! ' . $this->randomName(32) . ' ' . $this->randomName(32);
$this->drupalPostRequest('node/add/page', $edit, 'Submit');

$this->assertWantedRaw(t('Your %post has been created.', array ('%post' => 'Page')), 'Page created');

$node = node_load(array('title' => $edit['title']));
$this->assertNotNull($node, 'Node found in database. %s');
}
?>

The first new method in this code is $this->drupalLoginUser(). Use this function to log in using any $user object, such as those returned by user_load(). This code logs in using the $web_user which was created with the 'edit own page content' and 'create page content' permissions.

This code submits a form using Http POST. Note that $edit contains only the information that the user would be required to enter on the web form. The title and body fields were generated using the $this->randomName() method. 'Submit' is the name of the button that gets clicked in order to submit the form. The $this object stores the HTML output so that you can make assertions against it later.

$edit = array();
$edit['title'] = '!SimpleTest test node! ' . $this->randomName(10);
$edit['body'] = '!SimpleTest test body! ' . $this->randomName(32) . ' ' . $this->randomName(32);
$this->drupalPostRequest('node/add/page', $edit, 'Submit');
?>

This code takes the HTML output that is returned after submitting the form and looks for a specific string within it. The method asserts that the string exists.

$this->assertWantedRaw(t('Your %post has been created.', array ('%post' => 'Page')), 'Page created');
?>

Finally, this test asserts that the node is found in the database as well.

$node = node_load(array('title' => $edit['title']));
$this->assertNotNull($node, 'Node found in database. %s');
?>

More information

For more information on the Simpletest module, please refer to the handbook pages on Drupal.org. The source code for the drupal_unit_tests.php and drupal_test_case.php is also informative as the reference for the available assert and helper methods. The Simpletest API documentation is useful for learning about the underlying framework. Any of the methods available in the Simpletest base classes are also available to your test cases through class inheritance. The center of testing activity for Drupal.org is testing.drupal.org. There are two groups on groups.drupal.org that deal with testing, the Unit testing group and the Quality assurance group.

Invoice Management System

I recently customized a module for Invoice management in drupal, a powerful and very flexible CMS.

Some Features of Invoice Management
  1. Multi-Currency Support
  2. Customer and Company support
  3. Invoices can be converted into PDF
  4. Invoices can be Printed
  5. Invoices can be set as "Paid" or "Unpaid"
  6. TAX Calculation
Screenshot



Are you looking for an Invoice management system? Please do not hesitate to contact us.

Friday, April 24, 2009

Text Editor - VIM

VIM Editor I recently used for customizing a module in Drupal, and loved this editor. I selected PHP syntax in the editor and it worked good, it can switch syntax modes to lots other.

http://www.vim.org/

4 Ace Technologies

PHP HTML to PDF Converter

PDF Convertor known as DOMPDF can be used in PHP Projects to convert something such as an Invoice perhaps, to a PDF invoice.

You can visit the site for Details:
http://www.digitaljunkies.ca/dompdf/index.php

4 Ace Technologies

Monday, April 20, 2009

Drupal Theme Guide

Drupal Theme Guide consists of material that will help you understand how the Theme system of Drupal works, this can be visited at:

http://drupal.org/theme-guide

It consists of sections such as:

4 Ace Technologies

Drag and Drop with Drupal

Drupal now has Drag and Drop tables added in core functionality which can be used in development.

Please refer to drupal API for this function at:

drupal_add_tabledrag:
http://api.drupal.org/api/function/drupal_add_tabledrag/6

4 Ace Technologies

Developing for Drupal

If you are learning and want to develop in drupal, you may want to refer the following site:

http://drupal.org/contributors-guide

It consists sections that are very useful for Drupal developers, such as:
Hope this helps out the Drupal developers out there.

4 Ace Technologies

Saturday, April 18, 2009

Free Clock for your Website

I came accross a site which had a Clock there that looked great, but was free to use:
http://www.clocklink.com/

4 Ace Technologies

Integrate Chat in your Application

I cam accross this widget of Chat box, Chat group, etc, I think it also allows you to actually chat through MSN, and can be inserted into various technologies.

To better understand you can visit the site at:
http://xat.com/

Ofcourse, custom made is always according to your requirements :)
But when free tool fulfills your requirements and there's no worry about "Get a Chatbox" on your own chatbox that is promoting their product, then its a great tool I think.

4 Ace Technologies

Free Counters of your Own

Never tried, but saw some site powered by 99 Counters, it was a Country Counter which showed from Which country how many visits appeared, it looked great. So maybe this site can be useful while applying free counters on sites.

99 Counters

- Make your own counters
- Count your visitors
- Enrich your site with new features
- Get to know your visitors
- It's FREE and super easy!

4 Ace Technologies

Tips on How to get HighTraffic for your Website

According to my study, following are the things that can generate High Traffic for your Website:

  1. Keywords research
    For example, if the site is of Gift Shop, relevant keyword study should be made which can be used for Site so that High Traffic can be obtained.
  2. Write original Contents according to keywords

  3. Meta tags
    Meta tags Description and Meta tag Keywords should be set properly

  4. Page Titles
    Page Titles should also be set according to keywords so that High Traffic is generated

  5. Images ALT tags
    If any Images are used, the ALT tags should contain proper tags such as if an image is of a product "Cake", then it could be give ALT='delicious cake' etc. This option I didn't read at much places, but while writing I remember that I have seen it somewhere, you can consider this an Optional part, or do some of your own research

  6. Submit to search Engines such as Google Yahoo MSN & Live

  7. Perform Link Building
    This may depend on scenario, do some research regarding it on the internet what it is and how it can benefit

  8. Analyse Traffic
    You should try analysing traffic in order to track visitors, increase in visitors, unique visitors, average time spent, etc. Perhaps you can use Google Analytics, you can find out what keywords people searched and then found the Site or Blog

  9. Newsletter
    Keep your customers informed of new Products or Services that the site offers

  10. Blog / RSS Feeds
    Maintaining a Blog and RSS feeds will can also perhaps bring more traffic to site. You can do some reading regarding it over the internet

  11. Monetize
    Sell goods or services, or put Google Ads, or other methods. Join affiliates, Pay-per-click, etc.

4 Ace Technologies

Drupal Event Calendar using Date, Calendar, Views, and CCK

Extracted from: http://www.sagecraft-studios.com/2009/01/drupal-event-calendar-using-date-calendar-views-and-cck.html

I’ll admit it: I am a Drupal newbie. We chose it for our CMS last year, but we haven’t really been using it as a CMS as much as a place to dump and view our internal key indicator reports. But finally! Ah, yes… we finally have a feature request that is actual content management - an event calendar.

Imagine my surprise when I go looking for an event calendar module and find nothing. How could such a huge CMS not have a simple event calendar? A big part of this misunderstanding was that I didn’t understand Drupal - at all. I still don’t really, but figuring this feature out has helped a lot.

One thing to realize is that Drupal is a content management system. So (eventually) it would make sense to create event content and display that content in a specific way. I surprisingly couldn’t find much documentation on this, so below are the steps I took to get my event calendar up and running. They’re kind of abbreviated, so just ask if you need any clarification. Keep in mind this was a learning experience, so if you have any tips for me, I would like those as well. ;)

  1. ## Install Modules
    • View
    • Date
    • CCK
    • Calendar
    • Don’t forget to give yourself permissions to administer these modules and enable them!
  2. ## Create Calendar Event Content Type
    1. Name: Event
    2. Type: event
    3. Title Field Label: Event
    4. Body Field Label: Details
    5. Do not promote to front page.
    6. Save
    7. Go to Manage Fields for Event in the content type list
    8. Add a field called Date of type fieldeventdate with a textfield/popup calendar+repeat selector. Configure it to be required and blank by default, have a reasonable format, and to hide the repeat options by default.
    9. Add a field called Location of type field_event_location that is a single-row text field. Configure it to be 100 chars long and required.
  3. ## Set up A Calendar View
    1. Go to Administer > Views
    2. Enable the default calendar view and clone it.
      • View Name: a_calendar
      • View Description: Calendar
    3. Change the title to “Whatever you want Calendar”
    4. Change Arguments > Date: Date (Node: Updated date) to Content: Date (field_event_date value) Scroll down a bit to see the checkboxes (under Date fields)
    5. Add a sort criterion for Content: Date (field_event_date value)
    6. Add a filter for Node: Type is one of Event
    7. Click the Calendar page side-tab and change the path to “a_calendar”
    8. Click the Calendar block side-tab and change the block settings admin to “A Calendar”
    9. Save the view.
    10. Navigate to ?q=a_calendar to make sure it is working.
  4. ## Set up Roles
    1. Add a new role called Calendar_User and add the following permissions:
      • Edit/view field_event_*
      • (Create | delete own | edit own) event content
    2. Give this role to whoever you want to create event entries. (Let’s call them eventries for fun)
  5. ## Add a link somewhere and enjoy!


4 Ace Technologies

Friday, April 17, 2009

How to Stop Search Engines from Crawling your Site

Some useful sites that may come in handy to stop Search Engines from Crawling your Site

http://www.antezeta.com/blog/avoid-search-engine-indexing

http://www.searchengineoptimizationjournal.com/2008/01/10/preventing-search-engines-from-crawling-your-web-pages/

Search on google perhaps:
http://www.google.com/search?ie=UTF-8&oe=UTF-8&sourceid=navclient&gfns=1&q=how+to+stop+search+engines+from+crawling+your+site

4 Ace Technologies

Wednesday, April 15, 2009

OSCommerce Documentation & Developer Guide

OSCommerce Documentation & Developer's Guide available at:

http://www.oscommerce.info/docs/english/
http://svn.oscommerce.com/confluence/display/OSCDOC/Developer+Guide
http://www.oscommerce.info/docs/english/c_developers_section.html


4 Ace Technologies

Thursday, April 9, 2009

phpFox Documentation

phpFox is a social engine script that can be customized and new modules and blocks can be installed in it.

Documentation for Alpha 2 release of PHPFOX script is at:

http://wiki.phpfox.com/guide/v2

4 Ace Technologies

Source code documentation generator tool

Source code documentation generator tool

Doxygen is a documentation system for C++, C, Java, Objective-C, Python, IDL (Corba and Microsoft flavors), Fortran, VHDL, PHP, C#, and to some extent D.

It can help you in three ways:

  1. It can generate an on-line documentation browser (in HTML) and/or an off-line reference manual (in $\mbox{\LaTeX}$) from a set of documented source files. There is also support for generating output in RTF (MS-Word), PostScript, hyperlinked PDF, compressed HTML, and Unix man pages. The documentation is extracted directly from the sources, which makes it much easier to keep the documentation consistent with the source code.
  2. You can configure doxygen to extract the code structure from undocumented source files. This is very useful to quickly find your way in large source distributions. You can also visualize the relations between the various elements by means of include dependency graphs, inheritance diagrams, and collaboration diagrams, which are all generated automatically.
  3. You can even `abuse' doxygen for creating normal documentation (as I did for this manual).

Doxygen is developed under Linux and Mac OS X, but is set-up to be highly portable. As a result, it runs on most other Unix flavors as well. Furthermore, executables for Windows are available.




4 Ace Technologies

Saturday, April 4, 2009

PHP Login System v2.0

You can download the system from:
http://www.4acetech.com/downloads/Login_System_v.2.0.zip


It is related with article of PHP Login System at:
http://4acetech.blogspot.com/2009/04/php-login-system.html



4 Ace Technologies

PHP Login System

Extracted from: http://www.evolt.org/node/60384 (recommended)

Introduction

I wrote the popular evolt.org tutorial PHP Login Script with Remember Me Feature mainly as an introduction to user sessions and cookies in PHP. Since it was created as a learning tool, many advanced features were left out of the script. By popular demand, I have written and am presenting here a complete Login System, with all the features that were left out of the first script, that can be easily integrated into any website.

Notes

This article is intended primarily for intermediate to advanced users of PHP, as it is not exactly a tutorial, but a description of the implementation of an advanced Login System. Beginners who are looking to learn about user session and cookies in PHP are advised to read the above mentioned tutorial before reading this article.

Features

Here are some of the features in this Login System that weren't included in the initial tutorial:

  • Better Security - Passwords are not stored in cookies, randomly generated ids take their place.
  • Member Levels - Now users can be differentiated by what level they are (user, admin, etc.)
  • Admin Center - As an admin, you have full control over registered users. You can view user info, upgrade/demote user levels, delete users, delete inactive users, and ban users.
  • Visitor Tracking - You can now tell how many guests and users are actively viewing your site, and who those users are. You also know how many total members your site has.
  • Account Info - Users can now view their own information, and edit it as well. They can also see the information of other users.
  • Form Helper - No more ugly error pages! Now users are redirected to the form they filled out and the errors that have occurred are displayed.
  • Forgot Password - Users who forget their password can have a new one generated for them and sent to their email address.
  • Email - Now emails can be sent to newly registered users.
  • Miscellaneous - Much better code design, smooth page transitions, and MORE!

Database

All the tables needed for the Login System are written in the file dbtables.sql. You can look at the file and create each table manually or you can just run the file with mysql and it will create all the necessary tables automatically.

dbtables.sql

#

# dbtables.sql
#
# Simplifies the task of creating all the database tables
# used by the login system.
#
# Can be run from command prompt by typing:
#
# mysql -u yourusername -D yourdatabasename < dbtables.sql
#
# That's with dbtables.sql in the mysql bin directory, but
# you can just include the path to dbtables.sql and that's
# fine too.
#
# Written by: Jpmaster77 a.k.a. The Grandmaster of C++ (GMC)
# Last Updated: August 13, 2004
#

#
# Table structure for users table
#
DROP TABLE IF EXISTS users;

CREATE TABLE users (
username varchar(30) primary key,
password varchar(32),
userid varchar(32),
userlevel tinyint(1) unsigned not null,
email varchar(50),
timestamp int(11) unsigned not null
);


#
# Table structure for active users table
#
DROP TABLE IF EXISTS active_users;

CREATE TABLE active_users (
username varchar(30) primary key,
timestamp int(11) unsigned not null
);


#
# Table structure for active guests table
#
DROP TABLE IF EXISTS active_guests;

CREATE TABLE active_guests (
ip varchar(15) primary key,
timestamp int(11) unsigned not null
);


#
# Table structure for banned users table
#
DROP TABLE IF EXISTS banned_users;

CREATE TABLE banned_users (
username varchar(30) primary key,
timestamp int(11) unsigned not null
);

Code Design

I will be presenting the Login System by showing only the important files, describing what they do and how they interact with each other. By reading this you should get a good idea of how the Login System works and understand how to integrate it into your website. It is important to note before you start that the code relies on classes and the key variables of this Login System are class objects.

constants.php

This file will contain all the constants and important information used by the login system. Here you specify stuff like your database username and password, the admin account name (which will be able to create other admins), visitor timeouts, email options, etc.

/**

* Constants.php
*
* This file is intended to group all constants to
* make it easier for the site administrator to tweak
* the login script.
*
* Written by: Jpmaster77 a.k.a. The Grandmaster of C++ (GMC)
* Last Updated: August 19, 2004
*/

/**
* Database Constants - these constants are required
* in order for there to be a successful connection
* to the MySQL database. Make sure the information is
* correct.
*/
define("DB_SERVER", "localhost");
define("DB_USER", "your_name");
define("DB_PASS", "your_pass");
define("DB_NAME", "your_dbname");

/**
* Database Table Constants - these constants
* hold the names of all the database tables used
* in the script.
*/
define("TBL_USERS", "users");
define("TBL_ACTIVE_USERS", "active_users");
define("TBL_ACTIVE_GUESTS", "active_guests");
define("TBL_BANNED_USERS", "banned_users");

/**
* Special Names and Level Constants - the admin
* page will only be accessible to the user with
* the admin name and also to those users at the
* admin user level. Feel free to change the names
* and level constants as you see fit, you may
* also add additional level specifications.
* Levels must be digits between 0-9.
*/
define("ADMIN_NAME", "admin");
define("GUEST_NAME", "Guest");
define("ADMIN_LEVEL", 9);
define("USER_LEVEL", 1);
define("GUEST_LEVEL", 0);

/**
* This boolean constant controls whether or
* not the script keeps track of active users
* and active guests who are visiting the site.
*/
define("TRACK_VISITORS", true);

/**
* Timeout Constants - these constants refer to
* the maximum amount of time (in minutes) after
* their last page fresh that a user and guest
* are still considered active visitors.
*/
define("USER_TIMEOUT", 10);
define("GUEST_TIMEOUT", 5);

/**
* Cookie Constants - these are the parameters
* to the setcookie function call, change them
* if necessary to fit your website. If you need
* help, visit www.php.net for more info.
*
*/
define("COOKIE_EXPIRE", 60*60*24*100); //100 days by default
define("COOKIE_PATH", "/"); //Available in whole domain

/**
* Email Constants - these specify what goes in
* the from field in the emails that the script
* sends to users, and whether to send a
* welcome email to newly registered users.
*/
define("EMAIL_FROM_NAME", "YourName");
define("EMAIL_FROM_ADDR", "youremail@address.com");
define("EMAIL_WELCOME", false);

/**
* This constant forces all users to have
* lowercase usernames, capital letters are
* converted automatically.
*/
define("ALL_LOWERCASE", false);
?>

database.php

This file contains all the functions that perform database operations, like adding new users to the database table, verifying username and password, retrieving user info, deleting users, etc. It also makes the initial connection to the MySQL database. The functions are members of the Database class, which means they can only be called through a variable of that class. At the end of the file, the $database variable is defined, which is the class object that gets used throughout the Login System.

/**

* Database.php
*
* The Database class is meant to simplify the task of accessing
* information from the website's database.
*
* Written by: Jpmaster77 a.k.a. The Grandmaster of C++ (GMC)
* Last Updated: August 17, 2004
*/
include("constants.php");

class MySQLDB
{
var $connection; //The MySQL database connection
var $num_active_users; //Number of active users viewing site
var $num_active_guests; //Number of active guests viewing site
var $num_members; //Number of signed-up users
/* Note: call getNumMembers() to access $num_members! */

/* Class constructor */
function MySQLDB(){
/* Make connection to database */
$this->connection = mysql_connect(DB_SERVER, DB_USER, DB_PASS) or die(mysql_error());
mysql_select_db(DB_NAME, $this->connection) or die(mysql_error());

/**
* Only query database to find out number of members
* when getNumMembers() is called for the first time,
* until then, default value set.
*/
$this->num_members = -1;

if(TRACK_VISITORS){
/* Calculate number of users at site */
$this->calcNumActiveUsers();

/* Calculate number of guests at site */
$this->calcNumActiveGuests();
}
}

/**
* confirmUserPass - 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 confirmUserPass($username, $password){
/* Add slashes if necessary (for query) */
if(!get_magic_quotes_gpc()) {
$username = addslashes($username);
}

/* Verify that user is in database */
$q = "SELECT password FROM ".TBL_USERS." WHERE username = '$username'";
$result = mysql_query($q, $this->connection);
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
}
}

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

/* Verify that user is in database */
$q = "SELECT userid FROM ".TBL_USERS." WHERE username = '$username'";
$result = mysql_query($q, $this->connection);
if(!$result || (mysql_numrows($result) < 1)){
return 1; //Indicates username failure
}

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

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

/**
* usernameTaken - Returns true if the username has
* been taken by another user, false otherwise.
*/
function usernameTaken($username){
if(!get_magic_quotes_gpc()){
$username = addslashes($username);
}
$q = "SELECT username FROM ".TBL_USERS." WHERE username = '$username'";
$result = mysql_query($q, $this->connection);
return (mysql_numrows($result) > 0);
}

/**
* usernameBanned - Returns true if the username has
* been banned by the administrator.
*/
function usernameBanned($username){
if(!get_magic_quotes_gpc()){
$username = addslashes($username);
}
$q = "SELECT username FROM ".TBL_BANNED_USERS." WHERE username = '$username'";
$result = mysql_query($q, $this->connection);
return (mysql_numrows($result) > 0);
}

/**
* addNewUser - Inserts the given (username, password, email)
* info into the database. Appropriate user level is set.
* Returns true on success, false otherwise.
*/
function addNewUser($username, $password, $email){
$time = time();
/* If admin sign up, give admin user level */
if(strcasecmp($username, ADMIN_NAME) == 0){
$ulevel = ADMIN_LEVEL;
}else{
$ulevel = USER_LEVEL;
}
$q = "INSERT INTO ".TBL_USERS." VALUES ('$username', '$password', '0', $ulevel, '$email', $time)";
return mysql_query($q, $this->connection);
}

/**
* updateUserField - Updates a field, specified by the field
* parameter, in the user's row of the database.
*/
function updateUserField($username, $field, $value){
$q = "UPDATE ".TBL_USERS." SET ".$field." = '$value' WHERE username = '$username'";
return mysql_query($q, $this->connection);
}

/**
* getUserInfo - Returns the result array from a mysql
* query asking for all information stored regarding
* the given username. If query fails, NULL is returned.
*/
function getUserInfo($username){
$q = "SELECT * FROM ".TBL_USERS." WHERE username = '$username'";
$result = mysql_query($q, $this->connection);
/* Error occurred, return given name by default */
if(!$result || (mysql_numrows($result) < 1)){
return NULL;
}
/* Return result array */
$dbarray = mysql_fetch_array($result);
return $dbarray;
}

/**
* getNumMembers - Returns the number of signed-up users
* of the website, banned members not included. The first
* time the function is called on page load, the database
* is queried, on subsequent calls, the stored result
* is returned. This is to improve efficiency, effectively
* not querying the database when no call is made.
*/
function getNumMembers(){
if($this->num_members < 0){
$q = "SELECT * FROM ".TBL_USERS;
$result = mysql_query($q, $this->connection);
$this->num_members = mysql_numrows($result);
}
return $this->num_members;
}

/**
* calcNumActiveUsers - Finds out how many active users
* are viewing site and sets class variable accordingly.
*/
function calcNumActiveUsers(){
/* Calculate number of users at site */
$q = "SELECT * FROM ".TBL_ACTIVE_USERS;
$result = mysql_query($q, $this->connection);
$this->num_active_users = mysql_numrows($result);
}

/**
* calcNumActiveGuests - Finds out how many active guests
* are viewing site and sets class variable accordingly.
*/
function calcNumActiveGuests(){
/* Calculate number of guests at site */
$q = "SELECT * FROM ".TBL_ACTIVE_GUESTS;
$result = mysql_query($q, $this->connection);
$this->num_active_guests = mysql_numrows($result);
}

/**
* addActiveUser - Updates username's last active timestamp
* in the database, and also adds him to the table of
* active users, or updates timestamp if already there.
*/
function addActiveUser($username, $time){
$q = "UPDATE ".TBL_USERS." SET timestamp = '$time' WHERE username = '$username'";
mysql_query($q, $this->connection);

if(!TRACK_VISITORS) return;
$q = "REPLACE INTO ".TBL_ACTIVE_USERS." VALUES ('$username', '$time')";
mysql_query($q, $this->connection);
$this->calcNumActiveUsers();
}

/* addActiveGuest - Adds guest to active guests table */
function addActiveGuest($ip, $time){
if(!TRACK_VISITORS) return;
$q = "REPLACE INTO ".TBL_ACTIVE_GUESTS." VALUES ('$ip', '$time')";
mysql_query($q, $this->connection);
$this->calcNumActiveGuests();
}

/* These functions are self explanatory, no need for comments */

/* removeActiveUser */
function removeActiveUser($username){
if(!TRACK_VISITORS) return;
$q = "DELETE FROM ".TBL_ACTIVE_USERS." WHERE username = '$username'";
mysql_query($q, $this->connection);
$this->calcNumActiveUsers();
}

/* removeActiveGuest */
function removeActiveGuest($ip){
if(!TRACK_VISITORS) return;
$q = "DELETE FROM ".TBL_ACTIVE_GUESTS." WHERE ip = '$ip'";
mysql_query($q, $this->connection);
$this->calcNumActiveGuests();
}

/* removeInactiveUsers */
function removeInactiveUsers(){
if(!TRACK_VISITORS) return;
$timeout = time()-USER_TIMEOUT*60;
$q = "DELETE FROM ".TBL_ACTIVE_USERS." WHERE timestamp < $timeout";
mysql_query($q, $this->connection);
$this->calcNumActiveUsers();
}

/* removeInactiveGuests */
function removeInactiveGuests(){
if(!TRACK_VISITORS) return;
$timeout = time()-GUEST_TIMEOUT*60;
$q = "DELETE FROM ".TBL_ACTIVE_GUESTS." WHERE timestamp < $timeout";
mysql_query($q, $this->connection);
$this->calcNumActiveGuests();
}

/**
* query - Performs the given query on the database and
* returns the result, which may be false, true or a
* resource identifier.
*/
function query($query){
return mysql_query($query, $this->connection);
}
};

/* Create database connection */
$database = new MySQLDB;

?>

session.php

This file is the heart and soul of the Login System. It contains the code to login, logout and register users. It also holds all the information about the user that is viewing the site. All the variables and functions are part of the Session class, and the $session class object variable is created so you can access those variables and functions. You will be using this class object whenever you want to get information about the visitor of your site, like whether or not they are logged in. How to use this object, and others as well, is apparent when looking through the example pages which are given (main.php, userinfo.php, etc.).

/**

* Session.php
*
* The Session class is meant to simplify the task of keeping
* track of logged in users and also guests.
*
* Written by: Jpmaster77 a.k.a. The Grandmaster of C++ (GMC)
* Last Updated: August 19, 2004
*/
include("database.php");
include("mailer.php");
include("form.php");

class Session
{
var $username; //Username given on sign-up
var $userid; //Random value generated on current login
var $userlevel; //The level to which the user pertains
var $time; //Time user was last active (page loaded)
var $logged_in; //True if user is logged in, false otherwise
var $userinfo = array(); //The array holding all user info
var $url; //The page url current being viewed
var $referrer; //Last recorded site page viewed
/**
* Note: referrer should really only be considered the actual
* page referrer in process.php, any other time it may be
* inaccurate.
*/

/* Class constructor */
function Session(){
$this->time = time();
$this->startSession();
}

/**
* startSession - Performs all the actions necessary to
* initialize this session object. Tries to determine if the
* the user has logged in already, and sets the variables
* accordingly. Also takes advantage of this page load to
* update the active visitors tables.
*/
function startSession(){
global $database; //The database connection
session_start(); //Tell PHP to start the session

/* Determine if user is logged in */
$this->logged_in = $this->checkLogin();

/**
* Set guest value to users not logged in, and update
* active guests table accordingly.
*/
if(!$this->logged_in){
$this->username = $_SESSION['username'] = GUEST_NAME;
$this->userlevel = GUEST_LEVEL;
$database->addActiveGuest($_SERVER['REMOTE_ADDR'], $this->time);
}
/* Update users last active timestamp */
else{
$database->addActiveUser($this->username, $this->time);
}

/* Remove inactive visitors from database */
$database->removeInactiveUsers();
$database->removeInactiveGuests();

/* Set referrer page */
if(isset($_SESSION['url'])){
$this->referrer = $_SESSION['url'];
}else{
$this->referrer = "/";
}

/* Set current url */
$this->url = $_SESSION['url'] = $_SERVER['PHP_SELF'];
}

/**
* 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(){
global $database; //The database connection
/* Check if user has been remembered */
if(isset($_COOKIE['cookname']) && isset($_COOKIE['cookid'])){
$this->username = $_SESSION['username'] = $_COOKIE['cookname'];
$this->userid = $_SESSION['userid'] = $_COOKIE['cookid'];
}

/* Username and userid have been set and not guest */
if(isset($_SESSION['username']) && isset($_SESSION['userid']) &&
$_SESSION['username'] != GUEST_NAME){
/* Confirm that username and userid are valid */
if($database->confirmUserID($_SESSION['username'], $_SESSION['userid']) != 0){
/* Variables are incorrect, user not logged in */
unset($_SESSION['username']);
unset($_SESSION['userid']);
return false;
}

/* User is logged in, set class variables */
$this->userinfo = $database->getUserInfo($_SESSION['username']);
$this->username = $this->userinfo['username'];
$this->userid = $this->userinfo['userid'];
$this->userlevel = $this->userinfo['userlevel'];
return true;
}
/* User not logged in */
else{
return false;
}
}

/**
* login - The user has submitted his username and password
* through the login form, this function checks the authenticity
* of that information in the database and creates the session.
* Effectively logging in the user if all goes well.
*/
function login($subuser, $subpass, $subremember){
global $database, $form; //The database and form object

/* Username error checking */
$field = "user"; //Use field name for username
if(!$subuser || strlen($subuser = trim($subuser)) == 0){
$form->setError($field, "* Username not entered");
}
else{
/* Check if username is not alphanumeric */
if(!eregi("^([0-9a-z])*$", $subuser)){
$form->setError($field, "* Username not alphanumeric");
}
}

/* Password error checking */
$field = "pass"; //Use field name for password
if(!$subpass){
$form->setError($field, "* Password not entered");
}

/* Return if form errors exist */
if($form->num_errors > 0){
return false;
}

/* Checks that username is in database and password is correct */
$subuser = stripslashes($subuser);
$result = $database->confirmUserPass($subuser, md5($subpass));

/* Check error codes */
if($result == 1){
$field = "user";
$form->setError($field, "* Username not found");
}
else if($result == 2){
$field = "pass";
$form->setError($field, "* Invalid password");
}

/* Return if form errors exist */
if($form->num_errors > 0){
return false;
}

/* Username and password correct, register session variables */
$this->userinfo = $database->getUserInfo($subuser);
$this->username = $_SESSION['username'] = $this->userinfo['username'];
$this->userid = $_SESSION['userid'] = $this->generateRandID();
$this->userlevel = $this->userinfo['userlevel'];

/* Insert userid into database and update active users table */
$database->updateUserField($this->username, "userid", $this->userid);
$database->addActiveUser($this->username, $this->time);
$database->removeActiveGuest($_SERVER['REMOTE_ADDR']);

/**
* 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 random value userid. It expires by the time
* specified in constants.php. Now, next time he comes to our site, we will
* log him in automatically, but only if he didn't log out before he left.
*/
if($subremember){
setcookie("cookname", $this->username, time()+COOKIE_EXPIRE, COOKIE_PATH);
setcookie("cookid", $this->userid, time()+COOKIE_EXPIRE, COOKIE_PATH);
}

/* Login completed successfully */
return true;
}

/**
* logout - Gets called when the user wants to be logged out of the
* website. It deletes any cookies that were stored on the users
* computer as a result of him wanting to be remembered, and also
* unsets session variables and demotes his user level to guest.
*/
function logout(){
global $database; //The database connection
/**
* 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['cookid'])){
setcookie("cookname", "", time()-COOKIE_EXPIRE, COOKIE_PATH);
setcookie("cookid", "", time()-COOKIE_EXPIRE, COOKIE_PATH);
}

/* Unset PHP session variables */
unset($_SESSION['username']);
unset($_SESSION['userid']);

/* Reflect fact that user has logged out */
$this->logged_in = false;

/**
* Remove from active users table and add to
* active guests tables.
*/
$database->removeActiveUser($this->username);
$database->addActiveGuest($_SERVER['REMOTE_ADDR'], $this->time);

/* Set user level to guest */
$this->username = GUEST_NAME;
$this->userlevel = GUEST_LEVEL;
}

/**
* register - Gets called when the user has just submitted the
* registration form. Determines if there were any errors with
* the entry fields, if so, it records the errors and returns
* 1. If no errors were found, it registers the new user and
* returns 0. Returns 2 if registration failed.
*/
function register($subuser, $subpass, $subemail){
global $database, $form, $mailer; //The database, form and mailer object

/* Username error checking */
$field = "user"; //Use field name for username
if(!$subuser || strlen($subuser = trim($subuser)) == 0){
$form->setError($field, "* Username not entered");
}
else{
/* Spruce up username, check length */
$subuser = stripslashes($subuser);
if(strlen($subuser) < 5){
$form->setError($field, "* Username below 5 characters");
}
else if(strlen($subuser) > 30){
$form->setError($field, "* Username above 30 characters");
}
/* Check if username is not alphanumeric */
else if(!eregi("^([0-9a-z])+$", $subuser)){
$form->setError($field, "* Username not alphanumeric");
}
/* Check if username is reserved */
else if(strcasecmp($subuser, GUEST_NAME) == 0){
$form->setError($field, "* Username reserved word");
}
/* Check if username is already in use */
else if($database->usernameTaken($subuser)){
$form->setError($field, "* Username already in use");
}
/* Check if username is banned */
else if($database->usernameBanned($subuser)){
$form->setError($field, "* Username banned");
}
}

/* Password error checking */
$field = "pass"; //Use field name for password
if(!$subpass){
$form->setError($field, "* Password not entered");
}
else{
/* Spruce up password and check length*/
$subpass = stripslashes($subpass);
if(strlen($subpass) < 4){
$form->setError($field, "* Password too short");
}
/* Check if password is not alphanumeric */
else if(!eregi("^([0-9a-z])+$", ($subpass = trim($subpass)))){
$form->setError($field, "* Password not alphanumeric");
}
/**
* Note: I trimmed the password only after I checked the length
* because if you fill the password field up with spaces
* it looks like a lot more characters than 4, so it looks
* kind of stupid to report "password too short".
*/
}

/* Email error checking */
$field = "email"; //Use field name for email
if(!$subemail || strlen($subemail = trim($subemail)) == 0){
$form->setError($field, "* Email not entered");
}
else{
/* Check if valid email address */
$regex = "^[_+a-z0-9-]+(\.[_+a-z0-9-]+)*"
."@[a-z0-9-]+(\.[a-z0-9-]{1,})*"
."\.([a-z]{2,}){1}$";
if(!eregi($regex,$subemail)){
$form->setError($field, "* Email invalid");
}
$subemail = stripslashes($subemail);
}

/* Errors exist, have user correct them */
if($form->num_errors > 0){
return 1; //Errors with form
}
/* No errors, add the new account to the */
else{
if($database->addNewUser($subuser, md5($subpass), $subemail)){
if(EMAIL_WELCOME){
$mailer->sendWelcome($subuser,$subemail,$subpass);
}
return 0; //New user added succesfully
}else{
return 2; //Registration attempt failed
}
}
}

/**
* editAccount - Attempts to edit the user's account information
* including the password, which it first makes sure is correct
* if entered, if so and the new password is in the right
* format, the change is made. All other fields are changed
* automatically.
*/
function editAccount($subcurpass, $subnewpass, $subemail){
global $database, $form; //The database and form object
/* New password entered */
if($subnewpass){
/* Current Password error checking */
$field = "curpass"; //Use field name for current password
if(!$subcurpass){
$form->setError($field, "* Current Password not entered");
}
else{
/* Check if password too short or is not alphanumeric */
$subcurpass = stripslashes($subcurpass);
if(strlen($subcurpass) < 4 ||
!eregi("^([0-9a-z])+$", ($subcurpass = trim($subcurpass)))){
$form->setError($field, "* Current Password incorrect");
}
/* Password entered is incorrect */
if($database->confirmUserPass($this->username,md5($subcurpass)) != 0){
$form->setError($field, "* Current Password incorrect");
}
}

/* New Password error checking */
$field = "newpass"; //Use field name for new password
/* Spruce up password and check length*/
$subpass = stripslashes($subnewpass);
if(strlen($subnewpass) < 4){
$form->setError($field, "* New Password too short");
}
/* Check if password is not alphanumeric */
else if(!eregi("^([0-9a-z])+$", ($subnewpass = trim($subnewpass)))){
$form->setError($field, "* New Password not alphanumeric");
}
}
/* Change password attempted */
else if($subcurpass){
/* New Password error reporting */
$field = "newpass"; //Use field name for new password
$form->setError($field, "* New Password not entered");
}

/* Email error checking */
$field = "email"; //Use field name for email
if($subemail && strlen($subemail = trim($subemail)) > 0){
/* Check if valid email address */
$regex = "^[_+a-z0-9-]+(\.[_+a-z0-9-]+)*"
."@[a-z0-9-]+(\.[a-z0-9-]{1,})*"
."\.([a-z]{2,}){1}$";
if(!eregi($regex,$subemail)){
$form->setError($field, "* Email invalid");
}
$subemail = stripslashes($subemail);
}

/* Errors exist, have user correct them */
if($form->num_errors > 0){
return false; //Errors with form
}

/* Update password since there were no errors */
if($subcurpass && $subnewpass){
$database->updateUserField($this->username,"password",md5($subnewpass));
}

/* Change Email */
if($subemail){
$database->updateUserField($this->username,"email",$subemail);
}

/* Success! */
return true;
}

/**
* isAdmin - Returns true if currently logged in user is
* an administrator, false otherwise.
*/
function isAdmin(){
return ($this->userlevel == ADMIN_LEVEL ||
$this->username == ADMIN_NAME);
}

/**
* generateRandID - Generates a string made up of randomized
* letters (lower and upper case) and digits and returns
* the md5 hash of it to be used as a userid.
*/
function generateRandID(){
return md5($this->generateRandStr(16));
}

/**
* generateRandStr - Generates a string made up of randomized
* letters (lower and upper case) and digits, the length
* is a specified parameter.
*/
function generateRandStr($length){
$randstr = "";
for($i=0; $i<$length; $i++){
$randnum = mt_rand(0,61);
if($randnum < 10){
$randstr .= chr($randnum+48);
}else if($randnum < 36){
$randstr .= chr($randnum+55);
}else{
$randstr .= chr($randnum+61);
}
}
return $randstr;
}
};


/**
* Initialize session object - This must be initialized before
* the form object because the form uses session variables,
* which cannot be accessed unless the session has started.
*/
$session = new Session;

/* Initialize form object */
$form = new Form;

?>

Read through the code and get a feel for how the script knows when the users are logged in or not (checks cookies and $_SESSION variables). Everything is commented so you won't have trouble. Note that the Session functions make good use of the $database object because the database needs to be queried for a lot of functions. Visitor tracking is also being done here. Whenever this page loads, the visitor is added as an active guest or active user, depending on if they are logged in or not, and it also performs the operation to remove any inactive users/guests (people who haven't loaded any pages within the timeout specified in constants.php).

Forms

The creation of a Form class was meant to facilitate the handling of errors with user-submitted forms. It keeps track of what the user entered into the form fields (the values) and what errors have occurred with the form.

form.php

/**

* Form.php
*
* The Form class is meant to simplify the task of keeping
* track of errors in user submitted forms and the form
* field values that were entered correctly.
*
* Written by: Jpmaster77 a.k.a. The Grandmaster of C++ (GMC)
* Last Updated: August 19, 2004
*/

class Form
{
var $values = array(); //Holds submitted form field values
var $errors = array(); //Holds submitted form error messages
var $num_errors; //The number of errors in submitted form

/* Class constructor */
function Form(){
/**
* Get form value and error arrays, used when there
* is an error with a user-submitted form.
*/
if(isset($_SESSION['value_array']) && isset($_SESSION['error_array'])){
$this->values = $_SESSION['value_array'];
$this->errors = $_SESSION['error_array'];
$this->num_errors = count($this->errors);

unset($_SESSION['value_array']);
unset($_SESSION['error_array']);
}
else{
$this->num_errors = 0;
}
}

/**
* setValue - Records the value typed into the given
* form field by the user.
*/
function setValue($field, $value){
$this->values[$field] = $value;
}

/**
* setError - Records new form error given the form
* field name and the error message attached to it.
*/
function setError($field, $errmsg){
$this->errors[$field] = $errmsg;
$this->num_errors = count($this->errors);
}

/**
* value - Returns the value attached to the given
* field, if none exists, the empty string is returned.
*/
function value($field){
if(array_key_exists($field,$this->values)){
return htmlspecialchars(stripslashes($this->values[$field]));
}else{
return "";
}
}

/**
* error - Returns the error message attached to the
* given field, if none exists, the empty string is returned.
*/
function error($field){
if(array_key_exists($field,$this->errors)){
return "".$this->errors[$field]."";
}else{
return "";
}
}

/* getErrorArray - Returns the array of error messages */
function getErrorArray(){
return $this->errors;
}
};

?>

The $form class object is actually defined at the bottom of session.php, for reasons explained there. Basically how it works is there is a value array and an error array. They can be indexed with the names of the fields in the HTML form. So if you had a field whose name was "email", once the user submits the form and an error occurred, you can display what the user already typed in by calling $form->value("email"). If there was an error with what the user typed into the "email" field, you can display the error with $form->error("email").

Look at session.php, login and register functions, they use the form object well and show how to appropriately specify the form errors. Also look later on at main.php and you'll see how to appropriately use the form object when displaying any HTML form on your website.

process.php

All forms submitted by the user have to be processed in some way, and this file takes care of that. Every form the user fills out is directed to this page, and this page figures out which form needs to be processed (whether it be login, register, forgot pass, etc.) and calls the appropriate functions to handle the request.

This page is also in charge of re-directing the user to the correct page after the form has been processed, whether it be to the page referrer (default), or some other specified page. When errors have been found with the submitted form, the default action is to re-direct to the page where the user filled out the form in order to let them know about the error and fix it. If you want your users when just logging-in to be re-directed to their own specific home page, instead of the website main page, this is the file you want to edit to do that.

/**

* Process.php
*
* The Process class is meant to simplify the task of processing
* user submitted forms, redirecting the user to the correct
* pages if errors are found, or if form is successful, either
* way. Also handles the logout procedure.
*
* Written by: Jpmaster77 a.k.a. The Grandmaster of C++ (GMC)
* Last Updated: August 19, 2004
*/
include("include/session.php");

class Process
{
/* Class constructor */
function Process(){
global $session;
/* User submitted login form */
if(isset($_POST['sublogin'])){
$this->procLogin();
}
/* User submitted registration form */
else if(isset($_POST['subjoin'])){
$this->procRegister();
}
/* User submitted forgot password form */
else if(isset($_POST['subforgot'])){
$this->procForgotPass();
}
/* User submitted edit account form */
else if(isset($_POST['subedit'])){
$this->procEditAccount();
}
/**
* The only other reason user should be directed here
* is if he wants to logout, which means user is
* logged in currently.
*/
else if($session->logged_in){
$this->procLogout();
}
/**
* Should not get here, which means user is viewing this page
* by mistake and therefore is redirected.
*/
else{
header("Location: main.php");
}
}

/**
* procLogin - Processes the user submitted login form, if errors
* are found, the user is redirected to correct the information,
* if not, the user is effectively logged in to the system.
*/
function procLogin(){
global $session, $form;
/* Login attempt */
$retval = $session->login($_POST['user'], $_POST['pass'], isset($_POST['remember']));

/* Login successful */
if($retval){
header("Location: ".$session->referrer);
}
/* Login failed */
else{
$_SESSION['value_array'] = $_POST;
$_SESSION['error_array'] = $form->getErrorArray();
header("Location: ".$session->referrer);
}
}

/**
* procLogout - Simply attempts to log the user out of the system
* given that there is no logout form to process.
*/
function procLogout(){
global $session;
$retval = $session->logout();
header("Location: main.php");
}

/**
* procRegister - Processes the user submitted registration form,
* if errors are found, the user is redirected to correct the
* information, if not, the user is effectively registered with
* the system and an email is (optionally) sent to the newly
* created user.
*/
function procRegister(){
global $session, $form;
/* Convert username to all lowercase (by option) */
if(ALL_LOWERCASE){
$_POST['user'] = strtolower($_POST['user']);
}
/* Registration attempt */
$retval = $session->register($_POST['user'], $_POST['pass'], $_POST['email']);

/* Registration Successful */
if($retval == 0){
$_SESSION['reguname'] = $_POST['user'];
$_SESSION['regsuccess'] = true;
header("Location: ".$session->referrer);
}
/* Error found with form */
else if($retval == 1){
$_SESSION['value_array'] = $_POST;
$_SESSION['error_array'] = $form->getErrorArray();
header("Location: ".$session->referrer);
}
/* Registration attempt failed */
else if($retval == 2){
$_SESSION['reguname'] = $_POST['user'];
$_SESSION['regsuccess'] = false;
header("Location: ".$session->referrer);
}
}

/**
* procForgotPass - Validates the given username then if
* everything is fine, a new password is generated and
* emailed to the address the user gave on sign up.
*/
function procForgotPass(){
global $database, $session, $mailer, $form;
/* Username error checking */
$subuser = $_POST['user'];
$field = "user"; //Use field name for username
if(!$subuser || strlen($subuser = trim($subuser)) == 0){
$form->setError($field, "* Username not entered
");
}
else{
/* Make sure username is in database */
$subuser = stripslashes($subuser);
if(strlen($subuser) <> 30 ||
!eregi("^([0-9a-z])+$", $subuser) ||
(!$database->usernameTaken($subuser))){
$form->setError($field, "* Username does not exist
");
}
}

/* Errors exist, have user correct them */
if($form->num_errors > 0){
$_SESSION['value_array'] = $_POST;
$_SESSION['error_array'] = $form->getErrorArray();
}
/* Generate new password and email it to user */
else{
/* Generate new password */
$newpass = $session->generateRandStr(8);

/* Get email of user */
$usrinf = $database->getUserInfo($subuser);
$email = $usrinf['email'];

/* Attempt to send the email with new password */
if($mailer->sendNewPass($subuser,$email,$newpass)){
/* Email sent, update database */
$database->updateUserField($subuser, "password", md5($newpass));
$_SESSION['forgotpass'] = true;
}
/* Email failure, do not change password */
else{
$_SESSION['forgotpass'] = false;
}
}

header("Location: ".$session->referrer);
}

/**
* procEditAccount - Attempts to edit the user's account
* information, including the password, which must be verified
* before a change is made.
*/
function procEditAccount(){
global $session, $form;
/* Account edit attempt */
$retval = $session->editAccount($_POST['curpass'], $_POST['newpass'], $_POST['email']);

/* Account edit successful */
if($retval){
$_SESSION['useredit'] = true;
header("Location: ".$session->referrer);
}
/* Error found with form */
else{
$_SESSION['value_array'] = $_POST;
$_SESSION['error_array'] = $form->getErrorArray();
header("Location: ".$session->referrer);
}
}
};

/* Initialize process */
$process = new Process;

?>

Active Visitors

Tracking active visitors is accomplished in the following way: There are two database tables, one to hold the active users and one to hold the active guests. The users are distinguished by their username and the guests by their IP address. This is so we won't add any given user or guest to the tables more than once, because if we did, our information would be incorrect.

Associated with the user or guest is a timestamp, this is updated every time he/she loads a page. The timestamp tells us when the user/guest was last active. When a visitor loads a page, not only are they added/updated in the active table, but a clean-up operation is performed, one that removes any IP addresses or usernames in the database tables that haven't recently been active, the ones who have a timestamp older than the current time minus the timeout specified in constants.php. The tracking of visitors is accomplished in session.php.

Admin Center

The admin center is the page where admins go to do what they do best, administer the Login System. There they can view the table of users and all the user information, except for user passwords because they are encrypted. But how does someone become an admin, how does the system even recognize admins? Well, I'll tell you. If you look in constants.php you'll see that the admin level and admin name are specified. When a user logs in to the website, their user level is retrieved from the database, if their user level equals the admin level, then they are an admin, and they have all admin priviledges.

Admin Name

Well, who gets the admin name as a username? You do, but you have to register it, just like any other name. You should do this once you get the script up and running. Once you register the admin name, the Login System gives that username an admin user level. Let's assume someone were to steal it from you. You have access to constants.php, which means you can edit it, so you could create a new admin name, then register that name, go to the admin center and delete the guy from the system.

Adding Admins

Let's say you need help with your website, and you want your buddy to help out and be an admin. You can have him register under some username of his choice, then you can go to the admin center and give his username the admin user level. Done. That would put him at your level, ...maybe you don't want to give him that much power. Well, the user level is a number from 0-9. By default, guests are 0, users are 1, and admins are 9. You can just give him a user level of 8, and let your website define what that means as far as privileges.

Main Page

The following is an example for your website's main page. It shows a little bit how to use the $session, $form, and $database variables. It contains the login form of the Login System. Note when looking at the HTML form, there's a hidden field called "sublogin", that's the name of the form. That's important because when process.php is loaded it needs to know what form is being processed. So if you want to create different forms later on, make sure you give it a unique name.

main.php

/**

* Main.php
*
* This is an example of the main page of a website. Here
* users will be able to login. However, like on most sites
* the login form doesn't just have to be on the main page,
* but re-appear on subsequent pages, depending on whether
* the user has logged in or not.
*
* Written by: Jpmaster77 a.k.a. The Grandmaster of C++ (GMC)
* Last Updated: August 26, 2004
*/
include("include/session.php");
?>


Jpmaster77's Login Script







/**
* User has already logged in, so display relevant links, including
* a link to the admin center if the user is an administrator.
*/
if($session->logged_in){
echo "

Logged In

";
echo "Welcome $session->username, you are logged in.

"
."[username\">My Account] "
."[Edit Account] ";
if($session->isAdmin()){
echo "[Admin Center] ";
}
echo "[Logout]";
}
else{
?>

Login


/**
* User not logged in, display the login form.
* If user has already tried to login, but errors were
* found, display the total number of errors.
* If errors occurred, they will be displayed.
*/
if($form->num_errors > 0){
echo "".$form->num_errors." error(s) found";
}
?>







Username:value("user"); ?>">error("user"); ?>
Password:value("pass"); ?>">error("pass"); ?>
value("remember") != ""){ echo "checked"; } ?>>
Remember me next time


[Forgot Password?]

Not registered? Sign-Up!



}

/**
* Just a little page footer, tells how many registered members
* there are, how many users currently logged in and viewing site,
* and how many guests viewing site. Active users are displayed,
* with link to their user information.
*/
echo "


";
echo "Member Total: ".$database->getNumMembers()."
";
echo "There are $database->num_active_users registered members and ";
echo "$database->num_active_guests guests viewing the site.

";

include("include/view_active.php");

?>







Download

As you've probably noticed, pages have been left out of the article. Where's the Admin Center? User Account Page? Forgot Password Form? ... Well, there's too much code to show it all here, plus most of it is self-explanatory. So if you want to see that stuff, and use what I've shown you, download it!

Conclusion

The only reason I made this advanced Login System was because so many people liked my first one and wanted to see more features get added. So I decided to put all the requested features together into this new Login System and give the people what they wanted. So I want to say thank you to all those who enjoyed my first script and supported me, and I hope you enjoy this one too. Happy programming!

AttachmentSize
Login_System_v.2.0.zip22.83 KB

well written step-by-step

Submitted by spinhead on September 28, 2004 - 06:53.

I'm still refining my PHP, and this article is a real boost. Makes me feel like even I can do this!

login or register to post comments

And he does it again !

Submitted by saruman on September 28, 2004 - 12:51.

Thanks again JP, You truly are great for taking your time to do these scripts, I did manage to get the last one working but have not really had time to finish the site I was supposed to use it with, maybe ill try upgrade to this one :)

I will try it out when I get a chance and let you know

login or register to post comments

Question

Submitted by libelle on September 28, 2004 - 16:09.

When I look at the PEAR libraries, I see a fair amount of infrastructure for this kind of application. Any recommendations with regard to using them? I'm interested in the more general character (e.g., DB-agnosticism) of those libraries, but like the additional features you implement.

login or register to post comments

Real cool script

Submitted by wocktu on September 28, 2004 - 16:37.

By scripts work really great. Especially this one. I havnt tried to modify the registration page yet so touch wood I won't stuff it up. I'm doing a Degree in IT and am building a Squash clubs website with a court booking system, this will help out greatly. Thanks JP

login or register to post comments

Great

Submitted by domostick on September 28, 2004 - 18:36.

On the other script you could hide html from people that were not logged in. The old php
<
{
>
^^Did not work. It looks something like that lol. Is there a way to do this again?

login or register to post comments

Customizing Main.php

Submitted by swattle on September 29, 2004 - 14:35.

I am new to PHP and I am starting a new website and at swattle.com . I am not sure what I am doing wrong. If you visit http://swattle.com you will see my site. You can login by creating yourself your own account or use the one I have been fooling around with which is user name: testing password: 12345 You will not that when you login at http://www.swattle.com/index.php you will be redirected to http://www.swattle.com/usr/main.php This is the folder I placed all of the files from the archive I downloaded to. Why does it redirect you to the main.php file? I want it to redirect back to http://www.swattle.com/index.php Where is the script getting this url location from?

login or register to post comments

reply

Submitted by domostick on September 29, 2004 - 15:45.

you must change the redirect link in the file you placed the login box.

also anybody know of the new php code to hide html from non logged in users. i tried the old one, it dont work

login or register to post comments

Customizing Login

Submitted by swattle on September 29, 2004 - 17:00.

I am not sure where you mean. The login box in my main index.php page and there is no variable listed for a redirect. The only place I see is a redirect in the process.php file which is the last attempt of logic in the else if statement to determine what the users is doing with a form.

login or register to post comments

Process.php and $session object

Submitted by jpmaster77 on September 29, 2004 - 17:14.

swattle,
In the HTML login form at swattle.com/index.php you called it "sublogin2", (it is called "sublogin" in the code provided), so I'm assuming you are checking for this name in swattle.com/usr/process.php. Because if you aren't, which I don't think you are, it will redirect to main.php. You need to edit process.php to check for this form name, then log the user in and redirect to either $session->referrer or just type in "../index.php".

domostick,
There is no global $logged_in variable like in the last script. This new script is more object oriented, you want the $session->logged_in variable.

Example:

if($session->logged_in){

echo "Hey $session->username, you are logged in!";

}

else{

echo "You are not logged in.";

}


Note that this example is seen in main.php.

Good luck,
JP

login or register to post comments

sublogin

Submitted by swattle on September 29, 2004 - 18:38.

JP, That was the problem. I am so silly. I must have looked at that string of characters 3,000 times and never paid any attention to the 2 One other thing, Maybe because of how I customized the form to login, but now when you log in, the form stays AND it displays welcome back, username. How can I get it so the login form is no longer shown after the user logs in? My plan is to create a top header on my finished site which will give the visitor the option to enter his user name and pass right from index.php Thanks, Chad

login or register to post comments

sublogin Part 2

Submitted by swattle on September 29, 2004 - 19:06.

If it is any help I posted the actual source, including all php references in my index file. You can view it at http://www.swattle.com/index2.txt

login or register to post comments

What else?

Submitted by jpmaster77 on September 29, 2004 - 20:01.

swattle,
Your code displays welcome back and then the form because you don't have an else statement. It should be:

if($session->logged_in){

...

}
else{

...

}


So to fix it, add the else statement. It is in the original main.php, so be careful when you edit stuff or just copy and paste code, you might forget something.

JP

login or register to post comments

Public Domain?

Submitted by fu_fish on September 30, 2004 - 05:35.

Are these scripts released to the public domain for use by anyone, anywhere? They're a whole lot better implemented than my current login system.

login or register to post comments

Sure you can

Submitted by jpmaster77 on September 30, 2004 - 07:16.

fu_fish,
I wrote this Login System for everyone for use on anything. If you would like to use it, please DO, because that's the whole purpose of it.

Thanks for checking it out,
JP

login or register to post comments

reply

Submitted by domostick on September 30, 2004 - 14:08.

sorry but i didnt get it, no exlanation of where it goes lol. just comes up with an error

login or register to post comments

jpmaster77

Submitted by dirtboy on September 30, 2004 - 18:56.

The Grandmaster of C++ has struck again.................................
awesome script.
Thanks,

login or register to post comments

reply

Submitted by domostick on October 1, 2004 - 13:39.

hey dirtboy sorry about that night, just angry from school and stuff. can you help me where the php coding goes to hide the html of people who arent logged in?

login or register to post comments

main.php

Submitted by jpmaster77 on October 1, 2004 - 16:57.

domostick,
I don't get what the problem you're having is. If you look at main.php, it checks whether or not the user is logged in, if so it displays the HTML for logged in users (basically links to relevant pages), if not it displays the login form.

What more are you looking for? For a general protected page, for users who are logged in you display the protected page HTML, for users who are not logged in you display an error message. This can be done with an if-else, and the variable you are checking is $session->logged_in, which can be used when session.php is included.

Let me know if this solves your problem,
JP

login or register to post comments

Hey jpmaster77

Submitted by Glytch on October 2, 2004 - 01:26.

I'm a newbie to PHP and so far this has been great (the script) and very easy to setup, but I was wondering how to change the URL after successfully logging in, or including more in main.php after logging in. I tried what you were talking to swattle about, just replacing $session->referrer with a URL but it didn't work, or is that not what I was supposed to do? Any help would be much appreciated. Cheers, Glytch

login or register to post comments

repl

Submitted by domostick on October 2, 2004 - 08:08.

Thanks for trying to help me jp, but I see in the first session the else statment to put my html. But where do I place it? Before or after }
else{
I tried both but they both come up with an error

login or register to post comments

domostick

Submitted by dirtboy on October 2, 2004 - 08:54.

My friend open up main.php and just look and read the code.
Do you see the line that says
if($session->logged_in){

echo "Logged In";
echo "Welcome $session->username, you are logged in.

"
."[username\">My Account] "
."[Edit Account] ";
if($session->isAdmin()){
echo "[Admin Center] ";
}
echo "[Logout]";
What that code does is it checks to see if the user is logged in and Grandmaster of C++ has added if they are logged in are they a user or admin. Then the rest of the code after
}
else
{
displays the message to non logged in users
"which is why it displays the login box form"

login or register to post comments

domostick

Submitted by dirtboy on October 2, 2004 - 08:56.

You place what message you want logged in users to see before the }else{ statement and what you want non logged in users to see after the }else{ statement.

login or register to post comments

reply

Submitted by domostick on October 2, 2004 - 17:27.

like i said before any way i place it, it comes up with a parse code error on line 74.

login or register to post comments

domostick

Submitted by dirtboy on October 2, 2004 - 17:44.

why dont you post your code so we can see it ?

login or register to post comments

reply

Submitted by domostick on October 2, 2004 - 18:21.

got it to work but now i cant logout. You click logout but it just reloads the page and doesnt log out.

login or register to post comments

domostick

Submitted by dirtboy on October 2, 2004 - 18:48.

I do not know what you have done to the code for that error ..........

But I do know there is nothing wrong with this script straight out of the zip file

login or register to post comments

Explain

Submitted by jpmaster77 on October 2, 2004 - 23:02.

Glytch,
Are you still having a problem? What's the problem exactly. If you want to redirect the user to some specific page after they log in, you need to modify process.php. Find the function where it processes the login form, then modify the header call. By default it is:

if($retval){

header("Location: ".$session->referrer);

}


But you can hard code a specific page for it to go to by changing it to:

if($retval){

header("Location: somepage.php");

}


Hope this helps,
JP

login or register to post comments

HELP!

Submitted by jaimeharvey on October 3, 2004 - 13:59.

Hi all,

Fantastic script - I am trying to get my head round most of it, but it works like a charm "out the box"!

Really fundamental question here - how do you add other fields like email etc??

Here is what I have tried so far... (only code shown is code that I have changed). Every time I click the register button, it gives me the 'registration failed page'

Thanks in advance!

register.php and process.php below that

<table align="left" border="0" cellspacing="0" cellpadding="3">
<
tr><td>Username:td><td>value("user");
?>
"> Password:value("pass"); ?>"> Email:value("email"); ?>"> ?>

process.php

function procLogin(){
global
$session, $form;
/* Login attempt */
$retval = $session->login($_POST['user'], $_POST['pass'], $_POST['email'], isset($_POST['remember']));

/* Login successful */
if($retval){
header("Location: ".$session->referrer);
}
/* Login failed */
else{
$_SESSION['value_array'] = $_POST;
$_SESSION['error_array'] = $form->getErrorArray();
header("Location: ".$session->referrer);
}
}
?>

login or register to post comments

Stupid me

Submitted by jaimeharvey on October 3, 2004 - 14:09.

ok - FORGET EVERYTHING I JUST SAID

Just got totally confused - very sorry!!!

login or register to post comments

User Account Edit

Submitted by peterc on October 4, 2004 - 03:30.

Excellent script, JP. Thank you. While working through it I have picked up this problem. When useredit.php opens, it shows empty curpass and newpass fields with the email of the logged on user displayed. Without entering anything, if I click the Edit Account button, I am advised that the account has been successfully updated. Shouldn't it advise me that both password fields are empty? When something is entered in either field, it seems to work OK.

login or register to post comments

Account Edit

Submitted by jpmaster77 on October 4, 2004 - 08:10.

peterc,
What if you want to just modify your email address and you don't want to change your password? That's how the account edit page works, if something is entered into either password field, it assumes you want to change your password, so it does error checking on those two fields. However, if you don't enter anything in either of the two fields, it assumes you don't want to change your password, just your email.

JP

login or register to post comments

Protecting Pages

Submitted by jaimeharvey on October 4, 2004 - 11:13.

Hi guys, What is the code needed at the top of new pages (that I have created - not in the download) in order to protect them - i.e. only allow access to users that have logged in? Thanks

login or register to post comments

Account Edit

Submitted by peterc on October 4, 2004 - 12:35.

JP Yes, I get it. Many thanks again - really good script. Peter

login or register to post comments

Protected Page

Submitted by jpmaster77 on October 4, 2004 - 14:46.

jaimeharvey,
To make protected pages you want to use the $session->logged_in variable, but make sure session.php is included before you try and use it, or else it will give you an error.

Example: protected.php

include("include/session.php");


if($session->logged_in){
echo "You are viewing the protected page";
}
else{
echo "You are not allowed to view this page";
}
?>


Make sure the included path to session.php is correct in the page you actually want to protect, and you can insert HTML code into the if statement to actually display the page and not just a message.

Hope this helps,
JP

login or register to post comments

Thanks

Submitted by jaimeharvey on October 5, 2004 - 09:11.

Thats great - thanks very much!

Ever considered a job in customer service!!

login or register to post comments

More questions!

Submitted by jaimeharvey on October 5, 2004 - 14:55.

Having spent more time working on these pages I have noticed 2 things: 1. The question I asked earlier was really very stupid (!) and 2 how logically they have been put togther!

One question though, I have modified the database with other fields etc, and what I have done is on the admin page I have added a link on the users table to go the the userinfo.php page about that user (which works fine).

However, earlier I had modified that page (userinfo) so that anyone other than the user whos details they were could not access the page (see code). Is there anyway to change the IF statment to IF(session username OR admin)???

Thanks, Jamie

/* Requested Username error checking */
$req_user = trim($_GET['user']);
if(!
$req_user || strlen($req_user) == 0 ||
!
eregi("^([0-9a-z])+$", $req_user) ||
!
$database->usernameTaken($req_user)){
die(
"Username not registered");
}

/* Logged in user viewing own account */
if(strcmp($session->username,$req_user) == 0){
echo
"My Account";
}
/* Visitor not viewing own account */
else{
echo
"You are not authorised to view this information";
}

/* Display requested user information */
$req_user_info = $database->getUserInfo($req_user);


/* Usename */
if(strcmp($session->username,$req_user) == 0){
echo
"Username: ".$req_user_info['username']."
"
;
echo
"Email: ".$req_user_info['email']."
"
;
echo
"Title: ".$req_user_info['title']."
"
;
echo
"Forename: ".$req_user_info['forename']."
"
;
echo
"Surname: ".$req_user_info['surname']."
"
;
echo
"Address 1: ".$req_user_info['address1']."
"
;
echo
"Address 2: ".$req_user_info['address2']."
"
;
echo
"City: ".$req_user_info['city']."
"
;
echo
"County: ".$req_user_info['county']."
"
;
echo
"Postcode: ".$req_user_info['postcode']."
"
;
echo
"Phone number: ".$req_user_info['telephone']."
"
;
echo
"Mobile number: ".$req_user_info['mobilephone']."
"
;
}
?>

login or register to post comments

Great Script

Submitted by paulo61 on October 5, 2004 - 14:57.

This is a great scrip - works out of the box and easy to customise and maintain. I have a question about the logout logic. It seems that when a user los out they are demoted to guest level and guests expire after 5 minutes by default. Is there anyway to have logouts take affect immediatly, could I define GUEST_TIMEOUT as 0 for example. The best thing about this code is the supporting documentation - paul.....

login or register to post comments

More Answers

Submitted by jpmaster77 on October 5, 2004 - 20:49.

jaimeharvey,
You want to use the $session->isAdmin() function, it returns true if the user that is logged in has admin priviledges.

if(strcmp($session->username,$req_user) == 0 ||

$session->isAdmin()){
echo "You are allowed to view this page";
}


paulo61,
I would not recommend setting GUEST_TIMEOUT to 0, because then your site will never know when guests are viewing the site. You could of course decrease it to 1 perhaps, if you think 5 is too much. What I would suggest you do is remove one line from the logout() function in session.php, the one that adds the user that just logged out to the active guests table. So find and remove or comment out this line:

$database->addActiveGuest($_SERVER['REMOTE_ADDR'], $this->time);


Its near the end of the logout() function.

Hope this helps,
JP

login or register to post comments

HELP.

Submitted by deppie on October 6, 2004 - 12:36.

x__X http://rebel.urban-ducks.net ...All that's on line 14 is a "{" ... Please help. Sorry- I'm kinda new to PHP.. -Rae

login or register to post comments

Protected pages

Submitted by Brewman on October 6, 2004 - 13:52.

JP .... in the Protected page comment ... you mentioned "you can insert HTML code into the if statement to actually display the page and not just a message." Could you please show an example of how to insert the HTML correctly. I've tried various ways ... I'm new to PHP and I'm sure I'm missing the correct coding. I placed the HTML code inside the quote marks after the echo statement.

login or register to post comments

Help and Protected HTML

Submitted by jpmaster77 on October 6, 2004 - 15:50.

deppie,
It tells me you're getting an error when trying to connect to your database, "Access denied", make sure your database name and password information is specified correctly in constants.php. If you still can't connect after verifying the information, then ask your web host what you need to put in.

Brewman,
To insert HTML code directly into a php file, you need to close the php tag (insert "?>"). And then open the php tag when you want to use php again (insert "
Example: protected.php
include("include/session.php");

?>


Protected Page

/* User is not logged in */
if(!$session->logged_in){
?>


Insert HTML code here that says "You are not allowed to view this page"


}
/* User is logged in */
else{
?>


Insert HTML code here that says "This is the protected page"


}
?>




Notice that I switched it up in the example, such that the first "if" clause checks if the user is NOT logged in, the reason is most of the time the HTML code that goes in the "if" statement is a lot shorter than the code that goes in the "else".

JP

login or register to post comments

Protected 2

Submitted by jpmaster77 on October 6, 2004 - 15:57.

Brewman,
Sorry the code I gave you was suppose to include HTML tags and they didn't show up, heres what I wanted to show:

Example: protected.php
include("include/session.php");

?>


Protected Page

/* User is not logged in */
if(!$session->logged_in){
?>


Insert HTML code here that says "You are not allowed to view this page"


}
/* User is logged in */
else{
?>


Insert HTML code here that says "This is the protected page"


}
?>




JP

login or register to post comments

Thanks so much!

Submitted by Brewman on October 6, 2004 - 16:29.

JP ... your awesome! The script is now running flawlessly. Thanks so much for your help.
By the way, this script is the best php login script on the web.

login or register to post comments

Well Script.

Submitted by sathiyan_lee on October 6, 2004 - 23:01.

This is really a fanatastic scripts I have ever seen. It looks very simple to undestand. Lot of thanks to you JP

login or register to post comments

I always get the "Username below 5 characters"

Submitted by robmorin on October 8, 2004 - 06:44.

No matter how many i type?? Any suggestions? When i go to register... for the first time Thanks Rob

login or register to post comments

Excellent scripts but...

Submitted by gonzalezamado on October 8, 2004 - 08:05.

I am new with PHP and these scripts look like what I was looking for. But my actual case scenario is quite special. I am unable to access any DBMS from my ISP, so I will need to implement it using a flat file "database" system. Is it possible? What should be adapted to accomplish that approach? JP, thank you in advance for all the help you can provide

login or register to post comments

Flat file database

Submitted by jpmaster77 on October 8, 2004 - 11:26.

gonzalezamado,
I initially was going to write a flat file database for this Login System, specifically for people in your position, but I quickly realized that all the features I wanted (tracking active visitors, etc.) could not really be achieved, or at least to the level that I wanted them to, with a flat-file database. They don't scale to large number of users and you can't write to the same file at the same time, so that basically means a huge performance decline. But, those are the drawbacks of flat file databases, and you can't do anything about that.

You have two options, the first is to write a simple flat file database that doesn't support tracking active visitors (just stores user information and looks it up). This would take some time to get right, but it shouldn't be that hard. The other is to find a pre-existing flat file database on the web that you can just insert for use on your website. I found this one while searching google: FFDB. It's pretty advanced so you may get the active visitors thing working. So just think about that, and I'm sorry I don't have code to give you that I've written.

robmorin,
I'm not sure I understand the problem you're having, it works when you register but just not on the first time you load the page? It gives you that error. Look at register() function in session.php, that's where it checks the length of the string you entered. However it trims the string and calls stripslashes() on it before it checks the length. I'd suggest you echo the string it's checking for debugging this problem. I don't know why it wouldn't work on the first try, but on subsequent tries it does.

login or register to post comments

Using list boxes - How?

Submitted by SunCoder on October 10, 2004 - 03:24.

Hi, Currently, the register/main php scripts are using text boxes, such as: value("pass"); ?>"> for example. But how to use the php code within a list box, such as: Germany USA UK How exactly must the php code look alike in that listbox? Please let me know. I tried several possibilities but none seemed to work. Otherwise, the login script is great, it worked out of the box. Unlike the previous one which does not performed redirection on one of my pc's using IE (but was ok with NS), for whatever reasons, but worked on other pcs and configurations including IE from me. Never figured out why exactly it had problems with IE. Thanks JP for developing and sharing the new code with us

login or register to post comments

Using list boxes - How? (II)

Submitted by SunCoder on October 10, 2004 - 03:31.

Sorry, the text above looks a little bit confusing, not exactly what i have expected after the preview. I should however be clear what I mean: How must the complete list box (including php code) look alike. A small sample would be much appreciated. Thanks.

login or register to post comments

List boxes

Submitted by jpmaster77 on October 10, 2004 - 17:05.

SunCoder,
You'd have to check every list item and see if the value given by the list name is equal to the list item value, if so, you print out "selected" inside the option tag. That's what tells the HTML which item is selected.

Example:



Hope this helps,
JP

4 Ace Technologies