#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    19
    Rep Power
    0

    Could someone please mentor me on a PHP script?


    Hi,
    I have a basic PHP user login and registration script I created, using code from the forum on this site entitled "How to program a basic but secure login system using PHP and MySQL".

    In any case, I integrated the entire script into my site design, yet I cannot seem to get it to function. Note that I added a couple of more lines to the database that were not originally included. I think the problem lies in the redirect method however.

    I can email my entire script with my SQL setup file to anyone willing to help. Perhaps you could put it into you're development environment and give it a try. You can modify my common.php file in the includes folder to you're own SQL user credentials.

    Any help would be appreciated.
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Jul 2003
    Posts
    3,600
    Rep Power
    595
    Why email it? Post your code here using [ PHP ] tags. See ManiacDan's New User Guide.
    There are 10 kinds of people in the world. Those that understand binary and those that don't.
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    19
    Rep Power
    0
    Oh ok..well I tried it last night with all of the pages but it said I had too many charictars. I suppose I could just start with the index and profile page and troubleshoot from there. Ill give it a shot when I get home.

    I know if someone were to try it on their own server they could really get a feel for it and identify the problems. If anyone would be willing to do that. Not saying build it for me but just like checking someone else's enlish paper.
  6. #4
  7. No Profile Picture
    Contributing User
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Jul 2003
    Posts
    3,600
    Rep Power
    595
    Just post the segment in which you are having trouble. If more is needed we will ask for it.
    There are 10 kinds of people in the world. Those that understand binary and those that don't.
  8. #5
  9. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    19
    Rep Power
    0

    We can start here...


    again, I am having trouble loading the my profile page when I submit in the login form.
    Here is my SQL structure, the common page with all of my SQL credential and the index page. I am trying to get to profile.php .
    users.sql
    Code:
    CREATE TABLE IF NOT EXISTS `users` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `username` varchar(30) NOT NULL,
      `password` char(64) NOT NULL,
      `salt` char(16) NOT NULL,
      `first_name` varchar(30) NOT NULL,
      `last_name` varchar(30) NOT NULL,
      `email` varchar(40) NOT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;
    common.php The credentials for SQL connection
    PHP Code:
    <?php

        
    // These variables define the connection information for your MySQL database
        
    $username "codeman061988";
        
    $password "Ht66LFNtw52hq7Ub";
        
    $host "localhost";
        
    $dbname "users";

        
    // UTF-8 is a character encoding scheme that allows you to conveniently store
        // a wide varienty of special characters, like  or , in your database.
        // By passing the following $options array to the database connection code we
        // are telling the MySQL server that we want to communicate with it using UTF-8
        // See Wikipedia for more information on UTF-8:
        // http://en.wikipedia.org/wiki/UTF-8
        
    $options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
        
        
    // A try/catch statement is a common method of error handling in object oriented code.
        // First, PHP executes the code within the try block.  If at any time it encounters an
        // error while executing that code, it stops immediately and jumps down to the
        // catch block.  For more detailed information on exceptions and try/catch blocks:
        // http://us2.php.net/manual/en/language.exceptions.php
        
    try
        {
            
    // This statement opens a connection to your database using the PDO library
            // PDO is designed to provide a flexible interface between PHP and many
            // different types of database servers.  For more information on PDO:
            // http://us2.php.net/manual/en/class.pdo.php
            
    $db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8"$username$password$options);
        }
        catch(
    PDOException $ex)
        {
            
    // If an error occurs while opening a connection to your database, it will
            // be trapped here.  The script will output an error and stop executing.
            // Note: On a production website, you should not output $ex->getMessage().
            // It may provide an attacker with helpful information about your code
            // (like your database username and password).
            
    die("Failed to connect to the database: " $ex->getMessage());
        }
        
        
    // This statement configures PDO to throw an exception when it encounters
        // an error.  This allows us to use try/catch blocks to trap database errors.
        
    $db->setAttribute(PDO::ATTR_ERRMODEPDO::ERRMODE_EXCEPTION);
        
        
    // This statement configures PDO to return database rows from your database using an associative
        // array.  This means the array will have string indexes, where the string value
        // represents the name of the column in your database.
        
    $db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODEPDO::FETCH_ASSOC);
        
        
    // This block of code is used to undo magic quotes.  Magic quotes are a terrible
        // feature that was removed from PHP as of PHP 5.4.  However, older installations
        // of PHP may still have magic quotes enabled and this code is necessary to
        // prevent them from causing problems.  For more information on magic quotes:
        // http://php.net/manual/en/security.magicquotes.php
        
    if(function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc())
        {
            function 
    undo_magic_quotes_gpc(&$array)
            {
                foreach(
    $array as &$value)
                {
                    if(
    is_array($value))
                    {
                        
    undo_magic_quotes_gpc($value);
                    }
                    else
                    {
                        
    $value stripslashes($value);
                    }
                }
            }
        
            
    undo_magic_quotes_gpc($_POST);
            
    undo_magic_quotes_gpc($_GET);
            
    undo_magic_quotes_gpc($_COOKIE);
        }
        
        
    // This tells the web browser that your content is encoded using UTF-8
        // and that it should submit content back to you using UTF-8
        
    header('Content-Type: text/html; charset=utf-8');
        
        
    // This initializes a session.  Sessions are used to store information about
        // a visitor from one web page visit to the next.  Unlike a cookie, the information is
        // stored on the server-side and cannot be modified by the visitor.  However,
        // note that in most cases sessions do still use cookies and require the visitor
        // to have cookies enabled.  For more information about sessions:
        // http://us.php.net/manual/en/book.session.php
        
    session_start();

        
    // Note that it is a good practice to NOT end your PHP files with a closing PHP tag.
        // This prevents trailing newlines on the file from being included in your output,
        // which can cause problems with redirecting users.
    index.php

    PHP Code:
    <?php

        
    // First we execute our common code to connection to the database and start the session
        
    require("includes/common.php");
        
        
    // This variable will be used to re-display the user's username to them in the
        // login form if they fail to enter the correct password.  It is initialized here
        // to an empty value, which will be shown if the user has not submitted the form.
        
    $submitted_username '';
        
        
    // This if statement checks to determine whether the login form has been submitted
        // If it has, then the login code is run, otherwise the form is displayed
        
    if(!empty($_POST))
        {
            
    // This query retreives the user's information from the database using
            // their username.
            
    $query "
                SELECT
                    id,
                    username,
                    password,
                    salt,
                    email,
                    first_name,
                    last_name
                FROM users
                WHERE
                    username = :username
            "
    ;
            
            
    // The parameter values
            
    $query_params = array(
                
    ':username' => $_POST['username']
            );
            
            try
            {
                
    // Execute the query against the database
                
    $stmt $db->prepare($query);
                
    $result $stmt->execute($query_params);
            }
            catch(
    PDOException $ex)
            {
                
    // Note: On a production website, you should not output $ex->getMessage().
                // It may provide an attacker with helpful information about your code. 
                
    die("Failed to run query: " $ex->getMessage());
            }
            
            
    // This variable tells us whether the user has successfully logged in or not.
            // We initialize it to false, assuming they have not.
            // If we determine that they have entered the right details, then we switch it to true.
            
    $login_ok false;
            
            
    // Retrieve the user data from the database.  If $row is false, then the username
            // they entered is not registered.
            
    $row $stmt->fetch();
            if(
    $row)
            {
                
    // Using the password submitted by the user and the salt stored in the database,
                // we now check to see whether the passwords match by hashing the submitted password
                // and comparing it to the hashed version already stored in the database.
                
    $check_password hash('sha256'$_POST['password'] . $row['salt']);
                for(
    $round 0$round 65536$round++)
                {
                    
    $check_password hash('sha256'$check_password $row['salt']);
                }
                
                if(
    $check_password === $row['password'])
                {
                    
    // If they do, then we flip this to true
                    
    $login_ok true;
                }
            }
            
            
    // If the user logged in successfully, then we send them to the private members-only page
            // Otherwise, we display a login failed message and show the login form again
            
    if($login_ok)
            {
                
    // Here I am preparing to store the $row array into the $_SESSION by
                // removing the salt and password values from it.  Although $_SESSION is
                // stored on the server-side, there is no reason to store sensitive values
                // in it unless you have to.  Thus, it is best practice to remove these
                // sensitive values first.
                
    unset($row['salt']);
                unset(
    $row['password']);
                
                
    // This stores the user's data into the session at the index 'user'.
                // We will check this index on the private members-only page to determine whether
                // or not the user is logged in.  We can also use it to retrieve
                // the user's details.
                
    $_SESSION['user'] = $row;
                
                
    // Redirect the user to the private members-only page.
                
    echo '<script language="javascript">window.location.href="profile.php"</script>';


                die();
            }
            else
            {
                
    // Tell the user they failed
                
    print("Login Failed.");
                
                
    // Show them their username again so all they have to do is enter a new
                // password.  The use of htmlentities prevents XSS attacks.  You should
                // always use htmlentities on user submitted values before displaying them
                // to any users (including the user that submitted them).  For more information:
                // http://en.wikipedia.org/wiki/XSS_attack
                
    $submitted_username htmlentities($_POST['username'], ENT_QUOTES'UTF-8');
            }
        }
        
    ?>
    <?php 
    include 'includes/header.php'?>
        
       <table width="100%" height="470" border="0">
    <tr>
    <td width="50%" height="218" valign="top">&nbsp;</td>
    <td width="50%" valign="middle"><div id="member_login">
    <p>Member Login</p></div>
    <form method="post" action="profile.php">
    <div id="user_input_styles"><p>Username: 
      <input type="text" name="username" value="<?php echo $submitted_username?>" />
    </p>
    <p>Password: 
      <input type="password" name="password" />
    </p>
    <p><input type="submit" value="Login">&nbsp;</p></div>
    </form>
    <p>&nbsp;</p>
    <p>&nbsp;</p>
    <p>&nbsp;</p></td>
    </tr>
    </table>

    <?php include 'includes/footer.php'?>
  10. #6
  11. --
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Jul 2012
    Posts
    3,959
    Rep Power
    1014
    Hi,

    what exactly do you mean by "it doesn't work"? What happens? Do you get an error message? If so, what does it say? If not, turn on your error_reporting and try again.

    Anyway, I wouldn't do the password hashing and checking "by hand". E-Oreo's script is nice to learn from, but for real life, there are ready-made libraries like phpass which do all this stuff automatically and have actually been tested by many people.

    By the way, why are you using this strange JavaScript hack to do the redirect?
  12. #7
  13. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    19
    Rep Power
    0
    Hello,

    Well I didnt have error reporting on but i believe he designed the script to foward the client side to the profile page but it simply does nothing when submitted. I did attempt the javascript fowarding but this was a failure as well.
    Of course, it originally had a header location script to faward to the next page.

    I am using a general header that is included on all of my pages. I put php scripting before my <?php include 'includes/header.php'; ?> on the pages. Should I include the common.php on my header page? They say call the header location in the page head, before anything else is written to the client side.
  14. #8
  15. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    19
    Rep Power
    0
    Originally Posted by codeman061988
    Hello,

    Well I didnt have error reporting on but i believe he designed the script to foward the client side to the profile page but it simply does nothing when submitted. I did attempt the javascript fowarding but this was a failure as well.
    Of course, it originally had a header location script to faward to the next page.

    I am using a general header that is included on all of my pages. I put php scripting before my <php? include 'includes/header.php'; ?> on the pages. Should I include the common.php on my header page? They say call the header location in the page head, before anything else is written to the client side.
    What I want to do is use intergrate a good scructure into my own design so I can work and learn from it.
  16. #9
  17. Confused badger
    Devshed Beginner (1000 - 1499 posts)

    Join Date
    Mar 2009
    Location
    West Yorkshire
    Posts
    1,184
    Rep Power
    492
    In order for a PHP Header() to work, there can't be ANYTHING outputted to the browser before it. E-Orea's script works perfectly so whatever modifications you have made have broken it ...

    There are more than adequate comments in all the files which explain in great detail what they are doing ... common.php just sets up the connection to the database, sets a page header type and "starts" the PHP session.

    Consider this, a user tries to view index.php.
    Index.php calls common.php which creates the database connection, starts the session and tells the browser what content to expect next.
    In index.php, a check is performed to see if the user is logged in (or not). If they are logged in then it will allow you to view the "protected content", if not, you're re-directed to login.php (which if you notice, you've pasted that and called it index.php).

    Presuming you were sent to login.php, the script sees if $_POST data was set (i.e. the user has entered and submitted their username and password) and if they have, attempts to validate it. Note that so far, NOTHING has been sent to the browser for display ... if the validation is a success, you are then re-directed back to index.php where it will again check if you're logged in or not (this time you will be) and then presents the appropriate content.

    Now, I can see in your login.php you have this line:-
    echo '<script language="javascript">window.location.href="profile.php"</script>';
    Get rid of that and replace it with
    PHP Code:
                header("Location: private.php");
                die(
    "Redirecting to: private.php"); 
    Both lines are important and required.
    You can of course, change private.php to any other page of your choice (e.g. profile.php).

    With regards to your inclusion of the two lines:-

    <?php include 'includes/header.php'; ?> and <?php include 'includes/footer.php'; ?>

    Because they appear AFTER the re-direct, it shouldn't interfere with it.
    You asked if you should include common.php in your header.php, well, there's no harm in it but I suggest you use "include_once" or "require_once" so that PHP will only include it if it needs to.

    I hope this helps.
    "For if leisure and security were enjoyed by all alike, the great mass of human beings who are normally stupefied by poverty would become literate and would learn to think for themselves; and when once they had done this, they would sooner or later realise that the privileged minority had no function and they would sweep it away"
    - George Orwell, 1984

IMN logo majestic logo threadwatch logo seochat tools logo