Jul 24, 2008

Help Improving My Login Script Code - The code works okay...just not the authorization part

Free Web Hosting, No Ads > CONTRIBUTE > Computers > Programming Languages > PHP Programming

free web hosting

Help Improving My Login Script Code - The code works okay...just not the authorization part

FirefoxRocks
I have developed a piece of code smile.gif that is going to work as my login script for my website. I need some help making improvements and creating additional features.

Here is my code:
CODE
<?php
session_start();
$name = $_POST['username'];
$password = $_POST['password'];

$con = mysql_connect("localhost","myDbUser","myDbPassword");
    if(!$con)
        {
        die('Sorry, the XKingdom Center database has encountered an error right now. Please try again later or contact the website administrator. The MySQL error is: ' . mysql_error());
        }
mysql_select_db("myDb", $con);

$result = mysql_query("SELECT * FROM myTable WHERE name='$name' and password = '$password'");
$auth = mysql_query("SELECT auth FROM myTable");
$rowcheck = mysql_num_rows($result);
if($rowcheck==1)
    {
    while($auth_check = mysql_fetch_array($auth))
        {
        if($auth_check==YES)
            {
            $_SESSION['db_is_logged_in'] = true;
            setcookie("user", "$name", time()+86400);
            header('Location: moderate.php');
            header('(anti-spam-(anti-spam-content-type:)) text/html;charset=iso-8859-1');
            }
        elseif($auth_check==NO)
            {
            $error="You are not authorized as an XKingdom Member yet. Please try again later. If this problem persists for more than 24 hours, please contact the website administrator.";  
            }
        }
    }
elseif($rowcheck>1)
{
$error="You have entered an incorrect username/password combination. Please try again. If you forgot your password, contact the website administrator.";
        header('(anti-spam-(anti-spam-content-type:)) text/html;charset=iso-8859-1');
}
header('(anti-spam-(anti-spam-content-type:)) text/html;charset=iso-8859-1');
mysql_close();
?>


It doesn't work. Also the $error variable isn't echoing properly in a <p> tag in the body.

This code works:
CODE
<?php
session_start();
$name = $_POST['username'];
$password = $_POST['password'];

$con = mysql_connect("localhost","myDbUser","myDbPassword");
    if(!$con)
        {
        die('Sorry, the XKingdom Center database has encountered an error right now. Please try again later or contact the website administrator. The MySQL error is: ' . mysql_error());
        }
mysql_select_db("myDb", $con);

$result = mysql_query("SELECT * FROM myTable WHERE name='$name' and password = '$password'");
$rowcheck = mysql_num_rows($result);
if($rowcheck==1)
    {
        $_SESSION['db_is_logged_in'] = true;
        setcookie("user", "$name", time()+86400);
        header('Location: moderate.php');
        header('(anti-spam-(anti-spam-content-type:)) text/html;charset=iso-8859-1');
    }
elseif($rowcheck>1)
{
$error="You have entered an incorrect username/password combination. Please try again. If you forgot your password, contact the website administrator.";
        header('(anti-spam-(anti-spam-content-type:)) text/html;charset=iso-8859-1');
}
header('(anti-spam-(anti-spam-content-type:)) text/html;charset=iso-8859-1');
mysql_close();
?>


I have removed the authorization stuff, and the $error variable isn't echoing properly here either.

1st priority: Get the authorized users right to log in, unauthorized users to wait.
2nd priority: Display a message if(...).
3rd priorities:
  • Lost Password
  • IP address logging at logon
  • Ability to enter more information (optional)
Could someone help me achieve my goal please?
Thank you,

 

 

 


Reply

Evil man
thanks for the code...

Notice from truefusion:
Improve your post quality. "Thank you" posts like these are considered spam to our boards.

Reply

saga
First I believe that using the condition
CODE
elseif($rowcheck > 1)
to check if the user entered the wrong user or password is a mistake. Your sql query
CODE
"SELECT * FROM name='$name' AND password='$password'"
returns the number of rows resulted from the query which in most cases will return 1 or less than one unless of course there are multiple entry in your database in which user name is not unique meaning there are name entries with the same name. It should not be the case. User name should be unique and only password can have duplicate but never the user name. The right condtion statement should be, assuming that user name is unique.

CODE
if($rowcheck == 1){
    //user name and password is ok
}
else{
    //wrong password or username
}



About the error report.. use <pre></pre> instead of <p></p> tag. The difference between the two is that the <pre> tag is sensitive to spaces and new lines. What ever space or new line inside the tag will be reflected or displayed. The <p> tag does not allow new line or <br /> since its in pharagraph formating which means there should be no new line inside the tag.
So for pre-formatted text use <pre></pre>.

For logging the IP address I believe there is a global variable that holds it or maybe a function that returns the IP address, I forgot about it. You could visit PHP.net they have good ducmentation in their website.

About the lost password feature. First you must have a record or entry in your Members database about their e-maill address. The common way for this to work is to ask the e-mail address of the user which it supplied when he register to your website. Then you check if the supplied e-mail address match to the user in your database. If it match then use the mail() function to e-mail the new generated password.

By the way about your password. I noticed that you get the one supplied by the user from $_POST[] directly then compared it directly in your query without encryption. This only mean that you havent encrtypted the password. For better security you should encrypt your password and the recommended one is the one way encryption. Here is how it works.

1. During registration you get the desired password then encrypt it using the crypt() function and save the result encrypted data to your database. crypt() function is a one way encrytion. Meaning you can not decrypt anymore what is encrtypted using the crypt() function.

2.To verify password during log-in, first you have to encrypt the supplied password using crypt(). The result encrypted data is the one used to check if it matches the encrypted password save in the database;

CODE
$pass = crypt($_POST['password']);
$query = "SELECT * FROM members WHERE userName LIKE '$name' AND password LIKE '$pass'"

in this way.. even if the database is compromised the password will still not be stolen since it is encrtypted using one way encryption. They may have the encrypted password but there is no way for them to know what are the actual values unless if they are the CIA or NSA.

 

 

 


Reply

jlhaslip
Presumably, you are running the script from a form on a web-site, hence the $_POST variable.
One precaution is to check that the $_POST variable has been provide by checking the query-string by using the ISSET().
CODE
if ( !isset($_POST['variable']) {

// do this stuff here. ie: transfer them back to the form page for completion

}
else {

// continue with the processing
// possibly passing control on errors

}

// pass control to the 'logged-in' page here

The 'variable' used in the initial IF statement checking the isset() is typically a hidden value from the Form itself.

Reply

FirefoxRocks
Now I have a message appearing if the user is not authorized, incorrect username/password, etc.
Also, unauthorized users can now log in. For example, please log into XKingdom Member Center with the username Trap17 and password 123. That user is supposed to be unauthorized, but it can still go through. Why is that?

My revised code is:
CODE
<?php
session_start();
$name = $_POST['username'];
$password = $_POST['password'];

$con = mysql_connect("localhost","myDbUser","myDbPassword");
    if(!$con)
        {
        die('Sorry, the XKingdom Center database has encountered an error right now. Please try again later or contact the website administrator. The MySQL error is: ' . mysql_error());
        }
mysql_select_db("myDb", $con);

$result = mysql_query("SELECT * FROM myTable WHERE name='$name' and password = '$password'");
$rowid = mysql_query("SELECT id FROM myTable WHERE name='$name' and password = '$password'");
$auth = mysql_query("SELECT auth FROM myTable");
$rowcheck = mysql_num_rows($result);
if($rowcheck==1)
    {
    $row=mysql_result($auth,$rowid);
        if($row==YES||yes||Yes)
            {
            $_SESSION['db_is_logged_in'] = true;
            setcookie("user", "$name", time()+86400);
            header('Location: moderate.php');
            header('(anti-spam-content-type:) text/html;charset=iso-8859-1');
            }
        elseif($row==NO||no||No)
            {
            $error="You are not authorized as an XKingdom Member yet. Please try again later.n If this problem persists for more than 24 hours, please contact the website administrator.";  
            }
    }
else
{
$error="You have entered an incorrect username/password combination. Please try again.n If you forgot your password, contact the website administrator.";
        header('(anti-spam-content-type:) text/html;charset=iso-8859-1');
}
header('(anti-spam-content-type:) text/html;charset=iso-8859-1');
mysql_close();
?>


I don't care if the incorrect username/password message appears at first visit. It isn't a priority right now.
As for lost password, I whipped up something that can be used. It does use the mail() function. And users NEED to provide an email address when registering.

Reply



Got an Opinion! Express your Views! (no registration):-
Add your Reply/ Opinion/ Views/ Comments/ Suggestion/ Questions/ Queries etc.
Posts with decent grammar & English will be accepted and please refrain from profanities.
For asking a Question, We recommend you to sign-up (for free) so that you can track the topic easily.

Nature of your Post*: Opinion/ Reply/ Comments
Question/Query
Feedback to us.
       
Name   Email
Title/Question*

(Maximum characters: 10,000)
You have characters left.
Confirm Code:

Similar Topics

Keywords : improving, login, script, code, code, works, authorization, part

  1. Php Guest Online Script
    (0)
  2. How To Make A View New Post Script?
    (5)
    Ok so i'm still working on the forum software i posted about a while back, but I have no idea
    how to do this. I want to make a view new post script, as this is one of the main things that my
    forum software dose not have that all other forums have. so does any body have an idea on how i
    would do this? Thanks.....
  3. Guessing Php Script
    (0)
    I am looking for: freeware php quess the person in the photo game script....
  4. Create Table - Mysql Code - Help
    (1)
    I need your feedback about setting the database issues. Please, review them and correct some entries
    in the code if they got some mistakes. This is the code itself: SQL CREATE TABLE
    `news` ( `id` int(250) NOT NULL auto_increment, `title` varchar(255)
    NOT NULL default '', `text` text NOT NULL, `author` varchar(255) NOT
    NULL default '', `valid` varchar(255) NOT NULL default '',
    `date` varchar(255) NOT NULL default '', PRIMARY KEY (`id`) ) ENGINE = ....
  5. Php Source Code Unveiled In Browser?
    is that possible? (7)
    I am quite new to PHP and this concern came to my mind after playing around a bit with it... When
    PHP is not correctly configured on the web server the source code of a php file we try to access
    through a browser will be shown instead of the result of the code itself. This will normally not
    happen when PHP is working properly, but I was just wondering if it could still be possible to see
    that code if a user wanted to or if something on the server failed. This would for example expose
    sensitive information like mysql passwords and so on... Is anything like that possib....
  6. Malicious Code Injection
    (3)
    Hi everyone! This is my first post, so be kind! Basically, I'm trying to get a free
    host together so am writing some posts. Here's a little summin' summin' about malicious
    code injection with PHP applications. Basically, this security exploit is one of the oldest tricks
    in the books and all comes down to the fact that PHP allows execution of both local and remote
    scripts with the SAME function... dur. Anyway, this is how it works. Image you've just employed
    a young go getter, straight outta uni, who has found becoming a Jack of all trades a ....
  7. Php And Mysql Programming
    anyone knows a code for mysql and php (2)
    hi everyone! I am making a program using php and mysql...I am a noob on this so i need your
    help guys...I want to make a simple program that will some values and then store them on a database
    and then retrieve them...uhmm let me give an example out put of what i need. This is the example
    say..: Enter First Name: Enter Last Name:
    Enter Age: Enter Address: ..those
    are the data needed for input values...my question now is how can I make a database....
  8. Need Help Installing Dolphin Community Script!
    (5)
    I'm not sure if this is the right place to post this but I really need help in installing the
    dolphin community script. I have absolutely no previous experience of scripts or programming. I
    would really appreciate if someone could walk me through it step-by-step, or even do it for me by
    logging into my cpanel. I have tried to install it my self but I'm a little confused. I'm
    sure it won't take very long at all for someone who has done this before.....
  9. How Do I Connect To Live Database With Php Script?
    while being hosted with ComputingHost (6)
    I am not new to programming. I want to create a form to add some values into my tables, the code
    are all working. But I am not sure what is the URL to connect to my site's database. All along,
    I have been testing through MAMP, which provides a local copy of mySQL. Can anyone lend me a hand?
    My site's URL is http://limetouch.com/ ....
  10. Download Script For Mp3 Files
    (0)
    Hello, I'm looking for a download script for sound files (e.g. mp3, avi, wma, and other ones).
    i have found a few download scripts but they would not work for sound files for some reason. also
    this will not be used for allowing downloading of illegal or riped music, what i will be using this
    script for is i'm making a site for my church and the pastor wants to be able to recored the
    services and then have me upload them to the site so that the church members can download them for
    what ever reason. If some one could tell me how to make one or could show me a plac....
  11. Php Code Needed Iii
    (10)
    Hello, everyone. I need your help again! Who might create the PHP code, the picture is
    above this text. Basically, I want when the user fill in all the information in this form, it
    automatically was sent to my email. And, then, the dialog box appears or on the same window, it was
    said that your request has been sent. Moreover, if the user did not fill the entire information,
    the dialog box appears stating that you did not fill some field. Thanks, for help. You always do
    that.....
  12. Php Code?
    Mathematical Applications (12)
    Hello, everyone. The help is needed again. How can I make calculator in PHP language? That will act
    like that a user just type in the fields known values, then click the button, and it's going to
    be solved automatically. In other words, have can I write a formula in PHP, how to plug it inside
    that language. For example, the formula to find a peremeter of square is: P=4a. So, a user
    just can write the known value which is peremeter itself and it will find the side of a square; and
    vice versa. If you can write many things how to do such formulas, such as comp....
  13. Php Code Needed
    Working Together? (5)
    Hello, everyone. I need your help again. This forum is quite good for it. Well, I need create a
    registration form for my web-site using PHP and SQL. The information it should contain: 1) User
    Name 2) First Name 3) Last Name 4) Password 5) e-mail Address 6) Security Image: that images helps
    to protect a random registration, for instance, 56+2=where user have to type an answer in order to
    finish registration. That's all for today. Anymore things, I will post another post over here.
    ....
  14. Php Rediret Script
    (12)
    Ok, what I am trying to do is this. Re-direct a domain name called: avalon.asn.au to
    preschool.stmarksavalon.org.au I have created a script that will re-direct within the a folder.
    However, the avalon.asn.au and stmarksavalon.org.au are PARKED Domains. Any ideas on how to create
    this PHP Redirect Script please?....
  15. Forum Script
    (3)
    Hello, i'm wanting to start making my own forum software but i dont know where to start or what
    i need to know in order to do this. I know i will need php and mysql but what else, and could some
    one point me to a good site were i could learn php and mysql. Thanks ....
  16. Php Code
    Needed?! (15)
    Well, I am a novice in PHP programming, so there is a script which I wanna get: 1. You go the
    web-site 2. On the main screen, there is a some kind of field windows, the one you get used to type
    in, when you go to google, for instance. 3. He or she types her email address and it's going to
    be saved in my SQL database. 4. That's it. Help me if you can.....
  17. How Would I Go About Making A Simple "counting" Script?
    (3)
    I plan on making a script for basic voting between different options, and I'd like to know what
    PHP coding I would require. Basically, each choice will be as simple as this: CODE <form
    method="post" action="process.php"> Best falsetto?<br><br>
    <input type="radio" name="1"> Person A<br> <input
    type="radio" name="2"> Person B<br> <input type="submit"
    value="Submit"> </form> What PHP would be used to basically add 1 value to a....
  18. Library Script
    Where? (6)
    Hello, everyone. Anyone knows where I can get a library script that acts like CMS script software,
    you can add books or delete them. I want to build virtual online library which can be accessible to
    everyone. Or just give me some advices how to make it build. I'm a novice in programming.....
  19. Script Help Required: Undefined Variable
    A fault I cannot spot in PHP (3)
    Hi, when running a PHP script I keep getting the error: QUOTE Notice: Undefined variable: bret
    in c:\program files\easyphp1-8\home\poll.php on line 294 Notice: Undefined
    variable: bret in c:\program files\easyphp1-8\home\poll.php on line 294 (And,
    yes, I get it twice). The code related to the variable is as follows: CODE function
    LogString($string,$type)     {         $t_log = "\n";
            $t_log .=
    $this->globaldata->server_vars['REMOTE_ADDR']."....
  20. Html Code Tester. Online Script
    (15)
    Yes, yes. I have another script that I have written and I am distributing. I am not entirely sure if
    this works. I have not tested it yet, but I will later and post back with a demo and fix it up.
    Current script: CODE <?php //Save this as something like htmltest.php function
    CheckForm() { $html_unsafe=$_POST['code']; //Gives us our user
    input $html_safe=str_replace("<?php"," ",$html_unsafe);
    //Starts security measures $html_safe=str_replace("?>","
    ",$html_sa....
  21. Creatting A Playlist Through Php
    script help needed (5)
    Hi I am trying to make a script so that i can insert songs into a playlist, but i need a script in
    which it opens the playlist file and removes the closing tag at the end, so before i can add more
    entrys. e.g CODE <atx> <entry>Location 5</entry> <entry>Location
    4</entry> <entry>Location 3</entry> <entry>Location
    2</entry> <entry>Location 1</entry> <atx> But to add more entrys
    i would have to get rid of the atx, then use the fputs to place the new entry into the file. ....
  22. What Kind Of Script Do You Need ?
    post here and get free script (15)
    Hi everybody sorry if i posting here , i know I want design free PHP script and i dont know
    webmasters what kind of scripts want i think its better to aks here becuase trap17 is very nice
    webmasters forum So , Plz post here what kind of script with details you need ! sorry may en
    is not very well for example you need "upload center" : write "upload center" with upload center
    options ( like Ajax , Fast , multi lan and ... ) with this post we can give script details and
    webmasters idea /smile.gif" style="vertical-align:middle" emoid=":)" border="0" alt="smile.....
  23. Wappy Buddy V1.10 - Tibia Gold Edition By Wappy & Jon Roig
    the official wap download script (3)
    By downloading this script you are agreeing to the license and terms outlined below /biggrin.gif"
    style="vertical-align:middle" emoid=":D" border="0" alt="biggrin.gif" /> QUOTE /** * *
    @package: wappyBUDDY - Tibia Gold Edition * @version: 1.10 2006/10/01 00:00:01 wappy * @copyright:
    ©2003, 2006 jon roig, wappy * @release notes: this is the first official release of my download
    script despite pirate and incomplete copies floating around that were stolen from one of my previous
    servers. The next release will follow very shortly * @terms: wappyBUDDY is free softw....
  24. Free Auction Script
    Any Suggestions? (6)
    Any free auction script suggested? I want it to be as many practical functions as possible, yet
    easy to manage. And more importantly, it is free! Appreciate your kind suggestions!....
  25. Wap Source Code Viewer
    Mobile/wap source code viewer page (4)
    This is a source code viewer that will workl on wap/mobile sites but you can easily convert it to
    work on web im sure ;-) CODE <? header("Content-Type:
    text/vnd.wap.wml"); echo '<?xml version="1.0"
    encoding="utf-8"?> <!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.1//EN"
    "http://www.wapforum.org/DTD/wml_1.1.xml"> <wml> <head><meta
    http-equiv="Cache-Control" content="no-cache"
    forua="true"/></head> <card title="s60.nerds.....
  26. Watermark Your Image With Simple Php Script
    found it on the net (34)
    This script was found on the net http://tips-scripts.com/?tip=watermark#tip B&T's Tips &
    Scripts site. Just in case the site may not show, I will include the code here: List of things
    needed: 1. your image in any format 2. watermark image--in gif format with transparent background 3.
    script below with name (i.e. watermark.php) CODE <?php // this script creates a watermarked
    image from an image file - can be a .jpg .gif or .png file // where watermark.gif is a mostly
    transparent gif image with the watermark - goes in the same directory as this script // ....
  27. Adapting Html Code Embed To Work On Phpnuke
    Help With This Html Code Pls (7)
    QUOTE how can get this html code to work on my phpnuke site? what tags would i
    have to enable in the $Allowable HTML part of my config.php file?? Edited topic title. Moved
    to Programming. ....
  28. Parse: Error Unexpected T_lnumber
    php parse error when running script (4)
    Hi. I've just created a php script. The main object of the script is to delete some old files
    and replace it with a new file with some new content, effectively moving the contents from one file
    to another. These are the first 50 lines of the file: /* Calculate For The "A" Group - The
    Latest Games ID */ $a_B = 002; while(file_exists("a_" . $a_B . ".dat")) {
    $a_B++; } $new_page_contents = " " . $_POST . " " . $_POST . "
    include \"/home/cmatcme/public_html/footer.php\"; ?> "; $a_stream = fopen(&....
  29. Script: Php Jukebox
    A one file script! (4)
    This scripts is so simple, you dont need to edit ANY of it! All you have to do is make a folder
    called 'songs' and put some audio files in it. Here is the whole page, I named it index.php
    and put it in a folder called 'music': CODE <!DOCTYPE HTML PUBLIC
    "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd"> <html> <head>
    <title>PHP jukebox</title> </head> <body> <!-- ©2005 Craig
    lloyd. All rights reserved. Visit cragllo.com for more sc....
  30. How do you test your php code
    (75)
    We know that php is a server side scripting language. So we will need a server with the php parser
    to parse/test our code. How are you doing that. Do you upload it to a server for testing or did you
    instal php and the server (apache) on your computer (localhost)....

    1. Looking for improving, login, script, code, code, works, authorization, part

Searching Video's for improving, login, script, code, code, works, authorization, part
advertisement



Help Improving My Login Script Code - The code works okay...just not the authorization part



 

 

 

 

ADD REPLY / Got an Opinion! Remove these ADs! RAPID SEARCH! Free Web Hosting [X]
Express your Opinions, Thoughts or Contribute more info. to help others.
Ask your Doubts & Queries to get answers, So that "Together We can help others!"
Register FREE for AD-FREE forum, Create your own topics, Ask Questions, track topics, setup subscriptions & notifications and Get a Free Website w/ Email and FTP.
500MB Space *No Ads*, CPanel, FTP, PHP, MySQL, EMails - 100% FREE