Simple PHP-login script using session and MySQL

11th of March, 2007 (Last modified: 13th of May, 2007) Håvard php ,

I came across a short tutorial on how to make a session based login script, using PHP and MySQL. However, I felt that the tutorial did have several shortcomings in terms of its code, and so I felt like writing a short post on how I would go about doing the same thing, elaborating the things I would do differently.

This post has been updated since it first was posted
You can download all the files from this tutorial by visiting http://hvassing.com/wp-content/uploads/simple-login/

PHP can do several nifty things, one of them is talking to a MySQL database server, another is using sessions. Session are useful when we want to keep track of users as they roam through a site. Using session, we can make sure that only those who have a valid username and password can gain access to a specific part of a site, or in the case of any online store; keep track of what is in the shopping chart at any given time.

Session support in PHP consists of a way to preserve certain data across subsequent accesses. This enables you to build more customized applications and increase the appeal of your web site.

A visitor accessing your web site is assigned a unique id, the so-called session id. This is either stored in a cookie on the user side or is propagated in the URL.1

A session can not be written to after there has been any form of output on screen. This means that all session-related code should be above all HTML-code, or any code that'll produce any output. Any error messages from any other script before the session is set, will result in the session not being set.

We'll create six files, which will do all the hard work for us

  • db.php
  • functions.php
  • manage-check.php
  • index.php
  • logout.php
  • members-only.php

The MySQL-table

CREATE TABLE IF NOT EXISTS `members` (
`ID` mediumint(5) UNSIGNED NOT NULL AUTO_INCREMENT,
`username` varchar(100) NOT NULL DEFAULT "",
`user_password` char(40) NOT NULL DEFAULT "",
PRIMARY KEY (`ID`, `username`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

Using mediumint(5) UNSIGNED we allow up to 16 777 215 entries, which is probably way too much. As a rule of thumb; it is always wise to use the smallest applicable type (tinyint rather than int if the value would never go beyond 255 unsigned).

Name Information
BIT[(M)] M indicates the number of bits per value, from 1 to 64. The default is 1 if M is omitted. Before 5.0.3, BIT is a synonym for TINYINT(1).
TINYINT The signed range is -128 to 127. The unsigned range is 0 to 255.
SMALLINT The signed range is -32 768 to 32 767. The unsigned range is 0 to 65 535.
MEDIUMINT The signed range is -8 388 608 to 8 388 607. The unsigned range is 0 to 16 777 215.
INT / INTEGER The signed range is -2 147 483 648 to 2 147 483 647. The unsigned range is 0 to 4 294 967 295.
BIGINT The signed range is -9223372036854775808 to 9223372036854775807. The unsigned range is 0 to 18446744073709551615.

The table above can be found in its entirety at MySQL Developer Zone. Chose the type that is works best for your application, remember that scaling is usually not a problem, and when it is; you'll have the resources to deal with it.

You don't have a scaling problem yet
"Will my app scale when millions of people start using it?"

Ya know what? Wait until that actually happens. If you've got a huge number of people overloading your system then huzzah! That's one swell problem to have.2

Moving along; we'll use Sha1 to encrypt the password, we know that it'll be exactly 40 characters long, which means that char will be the best choice. varchar uses less space when the data has a variable length , as is the case with the username, but char is faster and there's no space to save in this case due to the constant length of the password hash. Using Sha1, we get that "Apples and diamonds" becomes a 40 character long string: "45d4e61ff429b6b61a52204a89d304f625e303d4".

The ID and the username are the two columns that we'll access most frequently, so it's a good idea to make indexes of the two of them.

We'll call the password field "user_password" instead of "password", which is a field type and thus is easily confused.

The HTML-form

index.php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Member Login</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
</head>
<body>
<form name="login-form" id="login-form" method="post" action="manage-check.php">
<fieldset>
<legend>Member Login</legend>
<dl>
<dt><label title="Username">Username: <input tabindex="1" accesskey="u" name="username" type="text" maxlength="100" id="username" /></label></dt>
</dl>
<dl>
<dt><label title="Password">Password: <input tabindex="2" accesskey="p" name="password" type="password" maxlength="14" id="password" /></label></dt>
</dl>
<dl>
<dt><label title="Submit"><input tabindex="3" accesskey="l" type="submit" name="submit" value="Login" /></label></dt>
</dl>
</fieldset>
</form>
</body>
</html>

That should do the trick.

The actual login

manage-check.php
< ?php
session_start();
include('db.php');
if(isset($_POST['submit'])) :
// Username and password sent from signup form
// First we remove all HTML-tags and PHP-tags, then we create a sha1-hash
$username = strip_tags($_POST['username']);
$password = sha1(strip_tags($_POST['password']));
// Make the query a wee-bit safer
$query = sprintf("SELECT ID FROM members WHERE username = '%s' AND user_password = '%s' LIMIT 1;", mysql_real_escape_string($username), mysql_real_escape_string($password));
$result = mysql_query($query);
if(1 != mysql_num_rows($result)) :
// MySQL returned zero rows (or there's something wrong with the query)
header('Location: index.php?msg=login_failed');
else :
// We found the row that we were looking for
$row = mysql_fetch_assoc($result);
// Register the user ID for further use
$_SESSION['member_ID'] = $row['ID'];
header('Location: members-only.php');
endif;
endif;
?>

The rest...

db.php
Before we can do any calls to your database and retrieve any information from our tables, we'll need to connect to the database. This is best done in a separate script, with the database username and password defined as constants, which will make sure that they are not easily hijacked and that they won't be echoed on screen in the unlikely event of the database connection failing. This is what the aforementioned db.php should look like.

< ?php
define('SQL_USER', 'username');
define('SQL_PASS', 'password');
define('SQL_DB', 'database');
// Create a link to the database server
$link = mysql_connect('localhost', SQL_USER, SQL_PASS);
if(!$link) :
die('Could not connect: ' . mysql_error());
endif;
// Select a database where our member tables are stored
$db = mysql_select_db(SQL_DB, $link);
if(!$db) :
die ('Can\'t connect to database : ' . mysql_error());
endif;
?>

For each document that's a part of your secure site, we'll need to check whether or not the user is logged in. This little snippet will ensure that users who are not logged in, won't get to see this particular page. That in mind; do not put this in top of your login page.

< ?php
session_start();
if(!session_is_registered('member_ID')) :
header('Location: index.php');
endif;
?>

members-only.php
This is the page which only members get to see


< ?php
// Start a session
session_start();
// Sends the user to the login-page if not logged in
if(!session_is_registered('member_ID')) :
header('Location: index.php?msg=requires_login');
endif;
// Include database information and connectivity
include 'db.php';
// We store all our functions in one file
include 'functions.php';
?>
< !DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


Members Only


Welcome < ?php print user_info('username'); ?>

Log out



logout.php
Making sure that our users can securely log out when they are done, we need to invoke session_unregister().

< ?php
session_start();
if(true === session_unregister('member_ID')) :
header('Location: index.php?msg=logout_complete');
else :
unset($_SESSION['member_ID']);
sleep(3);
header('Location: index.php?msg=logout_complete');
endif;
?>

functions.php
functions.php will only serve as a place to store functions, which, after a short while with developing, tend to grow quite big.


< ?php
function user_info($field='') {
// If $field is empty
if(empty($field))
return false;
// Check to see if we're allowed to query the requested field.
// If we add other fields, such as name, e-mail etc, this array
// will have to be extended to include those fields.
$accepted = array('username', 'user_password');
if(!in_array($field, $accepted))
return false;
// Poll the database
$result = mysql_query("SELECT ". $field ." FROM members WHERE ID = ". $_SESSION['member_ID'] .";");
// If we don't find any rows
if(1 != mysql_num_rows($result)) :
return false;
else :
// We found the row that we were looking for
$row = mysql_fetch_assoc($result);
// Return the field
return $row[$field];
endif;
} // end user_info
?>

That's about it! Of course, this could be taken even further, using tables to keep track of all session ID's to safeguard against session hijacking and so on, so forth.

Let me know if you find any mistakes or don't get it to work.


1Achour, Mehdi et al. "Session Handling Functions." PHP Manual. 28 Feb 2007. PHP, 11 Mar 2007 <http://php.net/manual/en/ref.session.php>.

237 Signals. "Scale later." Getting Real. 25 Oct 2006. 37 Signals, 11 Mar 2007 <http://gettingreal.37signals.com/ch04_Scale_Later.php>.


85 Responses to “Simple PHP-login script using session and MySQL”

  1. Hey cool tutorial :)

    Why would you use “$_SESSION['member_ID'] = $row['ID'];” is that because its another step past the user name password?

    1
  2. The reason behind storing the member ID as opposed to the username, is that it is more convenient to use the ID when dealing with databases and multiple tables. The idea is that you should have one common identifier in all member-related tables, preferably an integer as they are faster to retrieve and use less space.

    E.g. Your members can write non-anonymous comments, and thus you want to store the ID of the author. Since you’re storing the member ID in the session header, you can simply write INSERT INTO comments VALUES('', $_SESSION['member_ID'], $_POST['comment']);.

    Whereas if you only store the username as a session variable, you’ll have to fetch the member ID first, which adds an additional query to your database.

    When it comes to SELECT-statements, it’s a little bit different, as you can do various kinds of JOIN-statements.

    2
  3. Hey!
    I’m just a beginner in php, but it seems that your script sending plain text password via post method and then is encrypted in php script. In my opinion it should be encrypted before sending using js for example.
    Revise me if something is wrong.
    Anyway great tutorial.

    3
  4. You could of course do that, but JavaScript doesn’t really offer any protection other than when the password is submitted.

    However, using JavaScript has one huge disadvantage (other than being client-side), which is that it won’t work if the client browser doesn’t allow/support JavaScript. If you use JavaScript to encrypt the password before it is sent, you’re running the risk that it won’t be encrypted correctly and thus the user won’t be allowed to log in — which kind of defeats the purpose of the script.

    Personally I would use SSL instead of any JavaScript solutions for log-in purposes.

    4
  5. Code is still sensitive for SQL-injection. Use mysql_real_escape_string.

    5
  6. how do you echo user name when logged in?

    6
  7. There are several ways to do that. The clue here, is that since we have stored the unique user ID as a session we can query the database using that ID.

    One way to do it, which is very flexible and can be used for a whole variety of uses, is creating a function that does all the work for you, and then whenever you need some information from the table, you just call the function.
    [php]
    function user_info($field=”) {
    // If $field is empty
    if(empty($field))
    return false;

    // Check to see if we’re allowed to query the requested field.
    // If we add other fields, such as name, e-mail etc, this array
    // will have to be extended to include those fields.
    $accepted = array(’username’, ‘user_password’);
    if(!in_array($field, $accepted)) {
    return false;

    // Poll the database
    $result = mysql_query(”SELECT “. $field .” FROM members WHERE ID = “. $_SESSION['member_ID'] .”;”);
    if(!$result) :
    return false;
    else :
    return $row[$field];
    endif;

    } // end user_info

    // To print the user name
    print user_info(’username’);

    [/php]

    One possible way to do it…

    7
  8. im not that great with php, where would i put the above? do i put it in manage_check.php, then put print user_info(’username’); on any page? all i get is

    Fatal error: Call to undefined function: user_info() in /home/cunt/public_html/includes/header.php on line 55

    8
  9. I’ve updated all the code and done some testing, it shouldn’t give you any error messages now. My apologies for not testing the code thoroughly enough.

    Thanks for all the feedback

    9
  10. Hi,

    I am getting an error with the script in manage-check.php

    ——————————————————-
    Warning: Cannot modify header information - headers already sent by (output started at /home/mydomain/public_html/admin/db.php:16) in /home/mydomain/public_html/admin/manage-check.php on line 14
    ——————————————————–

    How do I get past this?
    Can you please confirm?

    Thanks a lot!

    10
  11. That usually means that there has been sent text to the screen before the session_start() sentence or the $_SESSION['member_ID'] = $row['ID'].
    You can’t have any kind of output before any session-statements. :)

    In your case, it would seem as if the script can’t connect to the database.

    11
  12. so when i execute this script. i login and it just returns the login_failed url and stays at index.php

    i add’ed my username and password through php my admin. maybe this has somthing to do with it??

    i wish i could give more info but this is all that is happening lol!

    12
  13. Remember that the scripts assumes that your password is encrypted using sha1.
    So for testing purposes only, set your password to 5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8 and then try to log in using “password” as your actual password.


    < ?php
    print sha1('password');
    // Will give 5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8
    ?>

    13
  14. GREAT!

    everything is working now. but i just had one question

    how do you block members-only.php, from people who are not logged in, from seeing it? if i go to members-only.php right now and i’m not logged in it displays Welcome with these errors

    Notice: Undefined index: member_ID in /Library/WebServer/Documents/InvisibleDesign/test/functions.php on line 13

    Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in /Library/WebServer/Documents/InvisibleDesign/test/functions.php on line 15

    obviously becuase i’m not logged in right

    14
  15. For each document that’s a part of your secure site, we’ll need to check whether or not the user is logged in. This little snippet will ensure that users who are not logged in, won’t get to see this particular page. That in mind; do not put this in top of your login page.

    For some odd reason, this snippet of code isn’t included in the members-only.php-page. I’ll fix that straight away!

    < ?php
    session_start();
    if(!session_is_registered('member_ID')) :
    header('Location: index.php');
    endif;
    ?>

    15
  16. Hi I’m still very new at PHP and mySQL and I can’t get this to work… When I login I get stuck at the manage-check.php site, I assume it is supposed to redirect to the members-only.php site?
    I don’t get any errors, I just get stuck on an empty page.

    16
  17. Thanks, just what I was looking for .

    17
  18. i added all pages and inserted an username and password manually in members table. but while i put username and password in index.php following error is comming
    ————————————– error ——————————————-

    Warning: Cannot modify header information - headers already sent by (output started at /home/infozone/public_html/iipm/new/db.php:17) in /home/infozone/public_html/iipm/new/manage-check.php on line 14

    —————————————- end ——————————————

    Could u tell me why it is coming? m not very good in php. please help me

    18
  19. rahul
    Cannot modify header information - headers already sent by means that something printed text or generated some kind of output to the browser before the session was started, thus making it impossible to modify the header information.

    Try checking for blank spaces and that alike. Have you remembered to encrypt your password in the table using sha1?

    19
  20. Thanx for this. I found some blank spaces in my db.php file and i removed all. But after it an another error is coming

    ————————————————- Error ———————————-

    Parse error: syntax error, unexpected ‘

    20
  21. I encrypt my password from sha1 like this

    ————————————————- PHP Code ——————————

    MD5 Function

    “>

    “;
    echo $result;
    }
    ?>

    21
  22. u didnt give answer of my question. i removed blank spaces from my db.php file but after it a new error is coming

    error
    ——-

    “Parse error: syntax error, unexpected ‘

    22
  23. new error
    ———-
    Parse error: syntax error, unexpected ‘

    23
  24. Rahul
    Make sure you’re using ' and not some other type of hyphen or something, like ’.

    By the way; sha1 is not the same as md5.

    24
  25. thanx for answering, but still i am facing that problem. i have uploaded following functions.php file on my server.

    ———————– functions.php ————————–
    :
    return false;
    else :
    // We found the row that we were looking for
    $row = mysql_fetch_assoc($result);
    // Return the field
    return $row[$field];
    endif;
    } // end user_info
    ?>

    ————————————– End ——————————————-

    While i put username and password in index.php page and click on login then same error is coming. You have posted answer but i didnt get yr point. i have to implement it some where soon. what should i do for this error please help me.

    ————————————- Error —————————————-

    Parse error: syntax error, unexpected ‘

    25
  26. thanx for answering, but still i am facing that problem. i have uploaded following functions.php file on my server.

    ———————– functions.php ————————–


    :
    return false;
    else :
    // We found the row that we were looking for
    $row = mysql_fetch_assoc($result);
    // Return the field
    return $row[$field];
    endif;
    } // end user_info
    ?>

    ————————————– End ——————————————-

    While i put username and password in index.php page and click on login then same error is coming. You have posted answer but i didnt get yr point. i have to implement it some where soon. what should i do for this error please help me.

    ————————————- Error —————————————-


    Parse error: syntax error, unexpected '

    26
  27. Thanks so much! This worked for me, but I notice there is a problem with the functions.php code line 15 where a smiley img HTML tag has found it’s way into the php! Took it out, and having eliminated a few bugs of my own introduction, worked fine. Great tutorial!

    27
  28. You can use this mysql code. Otherwise you will get an error at manage-check.php on line 14.

    CREATE TABLE `members` (
    `ID` mediumint(5) unsigned NOT NULL auto_increment,
    `username` varchar(100) NOT NULL default ”,
    `user_password` char(40) NOT NULL default ”,
    PRIMARY KEY (`ID`,`username`)
    ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;

    INSERT INTO `members` (`ID`, `username`, `user_password`) VALUES
    (1, ‘admin’, ‘a94a8fe5ccb19ba61c4c0873d391e987982fbbd3′);

    After adding the user admin:test (sql code above) i get the following error:

    Warning: Cannot modify header information - headers already sent by (output started at /var/www/site.stx.nl/db.php:15) in /var/www/site.stx.nl/manage-check.php on line 20

    28
  29. Edit, found a space ” ” after ?> at db.php :-). You’ve got some more errors. I am trying to update the code. I will send it you when i am ready.

    29
  30. Whereabouts in the PHP coding does it show which table in your database it’s trying to access?

    I stuck with an error which reads:

    Warning: Cannot modify header information - headers already sent by (output started at xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/db.php:17) in /xxxxxxxxxxxxxxxxxxxxxxxxxxxxx/manage-check.php on line 20

    Your help is appreciated - Cause I’ve only been doing PHP for a few days.

    30
  31. Becky
    Please read the comment I wrote to Rahul about this very issue.

    31
  32. Hi Havard,

    I’ve got the same issue I’m afriad.. and yes I have used the 5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8 example for (password) which you stated above.

    As soon as I put anything (either right or wrong login) into the form, it will give the message

    Warning: Cannot modify header information - headers already sent by (output started at /customers/fleetv.co.uk/fleetv.co.uk/httpd.www/filmquotes/db.php:17) in /customers/fleetv.co.uk/fleetv.co.uk/httpd.www/filmquotes/manage-check.php on line 14

    Seems this is quite a common problem, there any quick fix?

    Thanks

    32
  33. Lee
    I’ve uploaded all the files used in this tutorial for you to copy. This will probably help you.
    http://hvassing.com/wp-content/uploads/simple-login/

    33
  34. Cheers Havard… that works well. I configured it for my code.. so it obviously means I put it in the wrong place. I’ll play around and see if I can sort it out.

    Thanks!

    34
  35. Just gone through it.. sorted it out.. couple of errors that happened.. but I just repaste the code and uploaded and it worked fine.

    Cheers Havard.. you’re a lifesaver!

    35
  36. Hey hey! I’ve only just skimmed the post quickly but was just wondering what happens if a user doesn’t play nice and logout? In other words the user just closes the web browser without clicking on the logout button or link.

    From my quick understanding, session_unregister is called to get rid of the logged in status of a user, which is called in logout.php. But now what if that isn’t called? Presumably the variable still exists the next time round? Or does php handle sessions timing out by itself and so I don’t need to care or worry about people logging in, not logging out and thus allowing other people to get in without logging in.

    If you know what I mean

    36
  37. Mike
    Good question! A session is just a short lived cookie, and normally has the same lifetime as the browser. So, when you close the browser, the session cease to be.

    If you have a look at the PHP Manual and Session Handling Functions, you’ll see the following:

    session.cache_expire integer
    session.cache_expire specifies time-to-live for cached session pages in minutes, this has no effect for nocache limiter. Defaults to 180. See also session_cache_expire().

    And…

    session.cookie_lifetime integer
    session.cookie_lifetime specifies the lifetime of the cookie in seconds which is sent to the browser. The value 0 means “until the browser is closed.” Defaults to 0.

    Hope that answers your question :)

    37
  38. Thanks, that does help answer the question :)

    38
  39. For some reason, when I use this line at the beginning of manage-check.php (not counting session_start() ):
    include(’db.php’);
    header() will no longer redirect the page, either on correct or incorrect login. Simply including the login information in the manage-check.php page itself fixes things, but do I want to do this really? I don’t see why include(’db.php’) should make header() fail, it doesn’t output anything (my version, db_login.php doesn’t even check for errors in the db_login script, all it contains is those variables needed to access the DB)

    Any ideas? if not, is it safe to include login details in manage-check.php?

    39
  40. how would i print the user id like welcome “username
    id # “id’

    ? i tried many differnt ways cant get it to work?

    40
  41. strik009
    One way to do that would be:

    [php]printf (”Welcome %s (ID: %s)”, user_info(’username’), $_SESSION['member_ID']);[/php]

    BTW; I removed your URI…

    41
  42. Thank you for your great tutorial. I do have a question though:

    I get a blank page - with the “manage-check.php” url. it does not direct to the page that I want it to. What am i doing wrong?

    Any suggestions anyone?

    Thank you.

    42
  43. I am very new on PHP, where do I create the table:
    CREATE TABLE IF NOT EXISTS `members` (
    `ID` mediumint(5) UNSIGNED NOT NULL AUTO_INCREMENT,
    `username` varchar(100) NOT NULL DEFAULT “”,
    `user_password` char(40) NOT NULL DEFAULT “”,
    PRIMARY KEY (`ID`, `username`)
    ) ENGINE=MyISAM DEFAULT CHARSET=latin1;

    how should I name the file… Thanks so much for your tutorial and any help.

    43
  44. Thanks! A great tutorial.

    But how do I set the default password and username?

    44
  45. Sv
    I’m not quite sure if I understand what you mean by default password and username. If you’re talking about how you would go about creating the first user, you would have to do something along the lines of:
    INSERT INTO `members` VALUES (”, ‘admin’, ‘5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8′);

    Where “admin” is the username and “5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8” is the Sha1-hash of “password“.

    45
  46. Question, do you happen to have a few pages of adding users to the table?

    46
  47. James Buxton

    is there a way with in the login to save cookie? So user dont have to log in every time??

    Thank you

    47
  48. I am getting this error when attempting to login. I think I may have a configuration problem but not sure where to look. Any help is appreciated.

    Warning: mysql_connect() [function.mysql-connect]: Access denied for user ‘admin’@'localhost’ (using password: YES) in /php/db.php on line 7
    Could not connect: Access denied for user ‘admin’@'localhost’ (using password: YES)

    48
  49. NJ
    You’re probably just using the wrong password, or you haven’t set a password for your MySQL-account.

    49
  50. James Buxton
    Sure there is, however, this will require some additional security. One way to go about it is to simply do something like
    HTML:

    <input type="checkbox" name="remember_me" id="remember_me" />

    In the original code, add the following (the first three lines are from the original code)

    [php]
    // Register the user ID for further use
    $_SESSION['member_ID'] = $row['ID'];
    header(’Location: members-only.php’);
    // The additional bit
    if(isset($_POST['remember'])) :
    if(’remember_me’ == $_POST['remember']):
    setcookie(’auto_login’, $_SESSION['member_ID'], (time()+(3600*24*30)));
    endif;
    endif;

    This will store the user ID for 30 days.

    Then, before you load the login-page you’ll have to add something to bypass the whole login page


    [php]
    if(!isset($_COOKIE['auto_login'])) :
    $_SESSION['member_ID'] = $_COOKIE['auto_login'];
    header(’Location: members-only.php’);
    endif;

    Please note that I haven’t tested this code, and there’s probably a better way of doing this.

    50
  51. Hi,

    Please could you help me with this… i am gettin this error even though i have copied exactly the same code from this page. I hav just changed the table name according to my database.

    Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in mydomain\manage-check.php on line 12

    Warning: Cannot modify header information - headers already sent by (output started at mydomain\manage-check.php:12) in mydomain\manage-check.php on line 14

    51
  52. HI dude,
    Cool tutorial, this is my first php and mySql program, got it working in the first GO…
    I tried several other tutorials and finally reached yours..
    thanks again..

    Should have added somebit of mySql for newbies like me… would have helped. however this is gr8, continue works like this.

    All the best.

    For Newbies like me.
    Jus stumble upon the below link b4 reading this… would help a lot.

    http://msconline.maconstate.edu/Tutorials/PHP/

    :D

    52
  53. Is there a way to show the content of a row (in my database I added some fields) in the members-only.php?
    For example, I want that the “logged user” can read his data, I tried:
    “;
    echo “matricula: “.$records[1].”";
    echo “name: “.$records[7].”";
    echo “surname: “.$records[8].”";
    echo “email: “.$records[10].”";
    echo “”;
    }
    ?>

    but this code does not work!

    TNX

    53
  54. Maybe my code was trunked, here the complete code:

    “;
    echo “matricula: “.$records[1].”";
    echo “name: “.$records[7].”";
    echo “surname: “.$records[8].”";
    echo “email: “.$records[10].”";
    echo “”;
    }
    ?>

    54
  55. Hi,

    Thnx for the tutorial.

    James Buxton, I tried your additional script to remember the visitor, but it didn’t work.

    I put
    [php]

    in manage-check.php and

    [php]

    in index.php. When I login I receive errors like unexpected $end and when I press refresh it seems to be looping and I get a 404 page.

    As you haven’t tested the code yourself, could you please give me some pointers how I can get it to work?

    55
  56. Security Problem
    ——————

    In a note pad i run this code. then i managed to login my website without using login page with pre-set ID number. of course i knew the user ID in advance but anyone could guess the userID.

    [php]
    session_start();

    session_register(”member_ID”);

    $member_ID = “342″;

    ?>

    How to solve this.? please help.

    56
  57. Rowd Robbins

    I havent implemented your code yet but it looks clean and I want to use it. I do have a question though. I need multipal layers of access in my site. For example one login for everyone who enters and within the site different layers of access so new password areas. How do I manage this when I want specific users to only have access to specific areas? Some how the page(s) need to identify only users who can enter and reject others. I built this earlier by terminating sessions and forcing the user to relogin but its a poor way of doing it as the user can just type in the url while in session and go directly to the desired page without hitting the end session script. Hopefully this makes sense. Thanks for your help!

    57
  58. I could not get this to work. Gets stuck at the manage-check.php page. I took dfreer’s advice in post 39 but that still didn’t work.

    Any ideas? Just comes up with blank page at manage-check.php

    58
  59. Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at C:\xampp\htdocs\itpro\check.php:2) in C:\xampp\htdocs\itpro\check.php on line 3

    Warning: Cannot modify header information - headers already sent by (output started at C:\xampp\htdocs\itpro\check.php:2) in C:\xampp\htdocs\itpro\db.php on line 22

    i cant solve this plz solve it for me…

    59
  60. This php login script using session and MySQL works great… But the only problem is, it does not prevent double username login with the same account… Does anybody know how to solve this?

    60
  61. hi, am trying to implement this tutorial, have added sample data to members table as suggested above;

    INSERT INTO `members` VALUES (”, ‘admin’, ‘5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8′);

    but get the following error;

    Could not connect: Access denied for user ‘username’@'localhost’ (using password: YES)

    any ideas?

    thanks!

    61
  62. Thanks for the script.

    Could you create a script for adding new users to the database also?

    62
  63. Thanks for the tut… but I was actually wondering how you keep from having old POST data from sitting around in a browser’s history…

    for example… someone logs in… then they log out… later someone else hops on and goes “back” in the browser to the page right after they submit the username/password… in IE, it asks if you want to resubmit the old data… so someone can effectively log back in with the original login data.

    How do you prevent this?

    63
  64. Why has no one answered the question why with some people and including myself does the “manage-check.php” page show up blank and not redirect. I had it working before but now for some stupid reason it does not anymore. Is it possible that some variables could be in memory and getting stuck on the server side?

    Thanks in advance.

    64
  65. I have a problem.. I have used your files that you uploaded.. And when I try to log in i get no error.. But it just don’t want to send me to the member page.. plz help..

    I did replace the information in db.php so that it fits to my server..

    plz help

    65
  66. Hey all! I’ll try to write an article that answers all the questions posted here and with all the additional code that has been suggested here. Stay tuned!

    66
  67. Same problem as a few others. When login - just goes to manage-check.php with a blank screen. Anyone know why this happens?

    67
  68. Hi..
    I m a beginner PHP.. i have test and success have not error, but why if i had login and submit then show “http://localhost/web_erp/test_login/index.php?msg=login_failed”
    always like that…

    plz help…

    thx a lot

    68
  69. I am some how new to php, please I will like to know how all userID and password can access from a text file as the database not with use of SQL . but if only SQL can be use, how can I refer to that database file from the script.

    _______________________________
    logindetail.txt
    _______________________________

    username::::passsord:::name:::gender
    username::::passsord:::name:::gender
    username::::passsord:::name:::gender
    username::::passsord:::name:::gender

    _______________________________
    How can I use a text database like this.
    I need it for a project.
    Thank

    69
  70. hey,

    i was wondering, how would you create a REGISTER page and script? Thats all i need and my website is perfect and set to go!!!!

    70
  71. Hey, I’m not great at coding but I want to know why did you use ” instead of ” on the index.php?

    I tried it without changing anything and I cannot click on the button. In fact there was no button at all! All I got was 3 textboxes! =/

    Anyway thanks!

    71
  72. Ok, on my 1st post I think I made a mistake.

    You have used ”…” instead of “…”, but why?

    72
  73. Parse error: parse error, unexpected T_ENDIF in /var/www/sitename/foldername/manage-check.php on line 34

    Why it is happened?

    73
  74. I would like to check with you some issues.After the log-in is successful, if the user uses the browser back button and suppose if the user reached the index page.In this case is there any way we can do a forced log-out or unset($_SESSION['member_ID']);
    Anyway thank you very much for good tutorial.

    74
  75. I received these warnings. Where’s the problem.
    Warning: session_start() [function.session-start]: open(/tmp/sess_e4643b432f48384577cc9c59dcffac4b, O_RDWR) failed: Permission denied (13) in /home/osmalan/public_html/manage-check.php on line 3

    Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at /home/osmalan/public_html/manage-check.php:3) in /home/osmalan/public_html/manage-check.php on line 3

    Warning: Cannot modify header information - headers already sent by (output started at /home/osmalan/public_html/manage-check.php:3) in /home/osmalan/public_html/manage-check.php on line 25

    Warning: Unknown(): open(/tmp/sess_e4643b432f48384577cc9c59dcffac4b, O_RDWR) failed: Permission denied (13) in Unknown on line 0

    Warning: Unknown(): Failed to write session data (files). Please verify that the current setting of session.save_path is correct (/tmp) in Unknown on line 0

    You can try username akpirttin with password lkjd

    75
  76. omg… this wud be great if i didnt keep getting the error:

    Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource

    Warning: Cannot modify header information
    plz plz plz plz hlp me
    i copied the code exactly this makes no sense

    76
  77. Someone mentioned preventing multiple logins. I use an extra field in the user table (currentkey) which is a random string generated on login and the check at the top of each script looks at that rather than the id. Any subsequent login resets the currentkey invalidating the previous login, the logout clears the currentkey. I am considering a check on the login page to say “you’re already logged in” but I haven’t done it yet.

    77
  78. I need help I am so new to php please help no matter what php I use I seem to always get these two error

    Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in /home/content/a/d/m/admincaddie/html/scdsite/login2/manage_checks.php on line 12

    Warning: Cannot modify header information - headers already sent by (output started at /home/content/a/d/m/admincaddie/html/scdsite/login2/manage_checks.php:12) in /home/content/a/d/m/admincaddie/html/scdsite/login2/manage_checks.php on line 14

    78
  79. ok i followed all the above now how do i put in a user in MySQL and so that that user can then login and hpw do i put that to a specific page???

    79
  80. Hey, this is just a guess, but wouldn’t it be better to store the password as a char(40) binary, or does that not make a difference? Also, i’ve seen some scripts that store the session id as a sha1 encryption.

    80
  81. I am having a problem with db.php

    I have my database setup EX)

    <?php
    // Connects to your Database
    // Connects to your Database
    mysql_connect(”p41mysql161.secureserver.net”, “sweets_eg”, “Alexia01″) or die(mysql_error());
    mysql_select_db(”sweets_eg”) or die(mysql_error());

    I am using your script trying to figure out how to connect to the DB: I am getting this error.

    Warning: mysql_connect(): Can’t connect to local MySQL server through socket ‘/usr/local/mysql-5.0/data/mysql.sock’ (2) in /home/content/s/h/a/shawngjohnson/html/db.php on line 12
    Could not connect:

    Can you please help

    81
  82. on my homepage i never get stuck at manage-check.php but on my other page that uses the login i get stuck.

    82
  1. 1 php registration - DesignersTalk
  2. 2 Week 11 new « Ryan’s Photo Album
  3. 3 php client login system - DesignersTalk

Leave a Reply




XHTML: You can use these tags <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> :
If you want to include PHP-code you can do so by writing <code>[php]my_function()</code>

Comments for this post will be closed on 20 August 2009.