Results 1 to 23 of 23
  1. #1
    Join Date
    Feb 2011
    Location
    Nirvana
    Posts
    1,395

    php to mysql help

    Hey all you geniuses,

    I'm trying to sat up a simple sign in and registration script on a site. I write html but php and mysql are a major challenge to me. I set up a database with fields for username and password. I can create and install a signup form. every time I add the rest of the code (using http://php.about.com/od/finishedphp1...login_code.htm and upload the page it comes up blank, no errors or anything just a plain white page.

    Also wondering,
    I know I have to create another page with a form for registration. will this require another database?

    Thanks
    www.websitemagick.com "Add a little Magick to your Website"
    IwebNews.net

  2. #2
    Join Date
    Apr 2002
    Location
    Philadelphia
    Posts
    2,278
    every time I add the rest of the code (using http://php.about.com/od/finishedphp1...login_code.htm and upload the page it comes up blank, no errors or anything just a plain white page.
    Which code are you attempting to add - and where are you adding the code specifically?

    I know I have to create another page with a form for registration. will this require another database?
    No

  3. #3
    Hi,

    Instead of using the code in the tutorial try this:

    Sorry about lack of indentation, not sure how todo it on WHT, also signup.php will be posted after I've eaten breakfast, but here is the login script.

    I have opted for MySQLi, or MySQL Improved for PHP over the traditional MySQL classes for PHP, it makes stuff a little easier to understand as it cuts a few steps out ;-). Hopefully the stuff below should make sense. You should most probably adapt the script below to use SHA1 / SALT etc... at least to hide the passwords in the database tables.

    login.php - Gets username and password from the post of a form and checks against the DB to see if it exists...
    PHP Code:
    <?php
    //Start sessions so we can track the users status later.
    session_start();

    //Get the variables from the user login form.
    $username $_POST['username'];
    $password $_POST['password'];

    //Check to make sure the user has entered values on the form.
    if (!isset($username) || !isset($password)) {
    echo 
    "Please fill out the entire form before trying to login";
    } else {

    //Connect to the database, select the rows with the given username and password.
    $DB mysqli_connect("localhost","mysql_username","mysql_password","mysql_dbname");
    $SQL="SELECT * FROM USERS WHERE USERNAME='$username' AND PASSWORD='$password'";
    $RESULT mysqli_query($DB$SQL);

    //If there aren't exactly 1 rows then the user either doesn't exist or exists more than once so hence should not be logged in.
    if (mysqli_num_rows($RESULT) != 1) {
    echo 
    "Login Failed";

    //Else the user exists, create a token in the session and then forward the user to the users only page.
    } else {
    $_SESSION['loggedin'] = "true";
    $_SESSION['username'] = $username
    header
    ("location: my_user_portal.php");
    }
    }

    //Close the sessions, this keeps them active on the server, and does not remove the data but clears the connection for this particular script hence saving resource as the server doesn't wait until the session has timed out.
    session_close();
    ?>
    Signup.php, forms and a little "is the user logged in script" coming after breakfast ;-).
    Last edited by SpinUp_Rob; 06-10-2011 at 04:57 AM.

  4. #4
    Hey,

    At the top of the page you get a blank on add in (right at the top, in PHP tags):

    Code:
    ini_set('display_errors', 1);
    This should then give you some sort of useful error message. Paste it here

  5. #5
    Join Date
    Feb 2011
    Location
    Nirvana
    Posts
    1,395
    Thanks for the suggestions, will try to implement them today.
    www.websitemagick.com "Add a little Magick to your Website"
    IwebNews.net

  6. #6
    Join Date
    Apr 2002
    Posts
    446
    //Get the variables from the user login form.
    $username = $_POST['username'];
    $password = $_POST['password'];
    You need to sanitize your variables' data before executing your SQL otherwise you will be prone to SQL injections, etc. Sanitizing is checking the input from the user to be legit(non-harmful) data to be used by your system

    http://www.google.com/search?q=php+s...utf-8&oe=utf-8

  7. #7
    Join Date
    Feb 2011
    Location
    Nirvana
    Posts
    1,395
    Quote Originally Posted by BMurtagh View Post
    You need to sanitize your variables' data before executing your SQL otherwise you will be prone to SQL injections, etc. Sanitizing is checking the input from the user to be legit(non-harmful) data to be used by your system

    http://www.google.com/search?q=php+s...utf-8&oe=utf-8
    Ya kind of lost me here about sanitizing. Right now I'm getting the job done by using the tutorials on youtube. So far everything is working as it should. I was ready to hire some help today but the silly people didn't get back to me and the login has to be functional tonight so I had no choice but to take a crash course in phpmysql. I guess I was meant to learn it.
    www.websitemagick.com "Add a little Magick to your Website"
    IwebNews.net

  8. #8
    Join Date
    Feb 2011
    Location
    Nirvana
    Posts
    1,395
    Been writing it all by hand as every script I found did not work. Now I'm having trouble and need to debug. Can anyone see whats wrong with this?

    Code:
    <?php
    
    $username = $_POST['username'];
    $password = $_POST['password'];
    
    if ($username&&password)
    {
    
    $connect = mysql_connect("localhost", "root", "******") or die ("couldn't connect!");
    mysql_select_db("users") or die ("Couldn't find DB!");
    
    
     
    $query = mysql_query("SELECT * FROM users WHERE username='username'")
    
    $numrows = mysql_num_rows(query);
    
     
    if ($numrows!=0)
    {
     
    
    {
     while ($row + mysql_fetch_assoc($query))
    {
      $dbusername = $row['username'];
      $dbusername = $row['password'];
      }
    
    
      if ($username==$dbusername&&$password==$dbpassword)
    {
       echo "you're in!";
    
    }
      else
    
       echo "incorrect pessword!";
    
    
    else
      die("that user dosen't exist!");
    
    echo $numrows;
    
    }
    
    else
       die("Please enter user name and password!");
    
    
    ?>
    www.websitemagick.com "Add a little Magick to your Website"
    IwebNews.net

  9. #9
    Join Date
    May 2004
    Location
    NYC
    Posts
    793
    Quote Originally Posted by musicman153 View Post
    Been writing it all by hand as every script I found did not work. Now I'm having trouble and need to debug. Can anyone see whats wrong with this?
    Well...there are a few syntax errors, some inefficient code, and a couple of glaring security holes. But I'd also like to point out that if every script you tried didn't work, you might have some problem with your infrastructure, that is, with how PHP and/or Apache are configured.

    Syntax errors:

    • In your sql query, you have single quotes around username and you left off the $. You also haven't sanitized the variable, so your database is open to a sql injection attack. You also left the semicolon off the end of the function call.
    • The conditional term of your while loop doesn't make sense. You are adding the return value to a row variable, instead of doing first an assignment and then a check to see if the value was false.
    • In the body of the while loop, you assign the returned password and also the returned username to the same $dbusername variable. Probably not what you intended.


    As for inefficiencies, you've got some unnecessarily clunky looping, variable setting, and comparisons.

    Lastly, besides the sql injection vulnerability mentioned above, you really shouldn't store passwords in plaintext. Security is complicated -deciding on whether/how/why to salt/hash/encrypt the password is too involved to cover here, but plaintext is a really bad idea.

    Here's your code corrected and streamlined:

    PHP Code:
    $username $_POST['username'];
    $password $_POST['password'];

    // put validation test up front to avoid nesting entire body of code
    if (!$username || !password)
        die(
    "Please enter user name and password!");


    // connect and use correct database
    $connect mysql_connect("localhost""root""******") or die ("couldn't connect!");
    mysql_select_db("users") or die("Couldn't find DB!");

    // retrieve the user's password
    $query mysql_query("SELECT password FROM users WHERE username='" mysql_real_escape_string($password) . "'"
            or die(
    "SQL query failed");

    // You should only get one row; no need for a loop.
    // Whether we get back false or 0, it's still a "fail", so ! is a valid test here
    if (!($row mysql_fetch_assoc($query)))
        die (
    "User not found");
        
    // compare passwords    
    if ($password === $row['password'])
       echo 
    "you're in!";
    else
       echo 
    "incorrect password!"

  10. #10
    Join Date
    Feb 2011
    Location
    Nirvana
    Posts
    1,395
    Thanks Sea Otter for taking the time to do this.

    Much appreciated.
    www.websitemagick.com "Add a little Magick to your Website"
    IwebNews.net

  11. #11
    Join Date
    May 2004
    Location
    NYC
    Posts
    793
    No problem, and good luck

  12. #12
    Sea Otter is right, and it also sounds like you were generating a fatal error, and are using an output buffer or error suppressor.

  13. #13
    Join Date
    Jun 2011
    Location
    UK
    Posts
    28
    Question for Sea Otter really, is deciding to encrypt a password complex, or just use mcrypt_encrypt and mcrypt_decrypt? Or am I being naive?

  14. #14
    Neither. You should either use md5() or password() on a password BEFORE it gets stored into the mysql server. MD5() is recommended, because it can also be evaluated in php, whereas password() is a native MySQL function (not php). Sha1 may also be an option. Also you should be pulling data only if the username AND password match (don't pull the password from the database, because if there's an error, php may EXPOSE the user's data that you pulled, including the password), and if the data is null, that means that the username does not exist, or the password is incorrect.

  15. #15
    Join Date
    May 2004
    Location
    NYC
    Posts
    793
    Quote Originally Posted by alcaeus View Post
    Question for Sea Otter really, is deciding to encrypt a password complex, or just use mcrypt_encrypt and mcrypt_decrypt? Or am I being naive?
    Security is like drugs -the further down the rabbit hole you go, the more paranoid you get.

    In an ideal world, yeah, you'd use mcrrypt() functions along with salting and hashing (and store the hash with the password and verify it every time you pull the password from the database). This also allows you to not only store encrypted passwords, but also provide a password retrieval system.

    HOWEVER...mycrypt and hashing is computationally expensive. An active site with many users would bog down pretty quickly. So then you start to think, maybe I should run a password checking daemon on a separate machine, whose only job is to store and verify passwords? And it only gets better from there. And there are discussions that the Rijndael 256 bit algorithm is actually worse than the 128 bit one for a variety of esoteric reasons. And on and on.

    Also, assuming even the best crypto algorithms, where and how do you store the salt and the key? If they're just sitting there in your PHP file, well, if anyone gains access to that, there goes all your fancy encryption. So do you store them encrypted as well, perhaps in a flat file accessible only to root? And if so, how would you access that from PHP securely. It's all enough to drive you mad.

    So...just the way they say in the hosting forum here that "there is no best hosting, only the best hosting for you," so it goes with cryptography. You need to look at how secure you want to be, what kind of traffic you've got, what kind of hardware, what you're protecting. And none of this addresses anything beyond password storage. You need to protect yourself from session hijacking, stale sessions, session files visible to others on the server (in shared hosting environments) etc.

    And lastly, DO NOT use md5(), as suggested by ionisis. It's easily cracked, and there are already lots of rainbow tables out there as well, meaning all you have to do is look up the hash, not even try and crack it. At the very least, if you *must* encrypt via a hash, use either the hash() or mhash() functions with a strong algorithm and a dual salt.

    Whew. I'm done

  16. #16
    Join Date
    Feb 2011
    Location
    Nirvana
    Posts
    1,395
    SO What would be the most effective way to accomplish the issue? I know you didn't want to get into the long version here but now that the question has been raised.

    Again your expertise is much appreciated.
    www.websitemagick.com "Add a little Magick to your Website"
    IwebNews.net

  17. #17
    Join Date
    May 2004
    Location
    NYC
    Posts
    793
    Sure thing.

    If you don't care about recoverable passwords (I don't, it's only when a paying client insists on them and refuses to budge), a clever mix of hashing and salting via the password itself will work fine for > 90% of the situations, even with md5 involved:

    PHP Code:
    $password "mypassword"
    $salt sha1(md5($password));
    $encrypted md5($password.$salt); 
    Another way to use a salt without having to embed its value in the code is to use a timestamp stored with the user's other data.

    Note that although both sha1 and md5 can be cracked, it would take many many many years to reconstitute a strong password from the above code. Same goes for generating rainbow tables. The key here is educating users and enforcing a strong password policy: must be > 8 chars, and a required mix of upper/lower/digits/symbols.

    If you need to be able to recover the password, then yes, as you said originally, mcrypt/decrypt is the way to go. My preferred values for the hash, IV and encryption are:

    PHP Code:
    $hash_type=MHASH_SHA256;          

    $iv_mode=MCRYPT_MODE_CFB;           

    $cipher=MCRYPT_RIJNDAEL_128

  18. #18

    Exclamation

    Quote Originally Posted by sea otter View Post
    And lastly, DO NOT use md5(), as suggested by ionisis. It's easily cracked, and there are already lots of rainbow tables out there as well, meaning all you have to do is look up the hash, not even try and crack it. At the very least, if you *must* encrypt via a hash, use either the hash() or mhash() functions with a strong algorithm and a dual salt.
    You're completely wrong. You're going to tell him that IM insecure, but then in the same reply you're going to tell him to (a) use ANOTHER hash function and (b) PULL the password OUT of the database to check it? SERIOUSLY??? I don't know why this guy looks up to you, but he's got a false idol!

    @alcaeus
    You can listen to whatever you want. We do this sh*t for a living, and we HACK sites for kicks. Not to mention that we've got our own encryption algorithm . We eat website security for breakfast.

    Listen kid, DON'T EVER pull a password out of a database. Once it's in there, is in there FOREVER, you will NEVER SEE IT AGAIN. You do a ONE WAY ENCRYPTION on it using a function that is available in the SCRIPTING language AND the database (md5, or perhaps sha1), store it in the database, and check it against the user's password as a part of the QUERY, and if the query doesn't make a match, the password is WRONG or the user name doesn't exist. The password stored in the database should NEVER be reversible, in case your database gets hacked. That's why you use a ONE WAY HASH..

    Once the password is in the database, it's fairly safe, as it's more difficult to hack your database than to hack your website itself, so, YES, md5 is FINE. You CAN use something else, but you'd be going into pointless over kill. You should not be as concerned with how hard the passwords are to reverse if they are intercepted or hacked from your DB: you should be ensuring that they DO NOT GET intercepted or hacked from your DB.

    You still have a problem understanding why that's the "proper" way to do things? Go talk to the guys that make the forum that you're using right now (vBulletin), or any other LARGE SCALE product/software/website.

    You want pro security advice? Ask the pros, not some dude that reads a lot of sh*t but has NO industry experience.

    Here's another tip:
    No matter WHAT method you use to "protect" passwords, it's going to be USELESS if you don't take measures to ensure that it's MEANINGLESS if someone intercepts it. If you're not using SSL, then anyone can listen to your website's traffic, and intercept the usernames and passwords being sent to it. It's easier than your think. We don't use SSL, because we use a 2-stage login, which ensures that the same end result is achieved: if the password is intercepted, it is out of context and meaningless (because we RENDER it that way as a part of our process).

    Never substitute amateur advice for industry experience.
    Last edited by ionisis; 06-13-2011 at 08:06 PM.

  19. #19
    @admins:
    DELETE my above reply

    Quote Originally Posted by sea otter View Post
    And lastly, DO NOT use md5(), as suggested by ionisis. It's easily cracked, and there are already lots of rainbow tables out there as well, meaning all you have to do is look up the hash, not even try and crack it. At the very least, if you *must* encrypt via a hash, use either the hash() or mhash() functions with a strong algorithm and a dual salt.
    You're completely wrong. You're going to tell him that IM insecure, but then in the same reply you're going to tell him to (a) use ANOTHER hash function and (b) PULL the password OUT of the database to check it? SERIOUSLY???

    @alcaeus
    You can listen to whatever you want. We do this sh*t for a living, and we HACK sites for kicks. Not to mention that we've got our own encryption algorithm (it will be available as a SaaS service).

    Listen kid, DON'T EVER pull a password out of a database. Once it's in there, is in there FOREVER, you will NEVER SEE IT AGAIN. You do a ONE WAY ENCRYPTION on it using a function that is available in the SCRIPTING language AND the database (md5, or perhaps sha1), store it in the database, and check it against the user's password as a part of the QUERY, and if the query doesn't make a match, the password is WRONG or the user name doesn't exist. The password stored in the database should NEVER be reversible, in case your database gets hacked. That's why you use a ONE WAY HASH..

    You still have a problem understanding why that's the "proper" way to do things? Go talk to the guys that make the forum that you're using right now (vBulletin), or any other LARGE SCALE product/software/website.


    Here's another tip:
    No matter WHAT method you use to "protect" passwords, it's going to be USELESS if you don't take measures to ensure that it's MEANINGLESS if someone intercepts it. If you're not using SSL, then anyone can listen to your website's traffic, and intercept the usernames and passwords being sent to it. It's easier than your think.

    We don't use SSL, because we use a 2-stage login, which ensures that the same end result is achieved: if the password is intercepted, it is out of context and meaningless (because we RENDER it useless in the 1st stage of our process). You can edit the hash, in predetermined way, to make sure that it doesn't match up against a rainbow table, by including some predetermined, and pseudorandom, value in with the password hash, like, the user's browser. No rainbow table will ever match that hash, and it didn't take your processor 20000000 cycles to execute it, and it's a ONE WAY hash, so it can't be reversed.

    Once the password is in the database, it's fairly safe, as it's more difficult to hack your database than to hack your website itself, or to listen to your traffic; so, YES, md5 is FINE. You CAN use something else, but you'd be going into pointless over kill. You should not be as concerned with how hard the passwords are to reverse if they are intercepted or hacked from your DB: you should be ensuring that they DO NOT GET intercepted or hacked from your DB. And if you're throwing another element into the hash, they will NOT be reversible anyway.
    Last edited by ionisis; 06-13-2011 at 08:21 PM.

  20. #20
    Join Date
    Feb 2011
    Location
    Nirvana
    Posts
    1,395
    WhooH,

    Nothing to get upset about about, I'm just trying to learn a few things here.

    Thanks
    www.websitemagick.com "Add a little Magick to your Website"
    IwebNews.net

  21. #21
    Well, it's probable to fix this issue. I'm not a programmer myself and I prefer to use ready to use scripts like web forms, contact forms and other scripts which use database.

  22. #22
    I am using php coding in my website but it gives some function error at the server. why?

  23. #23
    Join Date
    Feb 2011
    Location
    Nirvana
    Posts
    1,395
    What error does it give?

    Thanks Johnny, I had tried a number of ready scripts and none worked. I'll take a look at the link you gave.
    www.websitemagick.com "Add a little Magick to your Website"
    IwebNews.net

Similar Threads

  1. Installer for php/mysql open source CMS and php/mysql coder needed
    By 0utlier in forum Employment / Job Offers
    Replies: 4
    Last Post: 03-11-2008, 03:24 PM
  2. Need help setting up PHP/MySQL & Compiling PHP w/MySQL
    By pixeldawn in forum Employment / Job Offers
    Replies: 3
    Last Post: 01-13-2007, 05:37 PM
  3. PHP/MySQL or Perl/MySQL Web Developer
    By asmar in forum Employment / Job Offers
    Replies: 1
    Last Post: 10-25-2005, 05:50 AM
  4. PHP/mySQL expert required for one off mysql troubleshooting project
    By singtel22 in forum Employment / Job Offers
    Replies: 0
    Last Post: 02-13-2005, 01:30 PM
  5. Lightning FAST MySQL and PHP Hosting - Dedicated 64 Bit MySQL Servers!
    By jphilipson in forum Shared Hosting Offers
    Replies: 0
    Last Post: 01-18-2005, 05:57 AM

Posting Permissions

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