Page 1 of 3 123 LastLast
Results 1 to 25 of 52
  1. #1

    PHP MySQL members system

    Hi, i am looking for some tutorials for PHP/MySQL on how to make a member system. Here are the things that I want to be able to do:

    [list=1][*]Users Online displayed, can be broken down in to (Members and Guests) For e.g. 15 Users online, 5 members and 10 guests. And also the ability to show the members that are online in a list.[*]PHP Sessions[*]User can click Remember Me, so next time they return they are automatically logged in.[/list=1]

    Thanks,
    Matt
    http://www.theextremenetwork.com
    MSN: webmaster@theextremenetwork.com

  2. #2
    Join Date
    Jun 2002
    Location
    Sherbrooke, Québec
    Posts
    184
    You know the parts of the system. What exactly is you question? On what part do you have problems?

  3. #3
    lots of scripts you can download free that do this.

    if you wanna code it yourself, best place to start is www.php.net and www.zend.com you might also go visit www.devshed.com and www.sourceforge.net maybe check out hotscripts.com, download crimson editor www.crimson.com and probably you'll want to go to www.google.com and search for "php tutorial" and you'll find literally hundreds of php tutorials. lots of CMS systems also show users online/member/guest breakdown (phpNuke and Postnuke for example)

    lots of places to look for this stuff.

  4. #4
    Thanks, I have just put this together, but need help. I dont understand all the session stuff. Well, heres what ive got, i want it to kind of work like these forums.

    index.php
    PHP Code:
    //+----------
    // Member Box
    //+----------
    if (//REMEMBER ME COOKIE EXISTS//) {
    // Auto make logged in session stuff??
    }
    if (
    //MEMBER IS LOGED IN//) {
        
    echo "Welcome //$username//
        <a href=\"logout.php\">Logout</a>"
    ;
    }
    else {
        echo 
    "<form method=\"post\" action=\"login.php\">
        Username: <input type=\"text\" name=\"username\" size=\"20\"><br />
        Password <input type=\"text\" name=\"password\" size=\"20\"><br />
        <input type=\"checkbox\" name=\"rememberme\" value=\"??\"> Remember Me<br />
        <input type=\"submit\" value=\"Login\" name=\"submit\">
        </form>"
    ;
    }
    //+----------
    // Stats Box
    //+----------
    $query "SELECT * FROM stats WHERE id = '1' LIMIT 1";
    $result mysql_query($query) or die("Mysql Error: " mysql_error());
    $row mysql_fetch_array($result);
    $total_online = ($members_online+$guests_online);
    echo 
    "$total_online Users online<br />
    $members_online Members Online<br />
    $guests_online Guests Online<br />
    Most Ever Online: 
    $most_online"
    login.php
    PHP Code:
    if(($_POST["username"]) || ($_POST["password"])) {
        
    $query "SELECT username, password FROM members WHERE username = '".$_POST["username"]."' AND username = '".$_POST["password"]."' LIMIT 1";
        
    $result mysql_query($query) or die("Mysql Error: " mysql_error());
        
    $row mysql_fetch_array($result);
        
    $rows mysql_num_rows($result);
            if (
    $rows 0) {
                <
    meta http-equiv='refresh' content='3;URL=index.php'>
                echo 
    "Thank You for loging in, you are now being transfered.";
            }
            else {
                echo 
    "Invalid Username or Password";
            }
    }
    else {
        echo 
    "Please fill out the reqired fields";

    logout.php
    PHP Code:
    ???? 
    Thanks,
    Matt
    Last edited by ballingtonma; 04-27-2004 at 01:11 PM.
    http://www.theextremenetwork.com
    MSN: webmaster@theextremenetwork.com

  5. #5
    Join Date
    Oct 2003
    Posts
    124
    PHPLIB can do most of this for you.

    https://sourceforge.net/projects/phplib/

  6. #6
    Originally posted by ballingtonma
    Thanks, I have just put this together, but need help. I dont understand all the session stuff. Well, heres what ive got, i want it to kind of work like these forums.

    index.php
    PHP Code:
    //+----------
    // Member Box
    //+----------
    if (//REMEMBER ME COOKIE EXISTS//) {
    // Auto make logged in session stuff??
    }
    if (
    //MEMBER IS LOGED IN//) {
        
    echo "Welcome //$username//
        <a href=\"logout.php\">Logout</a>"
    ;
    }
    else {
        echo 
    "<form method=\"post\" action=\"login.php\">
        Username: <input type=\"text\" name=\"username\" size=\"20\"><br />
        Password <input type=\"text\" name=\"password\" size=\"20\"><br />
        <input type=\"checkbox\" name=\"rememberme\" value=\"??\"> Remember Me<br />
        <input type=\"submit\" value=\"Login\" name=\"submit\">
        </form>"
    ;
    }
    //+----------
    // Stats Box
    //+----------
    $query "SELECT * FROM stats WHERE id = '1' LIMIT 1";
    $result mysql_query($query) or die("Mysql Error: " mysql_error());
    $row mysql_fetch_array($result);
    $total_online = ($members_online+$guests_online);
    echo 
    "$total_online Users online<br />
    $members_online Members Online<br />
    $guests_online Guests Online<br />
    Most Ever Online: 
    $most_online"
    login.php
    PHP Code:
    if(($_POST["username"]) || ($_POST["password"])) {
        
    $query "SELECT username, password FROM members WHERE username = '".$_POST["username"]."' AND username = '".$_POST["password"]."' LIMIT 1";
        
    $result mysql_query($query) or die("Mysql Error: " mysql_error());
        
    $row mysql_fetch_array($result);
        
    $rows mysql_num_rows($result);
            if (
    $rows 0) {
                <
    meta http-equiv='refresh' content='3;URL=index.php'>
                echo 
    "Thank You for loging in, you are now being transfered.";
            }
            else {
                echo 
    "Invalid Username or Password";
            }
    }
    else {
        echo 
    "Please fill out the reqired fields";

    logout.php
    PHP Code:
    ???? 
    Thanks,
    Matt
    Oh boy... PLEASE use something like phplib..
    or cruise around sourceforge.. borrow "auth.php" from TKI (www.sourceforge.net/projects/kabal-invasion) which has soem well tested and secured code that you can depend on to be less-exploitable. (anyone who says their code is NOT EXPLOITABLE is a fool, or their whole script consists of

    Code:
    <?php
     echo"hello world";
    ?>
    I'm sorry to say but the code you posted has so many security holes, might as well just say "hey if you're visiting just SQL inject your username and password and I'll let you in"

    before you code PHP, and while you are learning it...and while you're writing it.. always but always repeat after me.. NTUI!!! NTUI!!! NTUI!!!

    Never Trust User Input!

    definitely needs a lot of work in that regard..

  7. #7
    Thanks, but that link doesnt work. How would i make that secure, like stop people entering things such as < and >?
    http://www.theextremenetwork.com
    MSN: webmaster@theextremenetwork.com

  8. #8
    Oh boy.. it's a LOT more than just preventing stuff like < and >...

    you need to do stuff like verify the integrity of the user inputs, you need to validate WHERE the inputs come from... you need to make sure the inputs are limited to what you EXPECT the user to input, and nothing more. (i.e if you expect an e-mail input, use a regexp to check and make sure it is actually an email address format, make sure there are no newlines or linebreaks being injected, make sure the data is double checked before any MySQL queries, make sure they cant repetitively attempt to login (limit login attempt failures to no more than 3 or 4 per DAY) etc, etc, etc... there's a LOT that really should be ideally checked..

    as far as the link, I typo'd it.. it's ...

    http://sourceforge.net/projects/kabalinvasion/

    I'm a project admin there, so Im familiar with the code- basically you can read into the login, login2 and auth.php scripts (along with md5.js) which basically secures user login and passwords with some pretty darn good security in mind.

    The lead developer is senior security analyst for a very big nationwide corporation, so you can understand I worked with someone who is absoultely PARANOID about security.....

    the code continues to evolve, but I'd say the auth.php and the login process you will find in TKI would give you a great start for a user auth code..

    of course, it is open source GPL and free..

    I can get you some regexp's examples that I use, and a quite authorative e-mail syntax validation checker (all open source as well) .. feel free to PM me on AIM at id trukfixer.. or just drop a trouble ticket at emceehosting.net.... (which of course is still in development as I find time- it's only a hobby)
    Last edited by trukfixer; 04-27-2004 at 05:23 PM.

  9. #9
    Thanks trukfixer, PHP already has md5 so why do you need a javascript file? http_referer is unreliable so whats the point using it? I am trying to get it secure but with out javascript if possible because I am trying to get everything server side as it is other wise unreliable, as you say, user side cannot be trusted nor relied on. People can easaly disable javascript.

    Hows this now:
    PHP Code:
    <?
    if ($_POST["username"] && $_POST["password"]) {
      
    $username ereg_replace("\n"""strtolower(trim($_POST["username"])));
      
    $password ereg_replace("\n"""strtolower(trim($_POST["password"])));

      if (
    ereg("[^a-zA-Z0-9_-]",$username) || ereg("[^a-zA-Z0-9_-]",$password)) {
        echo 
    "Invalid Username or Password";
      }
      else {
        echo 
    "It's Good To Go..."// So Do Login Process With MD5 For Password.
      
    }
    }
    else {
      echo 
    "Invalid Username or Password";
    }
    ?>
    Thanks, Matt
    http://www.theextremenetwork.com
    MSN: webmaster@theextremenetwork.com

  10. #10
    Join Date
    Apr 2004
    Posts
    32
    Originally posted by trukfixer
    Oh boy... PLEASE use something like phplib..
    or cruise around sourceforge.. borrow "auth.php" from TKI which has soem well tested and secured code that you can depend on to be less-exploitable. (anyone who says their code is NOT EXPLOITABLE is a fool, or their whole script consists of

    Code:
    <?php
     echo"hello world";
    ?>
    I'm sorry to say but the code you posted has so many security holes, might as well just say "hey if you're visiting just SQL inject your username and password and I'll let you in"

    before you code PHP, and while you are learning it...and while you're writing it.. always but always repeat after me.. NTUI!!! NTUI!!! NTUI!!!

    Never Trust User Input!

    definitely needs a lot of work in that regard..

  11. #11
    Join Date
    Jun 2002
    Location
    Sherbrooke, Québec
    Posts
    184
    if (ereg("^[a-zA-Z0-9_-]{3,8}$", $_POST["username"]) && ereg("^[a-zA-Z0-9_-]{6,15}$", $_POST["password"]))
    {
    echo "Format ok... let's match the credentials with users in DB";
    }

    I don't see why you want to lower case them and then allow upper case characters into the regex latter. Triming is good, but did you know \n is already trimed out by trim() ?

    They told you to validate the data, not to pass it through all possible functions untill there is no usefull data left

    Maybe you should practice with something somewhat easier. Are you really going to write yet another vBulletin/phpBB/NameYourBoardSystemWrittenInPhpHere ?

  12. #12
    Join Date
    Jul 2003
    Location
    Kuwait
    Posts
    5,104
    mysql_escape_string() will help you avoid some injection attacks. If you code your script without attention, then the only one to blame is you.

    Why don't you consider using something like PEAR::Auth to help you with authentication? Or any number of other pre-written scripts? There is also this excellent zend article that details authentication procedures.

  13. #13
    Im trying to make a simple CMS with a member system. Thanks, What does this bit do?
    PHP Code:
    {3,8
    Last edited by ballingtonma; 04-28-2004 at 08:12 AM.
    http://www.theextremenetwork.com
    MSN: webmaster@theextremenetwork.com

  14. #14
    Oh, i see it it the length now, but what does the second digit after the comma do? becasue if its the maximum length it doesnt work
    http://www.theextremenetwork.com
    MSN: webmaster@theextremenetwork.com

  15. #15
    The md5.js Javascript is for CLIENT SIDE security- it MD5()'s the password BEFORE it gets sent from the client, so "sniffers" can't sniff out your password (which otherwise gets sent to the server by cleartext) We're working on an even MORE secure password authentication that will eliminate the need for JavaScript.

    With the md5.js, you cant store a password for later re-use (I.E. autocomplete fails) forcing the user to enter their password EVERY TIME....

    secures the user's password as well as the server. of course users can disable JavaScript at their own risk (small as it may be) but the server side is secure enough.

    The regexp's are used to clean up user inputs. the ^ (caret) in a regex means match anything BUT these characters and replace them with null (I.E. enter MyName123;<?php var_dump($_SESSION);?> )

    and the result of the regexp is like this:

    MyName123phpvardumpSESSION

    which breaks any attempt to inject php nasties.....

    so with the ^ caret we ALLOW the lowercase, uppercase and digits with a minimum length input of 3 and max length of 8 for username..

    another, shorter (but less explicit) way to allow letters and digits would be simply \[^\w\d\s\] which also permits spaces (\s) with an ereg_replace

    and to answer the remaining question as to "why allow UpperCase later when you already do strtolower" ..

    because we are checking the input as a string to make sure we have CLEAN input, (you can get around $_POST, you know?) and we check against the username in the database (which is also all lowercase) Allowing CAPS in a regexp does nothing if the input is already lowercased, but it DOES catch you up when you try to escape/break the login sequence to inject your own username.

    the way we have it, it wont matter if someone leaves the capslock key on, they will have a valid login if the characters are correct.

    Finally, we dont worry about identical usernames that way, everything's lowercased, and we check using metaphone() at signup time to make sure no one gets a username that is TOO similar to someone else's...

    I DID say we're a bit paranoid about security, no?

    so basically if you login using :
    MyName123
    myName123
    MYNAME123
    myname123
    myName123.
    you will login successfully if you give the correct password, and your password is secured from the client to the server (md5.js) and your inputs are cleaned up so you dont inject any sql or nasty php tricks, and finally checked just before entering the authentication to ensure you dont try to trick us, by escaping the script and modifying header information and sending it to the rest of the script.

    further, we DO use mysql_escape_string immediately before the sql queries, we use ADOdb database abstraction layer with encrypted sessions, so we have multiple layers of security, redundant as they may seem.. just can't be TOO secure.

    and all of this for just a GAME.. imagine what kind of code we'll be using for something more critical, such as a shopping cart or payment gateway?

  16. #16
    Join Date
    Aug 2003
    Location
    PA
    Posts
    110
    Top ten for making your php files and site more secure, not 100%, but close....

    1)If you use files that include the password to log into your database, at the very least, place these files above the public_html/ file, and include them through the directory.

    2)Always end included php files with .php. The only exceptiong should be if you have passed a server directive to read the file extension(usually .inc) that you have used as an include as a .php file.

    3)Always check included files for the calling script. This is simply:
    PHP Code:

    if($_SERVER['SCRIPT_FILENAME']=="/home/account/www/main_calling_file.php")
       
    $do_something_good;
    else
       
    exit_or_error_code
    4)Always check the following data requirements:
    =Type
    =Length
    =Referrer
    =HTML Tagging
    =SQL Commands(specifically ',%,<,>,drop,delete,insert)

    5)Always 'quote-out' string variables in SQL queries.

    6)Never give 'DROP' access to database users with your .php scripts.

    7)Never assume Javascript validation caught anything.

    8)Never use $_REQUEST variables.

    9)Never assume $_POST is any more secure than $_GET in reality, it simply lets more data be passed as arguments through the http:// protocol, including more types, and larger strings and instances.

    10)Never assume a user knows what he or she must or should type in....and worse yet, ALWAYS assume a user is entering exactly what they want to. The people typing special characters or finger-botching a number instead of a letter to break your alpha string is one thing. The person that knows that they are using SQL injection is far worse.

    Those are a BIG few to get started. These security constraints, plus using md5 for passwords, takes your security a lot further than simply trusting that your user is doing exactly what you want and need them to do.

    Take care!

  17. #17
    Thanks, so the config file would have to go in the www folder rather than public_html, even if you set particular permisions to the file?
    What are 'quote-out' string variables in SQL queries, how do i do that?
    PHP Code:
    ereg("^[a-zA-Z0-9_-]{4,20}$"$_POST["username"]) && ereg("^[a-zA-Z0-9_-]{6,15}$"$_POST["password"]) 
    That seems to check for everything. I cant get http_referer working, maybe because of my firewall?
    Last edited by ballingtonma; 04-28-2004 at 11:07 AM.
    http://www.theextremenetwork.com
    MSN: webmaster@theextremenetwork.com

  18. #18
    Join Date
    Jun 2002
    Location
    Sherbrooke, Québec
    Posts
    184
    You should learn more than the basics regarding regex's. They are very powerful when you know how to use them.
    Regex guide: http://pack.homelinux.com/break-in-it/regexguide.html
    It's a long reading, but don't skip a part. Make sure you understand every words and test with example after every paragraphs. It's not easy to get everything, but some day you'll be happy Tom told you to learn it

    Yes, the second number in {3,8} is the maximum number of characters, while the first one is the minimum. And it works perfectely, when you understand the regex. In particular make sure you use both ^ and $ or the limits are effectively useless.

    I cant get http_referer working
    Two things to check:
    - First it has to be upper case like any other predefined constants:
    http://www.php.net/reserved.variables
    - You got to have a referer. That is, make sure you came to the page by clicking a link, not typing the URL into the location bar.

  19. #19
    Thanks, I have been using it in capitals, like this:
    PHP Code:
    echo "Referer: ".$_SERVER['HTTP_REFERER']; 
    It just doesnt work.
    http://www.theextremenetwork.com
    MSN: webmaster@theextremenetwork.com

  20. #20
    Might be an issue with globals, but as was said, it will NOT work if you go to the page directly. try this: make an index.html page linking to that script and then grab the referrer. Perhaps you would be more likely to want to get the IP address instead? also depending on what version of PHP you have, you may have to declare the full global as:
    PHP Code:
    echo "Referrer: ".$HTTP_SERVER_VARS['HTTP_REFERRER']; 
    Also, note carefully your spelling- there's 2 R's in Referrer

    your example is misspelled.

    Next- the regexps can be quite complicated and the learning curve may be steep, but once you know them, you will be so very glad that you do.

    (php DOES have "c_type" functions that essentially do the same thing, so search php.net for c_type, that might make some things a bit easier)

    Now, as to your config file.. NEVER name it "config.inc" .. always name it config.php, set the permissions to the minimum (it will work with CHMOD 004, by the way, which is about as secure as you can get with it)

    While it isnt NECESSARY to put your config file BELOW your public_html directory (and NO!!! www directory is NOT different from public_html- www MAPS TO public_html. )

    Assume your account has the following path from ROOT. -

    /home/your_username/public_html

    in this case, you would put your config into the /home/your_username directory, NOT in www or public_html, and that will keep anyone from the outside from reading it. (they have to hack into your account to see it)

    HOWEVER, you will have to explicitly set the path to your config file in all of your scripts (if you have a script in public_html, then when you want to include config.php, you have to either :
    PHP Code:
    define("CONFIG","/home/your_username/config.php");
    //and then include("CONFIG"); 
    or
    PHP Code:
    include("../config.php");
    //only for files that are in public_html. 
    but as long as you NEVER name it with a .inc extension, you should be OK, and of course, you can ALWAYS add this tidbit

    PHP Code:
    if (preg_match("/config.php/i"$_SERVER["PHP_SELF"]))
     {
          echo 
    "You can not access this file directly!";
          die();

    put that as the first code in the top of any included files (I.E. those that are not directly accessed by browser) and you can pretty much prevent viewing of the files. (or be tricky and use header() to re-direct them instantly to a file that doesnt exist, so they'll think "oh, there is NO config.php file, wonder what they call it?")
    so you wont have to worry about figuring out the path to your config file, which can get rather complicated in multi-tiered folder structures.

    Bri!
    Last edited by trukfixer; 04-28-2004 at 03:08 PM.

  21. #21
    Oh yeah. .. "quote out string variables" in your sql statements means make sure they are quoted, and not just included.

    Examples:
    PHP Code:
    $res=mysql_query("SELECT * FROM table WHERE username= $username");

    //BAD, BAD, BAD!

    $res=mysql_query("SELECT * FROM table WHERE username='$username'");
    //MUCH BETTER- note single quoted variables (strings) 
    Next- ereg() regex would just match for those characters inside of the string, and do nothing else. just returns true or false, in teh case of teh expressions you gave as an example, valid username shuold return a "false"..

    but to actually CLEAN the inputs, you might do like ereg_replace() and replace matches with null values.

    (normally I would do a preg_replace. using Perl Compatible regexp's)

    In fact, there has been ONGOING discussion in this regard at Slashdot. (lemme go find it, Ill be back and post a link)... VERY valuable info for those who wanna LEARN to code securely

  22. #22
    OK. links to relevant parts of slashdot postings..
    http://developers.slashdot.org/artic...85&threshold=1


    http://developers.slashdot.org/comme...64&cid=8984484

    Those threads should tell you a *LOT* that you should know...

    (there's also a couple of postings in the thread somewhere that someone posted a glaring example of what we have already discussed in regards to the .inc extension.. you can find this stuff on GOOGLE!! and you suddenly discover that you have handed the keys to your server to a Hax0r .........on a silver platter...)

  23. #23
    Thanks,
    My host is running with PHP version 4.3.4 and these dont work:
    $HTTP_SERVER_VARS['HTTP_REFERRER'];
    $_SERVER['HTTP_REFERRER'];
    I have tryed them from a hyperlink referal and a form submit referal.
    Also, as im going to limit login attempts to 4 times a day, would the best option to be to save the failed attempts in a cookie? or would a table with the ip addresses in be better?
    Last edited by ballingtonma; 04-28-2004 at 06:16 PM.
    http://www.theextremenetwork.com
    MSN: webmaster@theextremenetwork.com

  24. #24
    Join Date
    Aug 2003
    Location
    PA
    Posts
    110
    PHP spelling is whack

    $_SERVER['HTTP_REFERER'];

    This is the actual variable.

    Take care.

  25. #25
    Yep. correct.. my bad..

    go here :

    http://us3.php.net/reserved.variables

    'HTTP_REFERER'

    The address of the page (if any) which referred the user agent to the current page. This is set by the user agent. Not all user agents will set this, and some provide the ability to modify HTTP_REFERER as a feature. In short, it cannot really be trusted.
    it would appear you wish to verify where the script came from, no?

    one way you can do so, is in the prior page (the referrer page) is to specifically set the 'http_referer' to PHP_SELF if it isnt already set , which I "think" might work.. I never use that anyway, as you can see from the quote- it's easily modified.

    what I would do if you want to verify that your script is being accessed ONLY by the page in question is to explicitly define a unique variable and check it in the next script. ..

    for example , in form.php do this:
    PHP Code:

    define
    ("FORM_PAGE","true");//(not sure if it should be quoted
    global FORM_PAGE
    and then in your auth.php check it thus:
    PHP Code:
    if(!FORM_PAGE)
    {
    die(
    "Wrong Referrer page!");
    }
    //if true, it ignores the above, if false, script dies 
    but that is off the top of my head, I havent tested it, its just an idea for an alternative...

    depends on what you wanna do.

Page 1 of 3 123 LastLast

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •