Skip to page content or skip to Accesskey List.
Search evolt.org
evolt.org login: or register

Work

Main Page Content

Creating a Login Script with PHP 4

Rated 4.18 (Ratings: 20) (Add your rating)

Log in to add a comment
(89 comments so far)

Want more?

 
Picture of jesteruk

Jester uk

Member info | Full bio

User since: December 22, 2001

Last login: December 22, 2001

Articles written: 6

In this article we're going to create a login script with PHP that will allow registered users to login to your site. With this method we'll make restricting certain areas of your site to registered users child's play.

What's the point?

There could be many reasons you want to restrict access to registered users only. Say you have a rating script on your site, yet you don't want unregistered users to be able to submit their rating (as they do here on evolt.org). You could require a user to be logged in before they could access the rating script by including a login check script at the beginning of a document.

Requirements

To use this script you must have access to PHP 4, and the PHP installation must be configured to allow sessions. We're going to use sessions with PHP 4 to check the user's input, and if it is indeed the information of a registered member, register this information as session variables so the script doesn't have to request their login info time and time again. It will create a session for them and "remember" the user until they log out.

Enough yappin', let's code it.

Start the Session

<?
session_start(); // start session, duh.
?>
<!-- header tags, edit to match your own, or include() template header file. -->
<html>
<head>
<title>Login</title>
<head>
<body>
<?

Alright, besides adding alittle header HTML in, the only useful bit in there is session_start() (click it). All this function does is initialise a session, or resumes the current one, bah, read the page. So now we have our session started, let's get it going.

Check Client

Next we need to check if the client is already logged in or not. If they are, leave them be, if they're not, pop up a login form:

if(!isset($username) | !isset($password)) {
// escape from php mode.
?>
<form action="<?=$PHP_SELF?><?if($QUERY_STRING){ echo"?". $QUERY_STRING;}?>" method="POST">
<p align="center">Members only. Please login to access this document.</p>
<table align="center" border="0">
 <tr>
  <th>
Username:
  </th>
  <th>
<input type="text" name="username">
  </th>
 </tr>
 <tr>
  <th>
Password:
  </th>
  <th>
<input type="password" name="password">
  </th>
 </tr>
 <tr>
  <th colspan="2" align="right">
<input type="submit" value="Login">
</form>
  </th>
 </tr>
</table>
</body>
</html>
<?
exit();
}

OK now $username and $password are our session variables. These variables will be registered and be available to all scripts whilst our session is open. If they're not set, then the user isn't logged in and we need to set them before the client can access the document, so we present them with a form and ask them for their username and password. I also made it so if there's a query string, add it into the form action. Say a user requested index.php?action=mail but they're not logged in. When the login form is displayed, and they login, you want them to end up where they were heading (index.php?action=mail, not just index.php), they will.

Verify The Client

Next we need to register the session variables, if the user has just submit the login form then this bit of code will register them as session variables, and authenticate them.

// If all is well so far.

session_register("username");
session_register("password"); // register username and password as session variables.

// Here you would check the supplied username and password against your database to see if they exist.
// For example, a MySQL Query, your method may differ, obviously you would make a dataabse connection first.

$sql = mysql_query("SELECT password FROM user_table WHERE username = '$username'");
$fetch_em = mysql_fetch_array($sql);
$numrows = mysql_num_rows($sql);

if($numrows != "0" & $password == $fetch_em["password"]) {
$valid_user = 1;
}
else {
$valid_user = 0;
}

OK first we use session_register() to register the client's username and password as session variables. Then we need to check if the username and password they supplied are valid. Bear in mind this is only an example, but say we have the below table in our database:

id username password
1 fred Mypass
2 bob bobspassword
3 lace letmein

Now say bob is presented with the login form. He enters his username, bob, and his password, bobspassword. The script then registers these values as his session variables, then queries the database for a row where the username is bob and retrieves the password, it also counts the number of rows where the username is bob. Now if all goes well, $numrows should contain the int value of 1, $fetch_em[&quot;password&quot;] will contain the user's password.

if($numrows != &quot;0&quot; &amp; $password == $fetch_em[&quot;password&quot;]) {

If the number of rows affected is not equal to zero and the password the user supplied is equal to the password retrieved from their database row, their information is correct, making them a valid user. If the above logic isn't true, set $valid_user to zero.

If information is incorrect

If the user enters incorrect information, up to now all the script does is check if the session variables are registered or not, so we need to add in a little bit to request their information again:

// If the username exists and pass is correct, don't pop up the login code again.
// If info can't be found or verified....

if (!($valid_user))
{
session_unset();   // Unset session variables.
session_destroy(); // End Session we created earlier.
// escape from php mode.
?>
<form action="<?=$PHP_SELF?><?if($QUERY_STRING){ echo"?". $QUERY_STRING;}?>" method="POST">
<p align="center">Incorrect login information, please try again. You must login to access this document.</p>
<table align="center" border="0">
 <tr>
  <th>
Username:
  </th>
  <th>
<input type="text" name="username">
  </th>
 </tr>
 <tr>
  <th>
Password:
  </th>
  <th>
<input type="password" name="password">
  </th>
 </tr>
 <tr>
  <th colspan="2" align="right">
<input type="submit" value="Login">
</form>
  </th>
 </tr>
</table>
</body>
</html>
<?
exit();
}

here we use session_unset() to unset the registered session variables and session_destroy() to kill the session completely, just to make sure. Then we present the user with a login form telling them the supplied information was invalid, please try again.

Logging Out

Once the user is logged in, each time they try to access a protected document the above script will recognise their session and allow them to access. It is wise to have a logout script that simply terminates the session and offers them a link to login again or go to "home", see below:

<?
session_start();
session_unset();
session_destroy(); // destroy session.
?>
<html>
<head>
<title>Logged Out</title>
</head>
<body>
<p align="center">You have been successfuly logged out.</p>
<p align="center"><a href="members.php">Log back in</a> | <a href="index.php">Go to homepage</a></p>
</body>
</html>

All we have done is destroyed the session completely and informed the user they are now "logged out".

The Scripts

login.php

<?
session_start(); // start session.
?>
<!-- header tags, edit to match your own, or include template header file. -->
<html>
<head>
<title>Login</title>
<head>
<body>
<?
if(!isset($username) | !isset($password)) {
// escape from php mode.
?>
<form action="<?=$PHP_SELF?><?if($QUERY_STRING){ echo"?". $QUERY_STRING;}?>" method="POST">
<p align="center">Members only. Please login to access this document.</p>
<table align="center" border="0">
 <tr>
  <th>
Username:
  </th>
  <th>
<input type="text" name="username">
  </th>
 </tr>
 <tr>
  <th>
Password:
  </th>
  <th>
<input type="password" name="password">
  </th>
 </tr>
 <tr>
  <th colspan="2" align="right">
<input type="submit" value="Login">
</form>
  </th>
 </tr>
</table>
</body>
</html>
<?
exit();
}

// If all is well so far.

session_register("username");
session_register("password"); // register username and password as session variables.

// Here you would check the supplied username and password against your database to see if they exist.
// For example, a MySQL Query, your method may differ.

$sql = mysql_query("SELECT password FROM user_table WHERE username = '$username'");
$fetch_em = mysql_fetch_array($sql);
$numrows = mysql_num_rows($sql);

if($numrows != "0" & $password == $fetch_em["password"]) {
$valid_user = 1;
}
else {
$valid_user = 0;
}

// If the username exists and pass is correct, don't pop up the login code again.
// If info can't be found or verified....

if (!($valid_user))
{
session_unset();   // Unset session variables.
session_destroy(); // End Session we created earlier.
// escape from php mode.
?>
<form action="<?=$PHP_SELF?><?if($QUERY_STRING){ echo"?". $QUERY_STRING;}?>" method="POST">
<p align="center">Incorrect login information, please try again. You must login to access this document.</p>
<table align="center" border="0">
 <tr>
  <th>
Username:
  </th>
  <th>
<input type="text" name="username">
  </th>
 </tr>
 <tr>
  <th>
Password:
  </th>
  <th>
<input type="password" name="password">
  </th>
 </tr>
 <tr>
  <th colspan="2" align="right">
<input type="submit" value="Login">
</form>
  </th>
 </tr>
</table>
</body>
</html>
<?
exit();
}
?>

logout.php

<?
session_start();
session_unset();
session_destroy(); // destroy session.
?>
<html>
<head>
<title>Logged Out</title>
</head>
<body>
<p align="center">You have been successfuly logged out.</p>
<p align="center"><a href="members.php">Log back in</a> | <a href="index.php">Go to homepage</a></p>
</body>
</html>

Now to require a user to log in, simply include the login script at the top of a php page.

include($DOCUMENT_ROOT .'/includes/login.php'); &nbsp;// or wherever yours is.

Bear it in mind that the session places a cookie on the client's machine, so if they are not accepting cookies this script will have problems logging them in. There is a work-around for this by using the session ID (session_id()) and passing it along in the query string, through form and links and such, and the variable is only set when a cookie cannot be set, providing an easy way to check if a user is accepting cookies or not. For more information see php.net's sessions reference.

Inspiration

In this article the script is used to require a user to login (as you may have noticed). This is just one application, you could have it so there is only one valid username and password pair and use it as an admin script, restrict access to each admin document by including it at the top of each file. I used this method in a guestbook script I recently wrote.

Hint: make sure you include the login script in your PHP document before any output, as you would use the setcookie() function, unless you want a "Headers already sent" error.

Look Into It

Sessions with PHP 4 is a powerful and easy-to-use method to register variables across requests. I recommend you look into sessions and learn more about them. As with all things it has advantages and disadvantages. Problems arise in certain circumstances, users have cookies off, but that's all part of building a compatible-for-all website. Have a play around on your personal server, or your host, you'll like it.

Bibliography

If you're curious and want to learn more about this nifty feature in PHP 4 visit php.net:

  • Php.net's Session Documentation
  • I just like messing around with web design stuff, just a hobby.

    Particularly perl, PHP and SQL.

    http://www.free2code.net/

    use the database more...

    Submitted by warpedjedi on January 9, 2002 - 08:09.

    why not expand the query to include the password?

    SELECT * FROM user_table WHERE username = '$username' AND password = '$password'

    then check for $numrows != "0" only.

    this way, it'd be easy to have encrypted passwords in the DB.. in this case it'd be:

    SELECT * FROM user_table WHERE username = '$username'") AND password = PASSWORD('$password')

    this is assuming that you stored the password in the database using the mysql PASSWORD function... if you're like me and feel weird storing cleartext passwords in a database.

    i would also have some sort of variable check so that the user can't pass a wildcard character into the script, just to be safe.

    good article though...

    -wj

    login or register to post comments

    up to you....

    Submitted by jesteruk on January 9, 2002 - 14:17.

    The point of the article wasn't the method of storing user information in the database, obviously there'd be more in, their email, personal info and stuff, to create a community feel. The database stuff is just an example i stuck in to show a version of the script that will actually function.

    The method you choose to sign users up, and extract that information from the database, or flat file for authentication purposes is entirely up to you, i tried to focus more on introducing people to sessions with PHP 4, they're very handy.

    Points well made though, will give some people more ideas to expand upon

    login or register to post comments

    Security issue

    Submitted by boysimple on January 16, 2002 - 11:02.

    This script has a bit of a security problem, in that if someone calls the URL of the login page like so:

    http://www.foo.com/login.php?valid_user = 1

    they can automatically gain access. PHP 4.1 deals with this. and yes - the person does have to know the name of the variable. But nonetheless, there are more secure ways (putting the value in an array, storing it in the database with a session ID, etc)

    However I really like the article, and these are the kind of things that make evolt a great site.

    login or register to post comments

    hummm...

    Submitted by jesteruk on January 16, 2002 - 14:16.

    How can that be?

    if($numrows != "0" & $password == $fetch_em["password"]) {<br>
    $valid_user = 1;<br>
    }<br>
    else {<br>
    $valid_user = 0;<br>
    }

    If they send valid_user=1 in the query string, the script still processes their session variables and if their username and password aren't authenticated, $valid_user will be set to zero, which is why i included the else statement in there. Wouldn't it? lol I don't think that'd be a problem.

    login or register to post comments

    actually

    Submitted by boysimple on January 16, 2002 - 14:23.

    From:

    http://www.php.net/ChangeLog-4.php

    "For various reasons, PHP setups which rely on register_globals being on (i.e., on form, server and environment variables becoming a part of the global namespace, automatically) are very often exploitable to various degrees. For example, the piece of code:

    <?php
    if 
    (authenticate_user()) {
      $authenticated = true;
    }
    ...
    ?>

    May be exploitable, as remote users can simply pass on 'authenticated' as a form variable, and then even if authenticate_user() returns false, $authenticated will actually be set to true. While this looks like a simple example, in reality, quite a few PHP applications ended up being exploitable by things related to this misfeature"

    It doesn't work exactly as you think it would. But it is a security hole.

    login or register to post comments

    well..

    Submitted by jesteruk on January 16, 2002 - 14:38.

    That's an exploit that relies on poor coding. if an else statement were to be added into the above code:

    else {<br>
    $authenticate = 0;<br>
    }<br>

    Then the variable they created by inputting to the query string would be over-written, i do believe. That isn't really an exploit, that's just stupid coding, never let a user control a variable unless that's what you want. Always put in else.

    Thanks for the comment on the article tho ;)

    login or register to post comments

    gah

    Submitted by boysimple on January 16, 2002 - 16:32.

    for some reason my brain put the else{} in there- even though it obviously isn't.

    sorry bout that.

    login or register to post comments

    ah...

    Submitted by jesteruk on January 16, 2002 - 19:14.

    If anything, it will teach some people to be more careful with their scripting, is a good point you raised man.

    login or register to post comments

    Use of Apache's .htpasswd for authentication

    Submitted by hpoe on January 17, 2002 - 00:09.

    @jesteruk

    Thanks for this great article!

    Your wrote:

    The method you choose to sign users up, and extract that information from the database, or flat file for authentication purposes is entirely up to you, i tried to focus more on introducing people to sessions with PHP 4, they're very handy.

    Q: Is there any way to access and use Apache's .htpasswd file for authentication trough your script?

    thx
    Henning

    login or register to post comments

    .htaccess

    Submitted by warpedjedi on January 17, 2002 - 07:55.

    henning,

    you can open the .htaccess file, grab the encrypted password and then change his code to use the following:

    if (crypt($password,$htaccess_password) == $htaccess_password) {
    // password is correct...
    }

    BUT, if you have an .htaccess file, why use php to check it? just protect the directory that the script is in and then you can use php to find out the username of someone who has logged in using apache htaccess authentication: that information is contained in the global variable $PHP_AUTH_USER.

    although, using either method doesn't allow for more interesting data to be stored about a user.

    hope this makes sense... i usually don't type before 9am. ;)

    -wj

    login or register to post comments

    yup...

    Submitted by jesteruk on January 17, 2002 - 14:50.

    You're right warpedjedi, that is why i'd always store my users' info in a database, to create more of a community feel, let users view other user's profiles and such, of course the passwords should be encrypted in the database, but the point of this article wasn't how to write an authentication system lol that's why the authentication code in this script leaves alot to be desired.

    The only reason i can think of is you already have alot of users and don't wanna stick all the info in a database, so i'll explain a little:

    Just read the .htpasswd file into an array, if you don't know how, look up fopen() and fread() functions and learn how to handle data from flat files with PHP, split at the : to get the password for the appropriate line in the password file (if it's there). Now the problem is the passwords are encrypted, so when comparing the user's submitted password to the password from .htpasswd it wont match. You can use the crypt() function (see warpedjed's code above) to encrypt the password the user submitted and then compare the encypted pass to the encryted pass from the .htpasswd file, if they match, they're in.

    login or register to post comments

    Logout tweak

    Submitted by sarahenglish on January 18, 2002 - 21:51.

    Hi, thanks for a great article. It got me up and going fairly quickly, but Logout just was not working. I was getting a nasty "Trying to destroy uninitialized session " error on logout.php until I added: session_start(); right above session_destroy(); This resumed the session so I could then destroy it. I don't know all the ins-and-outs, but it works, which it didn't for me before.

    login or register to post comments

    oops..

    Submitted by jesteruk on January 18, 2002 - 23:28.

    good point sarah, i didn't think of that, you can't destroy a session unless you resume it with session_start() first, but my logout coding is in the login script, just a conditional and if it's present it kills their session, i just separated it into a different file for the article, sorry about that.

    -J

    login or register to post comments

    .htaccess and login

    Submitted by Fuchur on March 20, 2002 - 12:38.

    How does the login script look if you dont get it out of a sql dbase but out of .htaccess, where they login with? Passwords are encrypted.... Would be very happy to see that! Drop me a line at my mail address CU Frank

    login or register to post comments

    Works like a Champ

    Submitted by TragicGod on April 23, 2002 - 04:03.

    I was also having problems with the logout.php page with the "Trying to destroy uninitialized session " but after addnim session_start() it runs sweet. Thanks

    login or register to post comments

    Login Form on its own

    Submitted by shane1090 on May 6, 2002 - 14:33.

    This script only brings up the login form when you try to get to a page that requires you to be signed up. What is the code to allow me to have a login form on a page? as i am pretty new to PHP.

    login or register to post comments

    RE: Login Form on its own

    Submitted by TragicGod on May 6, 2002 - 14:43.

    All you have to do is modify the script to your needs. I have done so and it works great.......

    login or register to post comments

    Yeah

    Submitted by jesteruk on May 6, 2002 - 17:42.

    Keep your eyes peeled for the new version, TragicGod. That code is pretty badly written, I'm going to write "Creating a login system with PHP 4, Part II". I will include the user database, authentication methods in more detail, and maybe throw in a "users online" script like i use on my site.

    I just need to find the time to write it. What do you mean Shane? The script pops up a login form if the user is not "logged in". If you just want to display a login form to a user, just copy the HTML code and use that?

    login or register to post comments

    hmm

    Submitted by travis1 on May 8, 2002 - 07:05.

    I am a newbie php programmer and i wanted to know a few things...

    Before I read this article I had this idea that I would make my site so that a few ppl i would let be admin can post news on my website. I decided to store the files in a table on the mysql database with the fields; id, username, password. I created a form in html where the user can enter username and password. Next i made a file with the mysql connect and the data base connect. In that file i had a query which was: $result = mysql_query( "SELECT * FROM login WHERE Username = '$username' AND password = '$password' "); $num_rows = mysql_num_rows( $result ); after that i had an if if ( "$num_rows == 1" ){ just to test it i had print " welcome user"; }else{ print "sorry"; } then i had mysql close. Now i had the form action going to the mysql connect file. If I entered the correct usename and password, say for example my namer it would say welcome travis, if the username or password was wrong it would say sorry.

    Now all of that worked but i was unsure if it was secure, say for example the servers php goes down, the php source can be viewed so then ppl can see the database password. There for i decided to create a file i called free.php which the form action went to. In the file free.php i made it so that the mysql connect and query file was included but i was still not satisfied. Now in the free.php it has include( "mysql.php" ) so then if the php on the web server went down all that a malitous person would need to do is view the source of free.php and go to mysql.php to find the database passwords. I then decided to store the passwords in a seperate file as variables and set unix permissions off. When i did this the code could not be executed. Any how i still left the passwords in the free.php so that in the free.php there is include("passes.php"); include("mysql.php")

    Now the hard part. I wanted to try and redirect to another page straight away and stay logged in so that ppl would not even know that passes.php was there and mysql.php was there. There is where my knowledge ends; only been learning php from a book and internet of 3 weeks and i am 15 years old still at school.

    I searched around to find out how to redirect. I found that using a header will redirect. I still didnt know how to stay logged in though after the redirect. Thats when i found this site. I tryed using session's and session register but say for example i have only one user in the data base. So the username is hello and password computer. They type this in the form the free.php redirects to another php page after that which that page includes the (!session_is_registered) thing. if not regestered it would go back to the index.html. If logged in it would display Welcome $username which would be Welcome hello. However i try logging in as a unautharized user for example abc and password 123, it would still redirect to the new file and it would display welcome abc.

    Can any body help me please!... It would be much much appreciated

    login or register to post comments

    sorry

    Submitted by travis1 on May 8, 2002 - 07:06.

    hmm sorry paragraphs didnt work in the other post :D

    login or register to post comments

    security and redirects

    Submitted by Martin Tsachev on May 8, 2002 - 12:53.

    If you want it to be secure you just need to save your database username and password in an include file that's not accessible by the webserver. Say you have your website in /home/shaggy/public_html/ then store that file in /home/shaggy/.

    As for redirects use header(&quot;Location: /foo/bar&quot;);. Your session will be lost if you redirect over domains.

    If I forgot anything just mention it. It is unreadable like that.

    Jester:
    You can make use of PHP classes when you write the sequel of the script. It is a much cleaner solution and it is usually plug and play(pray).

    login or register to post comments

    inc

    Submitted by travis1 on May 8, 2002 - 17:12.

    yes i have seen that in my book inc but i am not up to it yet, maybe i was jumping a bit ahead but i am 75 % of the way to make the login - addnews module that i want to finish it now. So when saving an inc do i save it as pass.inc.php or pass.inc or pass.php.inc. Also i was thinking today after reading a bit about cookies i might be able to actually make a session id with cookies to protect the redirected page

    login or register to post comments

    yum yum cookies...

    Submitted by travis1 on May 9, 2002 - 02:03.

    After reading up a little on cookies i found that my book told u how to set a cookie and tells u how to get visit information using the mysql data base. Usually I try and work every thing out for my self first but i really want to get this login working soon. I want to set a cookie so it recognises that it is an authentic user with the database and allows them to view pages others cant. On the other hand I want non authentic users to be redirected back to index.html.

    now all i really need to know is how to log in using the mysql data base on one page and stay logged in on after being redirected so that no include file functions for the mysql connect will be used.

    login or register to post comments

    you need sessions

    Submitted by Martin Tsachev on May 9, 2002 - 14:44.

    You need sessions: that's the best way to do it.

    On the filename issue: it doesn't really matter. If you can't have a .htaccess file go with the .php extension, otherwise you can forbid access to .inc files and that won't fail even if the server is started without PHP support.

    login or register to post comments

    Shaggy

    Submitted by jesteruk on May 9, 2002 - 19:18.

    Use PEAR::DB or something? The subject of the article is really a login system, not a database article, I don't want the article to be so complex I am answering questions on it for months afterwards. I want to keep the coding quite simple so it's easily customisable. I want PHP newbies to understand it, too. Although PEAR::DB is easy to use. I will think about it.

    login or register to post comments

    PEAR::DB?

    Submitted by Martin Tsachev on May 10, 2002 - 05:11.

    Jester I'm talking about packing your script as a PHP class thus making it more portable. PEAR::DB is really easy I actually don't think there's any differece between using MySQL specific calls VS PEAR::DB.

    login or register to post comments

    PHP class for logging in

    Submitted by Martin Tsachev on May 10, 2002 - 05:47.

    Actually if you want I can give you such a script BSD licensed if you want to see how it works. I've written the code for my site but it is still in beta.

    login or register to post comments

    hmmmmm

    Submitted by jesteruk on May 10, 2002 - 19:00.

    Shaggy, this isn't a development script, if I were writing a fully usable script I would put it up for download on my site. The point of an article is to give people ideas, and introduce them to new concepts, the learning process is then up to them.

    Of course using PEAR::DB is different from MySQL-specific functions, the whole point of PEAR::DB is to allow the code to work with a multitude of database engines, increasing portability.

    Sure, you can send me the script Shaggy, you know my e-mail. Let me have a gander.

    login or register to post comments

    Login time expiration with this script

    Submitted by George on June 1, 2002 - 02:24.

    Hi, how can I make this script for time expiration login ? I want to logout user after 15minutes if he don't make any activity. Thanks, George

    login or register to post comments

    Re: Login time expiration with this script

    Submitted by Martin Tsachev on June 2, 2002 - 15:00.

    Actually George there's no problem to expire the whole PHP session so you can do this with a setting like: php_value session.cookie_lifetime n where n is the expiration time in seconds for the session cookie. This should be put in a .htaccess file. You can also do this via plain PHP code.

    login or register to post comments

    Good article

    Submitted by Markavian on July 8, 2002 - 08:13.

    Thank you for introducing session variables to me. I did a search on Google.com and caim up with this article.

    I followed through your steps, and added the bits of code.

    I replaced the password check with my own text database script (MySQL not available).

    Fiddled around with the error messages, and login form design.. ..and hey presto, a complete mini-site with user authentication within an hour.

    Cheers

    login or register to post comments

    .htaccess login

    Submitted by chrisl on July 9, 2002 - 11:37.

    I read the comments above, about adding the code suggested. But I am not sure what to implement that code. Has anyone successfully used this script with .htaccess/.htpasswd. If so, could you please help me out. I am struggling quite a bit, and I could really use some help. Thank you

    login or register to post comments

    Re: Login time expiration with this script

    Submitted by mojokitten on July 16, 2002 - 08:06.

    I, too, have been hunting everywhere for some way to just stick an expiration variable in my session. I've already got session handling scripts written - that's just the missing piece of the pie, as it were. You said this could be done via plain PHP. Could you point me to some resource(s) that might help me on my way? Thanks!

    login or register to post comments

    Re: Login time expiration with this script

    Submitted by Martin Tsachev on July 16, 2002 - 08:45.

    Well what's the problem with adding a database column to hold the expiration time or expiring the session cookie itself?

    login or register to post comments

    Re: Login time expiration with this script

    Submitted by Martin Tsachev on July 16, 2002 - 08:47.

    Well what's the problem with adding a database column to hold the expiration time or expiring the session cookie itself?

    login or register to post comments

    Expiration time for sessions

    Submitted by Markavian on July 16, 2002 - 11:02.

    I don't know if there is any expiration time. Sessions only last as long as the browser is open. When you close the browser, the session is destroyed anyway.

    You could put a javascript redirect in. Just a counter that goes up to 15 minutes on a page, and if it reaches 15, then redirect to a session destroy page.

    Really tho, I don't think you need one. Unless you can justify a good reason.

    login or register to post comments

    Re: Expiration time for sessions

    Submitted by Martin Tsachev on July 17, 2002 - 18:02.

    Actually this is only the default behaviour which can be changed.

    login or register to post comments

    Complicated

    Submitted by Markavian on July 18, 2002 - 02:05.

    Okay, I just had a quick search around.. there doesn't seem a quick way.

    There is no default function for destroying a session.

    I can see two ways of logging the user out:

      1) Javascript timer, counts up/down and then redirects to a PHP session destroy page.
      2) Server side logging of each user, which records last login time (in a database). Each time the user visits a page, the server checks to see how long it was since they last visited a page. If the difference in time is greater then a given value, it runs a session destroy, and deletes the user from the database.

      Wanna try one of those?

      login or register to post comments

    Expiration time for sessions

    Submitted by chowmein858 on July 22, 2002 - 11:12.

    why would you want to delete a user whom just visited your site from your database? Would it not be better to add a column in your db that always has the current time and compare that with the time the user last visited your site? then run a script that would delete users who have not visited your site in awhile. I'm really new to website design so escuse me if it seems i dont' know what im talking about. Cause i don't even have a clue on how to write the script im talking about. If such a script is possible it would really helpful if someone can give me a link to such a tutorial or sample script. :)

    login or register to post comments

    Yeup

    Submitted by Markavian on July 22, 2002 - 12:00.

    Thats exactky what I just said.

    The thing is, its such a useless thing to do.. no one sems to be bothered to make a script up.

    If the webhost is interested in keeping his/her database 'clean' then make a form page somewhere in a secure area, with one big button that says 'PRUNE'.

    For a mySQL database use a command like:

    mysql_query("DELETE from myTable WHERE TO_DAYS(NOW()) - TO_DAYS(lastvisit_date) >= 30");

    This will quite happily delete all lastvisit_date entries which are 30 days or older.

    30 days, good number.. just over a month.

    login or register to post comments

    Jesteruk

    Submitted by phpoo on July 24, 2002 - 02:07.

    Jestuk,

    You've saved me again. This article and your one on multiple pages have both saved me from going bald(balder :D ). I'm originally a Perl programmer that has finally given into the PHP craze. You've made my switch easier then I could have even hoped for. Thanks again and I look forward to reading your articles in the future... especially the Part 2's :)

    login or register to post comments

    Finally!!!

    Submitted by sushin on August 26, 2002 - 06:28.

    Ive spent so long trying to find a simple form based login script in php. Theyre normally the ones with the Standard Windows Authentication window... Nice One!!

    login or register to post comments

    Still not there..

    Submitted by Mart on September 1, 2002 - 15:42.

    Hi Jestuk.
    Beeing new on php i still have a little problem getting the script to work. I get a "Page cannot be display" clicking the "Login" - button. The weirdest url ever is showing in my browsers adress field saying $QUERY_STRING is undefined. Seems like the action string doesn't work as it is supposed to in the form-tag.
    What did i miss?
    /Mart sthlm

    login or register to post comments

    Re: Still not there..

    Submitted by Martin Tsachev on September 2, 2002 - 02:14.

    Mart, it seems like you have register_globals disabled.

    If your server is Apache you can turn it on via a .htaccess file located in the your server root. Add php_flag register_globals on to this file.

    login or register to post comments

    Stil not there...

    Submitted by Mart on September 2, 2002 - 02:43.

    I'm running IIS 5 though, and that CGI -type of installation of PHP. Does that matter?

    login or register to post comments

    For IIS

    Submitted by Martin Tsachev on September 2, 2002 - 02:55.

    For IIS edit your php.ini file, probably located in c:\winnt\. There should be a line which says register_globals = off, just change that to on.

    You don't need to restart your webserver, the next request should reflect the change.

    login or register to post comments

    For IIS

    Submitted by Mart on September 2, 2002 - 03:50.

    Thanks Shaggy, but it still doesn't work, I get the same error message. Why doesnt PHP engine rekognize $QUERY_STRING ?

    login or register to post comments

    Did it!

    Submitted by Mart on September 2, 2002 - 05:17.

    Hi again and thanks for helping me out. I found out the problem was I didn't define the vars as globals (my login-form was printed by a php function).
    It had probably not worked without your help shaggy. Thanks (nice forum this, people seem nice and serious, i like that).
    /Mart

    login or register to post comments

    Can this peace of code be added?

    Submitted by nixisue on September 9, 2002 - 05:35.

    ...so IE users can't go back ater logout and see data

      if(!isset($PHP_AUTH_USER)) {
      <br> Header("WWW-Authenticate: Basic realm=\"My Realm\"");
      <br> Header("HTTP/1.0 401 Unauthorized");
      <br> echo "Text to send if user hits Cancel button\n";
     <br> exit;
     <br> } else {
     <br> echo "Hello $PHP_AUTH_USER.<P>";
     <br> echo "You entered $PHP_AUTH_PW as your password.<P>";
     <br> }


    THX

    login or register to post comments

    OOOPS this looks nasty

    Submitted by nixisue on September 9, 2002 - 05:36.

    :)

    login or register to post comments

    The access keys for this page are: ALT (Control on a Mac) plus:

    evolt.orgEvolt.org is an all-volunteer resource for web developers made up of a discussion list, a browser archive, and member-submitted articles. This article is the property of its author, please do not redistribute or use elsewhere without checking with the author.