Go Back   Dynamic Drive Forums > General Coding > PHP
Search Dynamic Drive Forums:

Reply
 
Thread Tools Search this Thread
  #1  
Old 09-28-2007, 09:35 PM
TimFA TimFA is offline
Regular Coders
 
Join Date: Mar 2007
Location: Tarboro, NC
Posts: 290
Thanks: 8
Thanked 2 Times in 2 Posts
Default PHP Simple Passwording

Ok, I've asked alot form you guys recently, please come through on this for me. *Crosses fingers* Of course you'll be able to help. Ok, I would like a simple PHP password script that can process a form I have made the form has 2 fields. One named user, one named pass. The script needs to be able to take them and if they match place a cookie, then redirect. If not then, I guess an error page, or just refresh. W/e. And I need code to put on each page that if the cookie is there allows you to go, if not then it doesn't. And two more things, if possible I'd like it to be able to specify a link, such as the cookie has the ID 39653 so the PHP makes a link www.mysite.com/members/39653.html and the page already exists. I'm sure there are simpler ways of doing such things, but I suck at PHP, and JavaScript. Number 2, If possible another bit that if the cookie is present it hides a the login menu. Which is a DIV named login. I know it sounds long, but I don't think its too hard...Well, I shall wait.
Reply With Quote
  #2  
Old 09-28-2007, 10:24 PM
djr33's Avatar
djr33 djr33 is offline
Global Moderator
 
Join Date: Mar 2006
Location: N. California, USA
Posts: 6,408
Thanks: 11
Thanked 82 Times in 82 Posts
Default

Will this work for you? If not, what needs to be different?
http://www.twey.co.uk/?q=loginscript
__________________
Daniel - <?php?> | <html>| Ich lerne Deutsch. | Studio l'italiano. | Estudiaba español. | Estudo português. | 日本語の勉強。| मैं हिन्दी सीखो | درس العربية
Reply With Quote
  #3  
Old 09-28-2007, 11:47 PM
TimFA TimFA is offline
Regular Coders
 
Join Date: Mar 2007
Location: Tarboro, NC
Posts: 290
Thanks: 8
Thanked 2 Times in 2 Posts
Default

I'm sorry I can't view his site, anywhere else I can check it out?
Reply With Quote
  #4  
Old 09-29-2007, 12:58 AM
djr33's Avatar
djr33 djr33 is offline
Global Moderator
 
Join Date: Mar 2006
Location: N. California, USA
Posts: 6,408
Thanks: 11
Thanked 82 Times in 82 Posts
Default

Description

A simple, MySQL-based login script, for people who Just Want To Get On With It.
Updates

*
05/03/07

Removed dependence on register_globals. Thanks to Sean Tuohy for pointing this one out.
*
13/07/06

Updated script to fix typo pointed out to me by the webmaster of QueerFM.

Instructions

Create your database table:
Code:
create table users (id int auto_increment, nick text, password text, email text, primary key(id));
Alter the database login details at the top; modify the bits in plain HTML to match your site design; save to a file; include at the top of any PHP-enabled page you wish to protect. Having anything (DOCTYPE, HTML, HEAD, whitespace...) before the opening <?php tag of the block containing the include statement will cause the script to fail.

Code
Code:
<?php
/* Simple Login script, by Twey                    */
/* (http://www.twey.co.uk/)                        */
/* Released under the terms of the                 */
/* GNU General Public License, version 2 or        */
/* later. See http://www.gnu.org/copyleft/gpl.html */
/* for details.                                    */

  session_start();

  $userstable = 'users';
  mysql_pconnect('localhost', 'user', 'pass');
  mysql_select_db('database');

  function is_email($email) {
    $qtext = '[^\\x0d\\x22\\x5c\\x80-\\xff]';
    $dtext = '[^\\x0d\\x5b-\\x5d\\x80-\\xff]';
    $atom = '[^\\x00-\\x20\\x22\\x28\\x29\\x2c\\x2e\\x3a-\\x3c\\x3e\\x40\\x5b-\\x5d\\x7f-\\xff]+';
    $quoted_pair = '\\x5c\\x00-\\x7f';
    $domain_literal = "\\x5b($dtext|$quoted_pair)*\\x5d";
    $quoted_string = "\\x22($qtext|$quoted_pair)*\\x22";
    $domain_ref = $atom;
    $sub_domain = "($domain_ref|$domain_literal)";
    $word = "($atom|$quoted_string)";
    $domain = "$sub_domain(\\x2e$sub_domain)*";
    $local_part = "$word(\\x2e$word)*";
    $addr_spec = "$local_part\\x40$domain";
    return preg_match("!^$addr_spec$!", $email);
  }

  function head($title) {
?>
  <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
  <html>
    <head>
      <title><?php echo($title); ?></title>
      <style type="text/css">
        label {
          display: block;
        }

        label.registerError {
          border: 1px solid red;
        }

        span.registerError {
          font-weight: bold;
          color: red;
        }
      </style>
    </head>
    <body>
<?php
  }

  function foot() {
?>
    </body>
  </html>
<?php
  }

  function logout() {
    session_destroy();
    setcookie('nick', '', time() - 50);
    setcookie('pass', '', time() - 50);
    header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
  }

  function loginForm() {
    head("Log In");
?>
      <form action="<?php echo($_SERVER['PHP_SELF']); ?>" method="post">
        <p>
          <label>
            Username: <input type="text" name="nick">
          </label>
          <label>
            Password: <input type="password" name="pass">
          </label>
          <label>
            Remember me? <input type="checkbox" name="rem" value="true">
          </label>
          <label>
            <input type="submit" value="Log in">
          </label>
          <a href="<?php echo($_SERVER['PHP_SELF']); ?>?register">Register</a>
        </p>
      </form>
<?php
    foot();
  }

  function login() {
    global $userstable, $key;

    $data = isset($_POST['nick']) ? $_POST : $_COOKIE;

    $nick = mysql_real_escape_string($data['nick']);
    $pass = isset($_POST['nick']) ? md5($data['pass']) : $data['pass'];

    $rs = mysql_query("select * from $userstable where nick='$nick' and password='$pass' limit 1;");
    if(mysql_num_rows($rs) === 0)
      die(noSuchUser());
    else {
      $row = mysql_fetch_array($rs);
      $_SESSION['userid'] = $row['id'];
      $nextweek = time() + (7 * 24 * 60 * 60);
      $_SESSION['nick'] = $row['nick'];
      $_SESSION['pass'] = $row['password'];
      $_SESSION['email'] = $row['email'];

      if(isset($_POST['rem'])) {
        setcookie('nick', $_SESSION['nick'], $nextweek);
        setcookie('pass', $_SESSION['pass'], $nextweek);
      }
    }
  }

  function noSuchUser() {
    head('Error: User Doesn\'t Exist');
?>
      <h1>Error: User Doesn't Exist</h1>
      <p>
        The username/password combination you have entered is not in our database.  Please check that you have entered your username and password correctly.  If you have not yet registered, you may do so <a href="<?php echo($_SERVER['PHP_SELF']); ?>?register">here</a>.
      </p>
<?php
    foot();
  }

  function registerForm($vals = array('', '', ''), $errors = array()) {
    head("Register");
?>
      <form action="<?php echo($_SERVER['PHP_SELF']); ?>" method="post">
        <p>
          <label<?php if(isset($errors[0])) echo(' class="registerError"'); ?>>
            Username: <input type="text" name="nick" value="<?php echo(htmlentities($vals[0])); ?>">
            <span class="registerError">
              <?php if(isset($errors[0])) echo($errors[0]); ?>
            </span>
          </label>
          <label<?php if(isset($errors[1])) echo(' class="registerError"'); ?>>
            Password: <input type="password" name="pass" value="<?php echo(htmlentities($vals[1])); ?>">
            <span class="registerError">
              <?php if(isset($errors[1])) echo($errors[1]); ?>
            </span>
          </label>
          <label<?php if(isset($errors[2])) echo(' class="registerError"'); ?>>
            Email: <input type="text" name="email" value="<?php echo(htmlentities($vals[2])); ?>">
            <span class="registerError">
              <?php if(isset($errors[2])) echo($errors[2]); ?>
            </span>
          </label>
          <label>
            <input type="hidden" name="register" value="true">
            <input type="submit" value="Register">
          </label>
        </p>
      </form>
<?php
    foot();
  }

  function register() {
    global $userstable;

    $nick = mysql_real_escape_string($_POST['nick']);
    $pass = $_POST['pass'];
    $email = mysql_real_escape_string($_POST['email']);

    if(mysql_num_rows(mysql_query("select * from $userstable where nick='$nick';")))
      die(userExists($_POST['nick']));

    $errArr = array(
      empty($_POST['nick']) ? 'Username must not be empty' : null,
      empty($_POST['pass']) ? 'Password must not be empty' : null,
      empty($_POST['email']) ? 'Email must not be empty' : null
    );
    $valArr = array(
      $_POST['nick'],
      '', // We don't restore the user's password value, since this is the default in most browsers, and the user will expect it.
      $_POST['email']
    );

    if(strlen($_POST['nick']) > 20)
      $errArr[0] = 'Username cannot be longer than 20 characters';
    if(strlen($_POST['pass']) < 7)
      $errArr[1] = 'Password must be longer than 7 characters';
    if(empty($errArr[2]) && !is_email($_POST['email']))
      $errArr[2] = 'This is not a valid email address';

    for($i = 0; $i < count($errArr); $i++)
      if(!empty($errArr[$i]))
        die(registerForm($valArr, $errArr));

    $pass = md5($pass);

    // Actual registration
    mysql_query("insert into $userstable (nick, password, email) values ('$nick', '$pass', '$email');") or die(mysql_error());
    login();
  }

  function userExists($nick) {
    head('Error: User Already Exists');
?>
      <h1>Error: User Already Exists</h1>
      <p>
        The username &quot;<?php echo(htmlentities($nick)); ?>&quot; already exists in our database.  Please check that you have entered your username and password correctly.
      </p>
<?php
    foot();
  }

  function validateUser() {
    global $userstable;

    $id = $_SESSION['userid'];
    $nick = mysql_real_escape_string($_SESSION['nick']);
    $pass = mysql_real_escape_string($_SESSION['pass']);
    $email = mysql_real_escape_string($_SESSION['email']);

    $rs = mysql_query("select * from $userstable where id=$id and nick='$nick' and password='$pass' and email='$email' limit 1;") or die(mysql_error());
    if(!mysql_num_rows($rs))
      die(loginForm());
  }

  if(isset($_GET['logout'])) logout();
  else if(isset($_GET['register']))
    die(registerForm());
  else if(isset($_POST['register']))
    register();
  else if(!isset($_SESSION['nick']) && !isset($_POST['nick']) && !isset($_COOKIE['pass']))
    die(loginForm());
  else if(!isset($_SESSION['nick']) && (isset($_POST['nick']) || isset($_COOKIE['pass'])))
    login();
  else
    validateUser();
?>
__________________
Daniel - <?php?> | <html>| Ich lerne Deutsch. | Studio l'italiano. | Estudiaba español. | Estudo português. | 日本語の勉強。| मैं हिन्दी सीखो | درس العربية
Reply With Quote
  #5  
Old 09-29-2007, 01:09 AM
TimFA TimFA is offline
Regular Coders
 
Join Date: Mar 2007
Location: Tarboro, NC
Posts: 290
Thanks: 8
Thanked 2 Times in 2 Posts
Default

Before I read to is it compatible with my host (ZendURL) I'll send you why I think it might on be in PM.
Reply With Quote
  #6  
Old 09-29-2007, 01:36 AM
djr33's Avatar
djr33 djr33 is offline
Global Moderator
 
Join Date: Mar 2006
Location: N. California, USA
Posts: 6,408
Thanks: 11
Thanked 82 Times in 82 Posts
Default

PHP and MySQL are needed. If so, then yes.
And, yes, limited databases, as detailed in your PM, should not be a problem. Simply specify one to use, and create the table in that.
__________________
Daniel - <?php?> | <html>| Ich lerne Deutsch. | Studio l'italiano. | Estudiaba español. | Estudo português. | 日本語の勉強。| मैं हिन्दी सीखो | درس العربية
Reply With Quote
  #7  
Old 09-29-2007, 02:56 AM
TimFA TimFA is offline
Regular Coders
 
Join Date: Mar 2007
Location: Tarboro, NC
Posts: 290
Thanks: 8
Thanked 2 Times in 2 Posts
Default

PHP and MySQL are supported, now please excuse my ignorance but how do I do this?
Reply With Quote
  #8  
Old 09-29-2007, 03:09 AM
TimFA TimFA is offline
Regular Coders
 
Join Date: Mar 2007
Location: Tarboro, NC
Posts: 290
Thanks: 8
Thanked 2 Times in 2 Posts
Default

Can someone else help me? If someone comes I'll send you a screen shot of the interface I have, please tell me what to do.
Reply With Quote
  #9  
Old 09-29-2007, 03:15 AM
TimFA TimFA is offline
Regular Coders
 
Join Date: Mar 2007
Location: Tarboro, NC
Posts: 290
Thanks: 8
Thanked 2 Times in 2 Posts
Default

I think I may have it. But I can't test due to FTP problems. :{
Reply With Quote
  #10  
Old 09-29-2007, 03:30 AM
djr33's Avatar
djr33 djr33 is offline
Global Moderator
 
Join Date: Mar 2006
Location: N. California, USA
Posts: 6,408
Thanks: 11
Thanked 82 Times in 82 Posts
Default

Have some patience.

Realize that I saw your post in less time than it took you to see mine. 13 minutes is NOT enough to post again.

If the FTP doesn't work, not much we can do to help until we can see what you've got.

In short, create the talbe in the database. Then just add the PHP to your page and you should be able to at least figure out what's going on. Might need a bit of configuring.
__________________
Daniel - <?php?> | <html>| Ich lerne Deutsch. | Studio l'italiano. | Estudiaba español. | Estudo português. | 日本語の勉強。| मैं हिन्दी सीखो | درس العربية
Reply With Quote
Reply

Bookmarks

Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT. The time now is 07:22 PM.

Home - Contact Us - Archives - Link to DD - Top 

Powered by vBulletin® Version 3.8.1
Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.