Search
Left Quote    By failing to prepare, you are preparing to fail.
- Benjamin Franklin    
Right Quote
 
[login] | [Register]
 

Complete Members System

by: bs0d
Page: 9 of 9
(View All)

LOGOUT

Once your members are able to sign in, they should have the option to sign out. Create a file called "logout.php" and if a member is logged in, display this link so that they may access it. Below is the code used to successfully logout a user:


As you see, we set $_SESSION['logged_in'] to equal 0, because it is set to 1 when they are signed in. Next, notice we are setting another cookie. Notice though, the setcookie( ); function. We are not setting a cookie, but deleting the one specified. This is achieved by setting a negative time. In this example I used time() - 60. This will successfully delete the cookie that was set if the user chose "Remember me." Finally, a call to session_destroy(); will delete all of the data that is in the current session. Afterwards, we use header( ); to automatically reload us to a desired page. In most instances, the index or main page of your site if you so choose.

CONCLUSION

Well, Kudos to those who actually read through the entire tutorial! If you did, you should be able to grasp the concept pretty easy. I didn't care how long the tutorial would turn out to be. I wanted to make sure that everyone who read through would be able to have a good start at building a member system for their own website. I did not write the tutorial in one setting, this is probably a couple of months worth of 10 minuts free time here and there. So if any part seems repetitive, irrelevant or off topic in any way just let me know and I can make revisions.

In this tutorial, code for scripts are broken up into alot of parts. So here is the full code for each script. If anyone has any questions, feel free to join discussion in our AllSyntax.com Forums!

Enjoy,

-bs0d | www.allsyntax.com

Members Table (sql):



Registration Script:




Login script:




Page_header code:




Logout:







1  |  2  |  3  |  4  |  5  |  6  |  7  |  8  |  9  |  


Comments:

  mo
  Subject: "session logged_in is zero" Date: May 01 2007 at 5:47 pm    
I'm a PHP noob. I implemented the script and everything looks ok and works from a database standpoint but I do not think the session from the login is getting set. After login, I redirect to a page called usercp.php which I included the page header code in. I check the session[logged_ in] befor the "check cookie" and the session is set to 0.
  bs0d
  Subject: "Sessions" Date: May 06 2007 at 4:50 pm    

Make sure your session code to recognize members is in your "page header" code. Also that the code in your page header is executed to check login status before anything else.

You may need to bring this to the forums and start a topic, post some of your code and we can help you from there.

Thanks
  duece
  Subject: "Error for Register" Date: Jun 13 2007 at 6:08 am    
Got the following error when executing.
Parse error: syntax error, unexpected '`', expecting ')' in C:\wamp\www\ register.php on line 26

which corresponds to:

Code:
$junk = array('.' , ',' , '/' , '\' , '`' , ';' , '[' , ']' , '-', '*', '&', '^', '%', '$', '#', '@', '!', '~', '+', '(', ')', '|', '{', '}', '<', '>', '?', ':', '"', '=');


pasted right from the code for "register " in this post...
Please clarify
D
  duece
  Subject: "Error in Login.php" Date: Jun 14 2007 at 8:03 am    
I have looked over the code for quite a bit, can't figure it out.
Here is my error...
Warning: Cannot modify header information - headers already sent by (output started at C:\wamp\www\ MyLogin.php:6) in C:\wamp\www\ login.php on line 27

Warning: mysql_fetch_obj ect(): supplied argument is not a valid MySQL result resource in C:\wamp\www\ login.php on line 36
Login Failure: An error occured, please verify your username and password are correct.


Code for Login Below.
Thanks in advanced....

Code:

<?php
ob_start();
require_once(' ../www/connect. php');

if(isset($_SESS ION['username ']) && isset($_SESSION ['password']) ) {
//REDIRECT TO USERS PROFILE...
header("L ocation: ../www/temp.htm l");
} //end if logged in

//IF SUBMIT BUTTON PRESSED
if(isset($_POST ['submit'])) {

if(!$_POST['us ername']) die("Erro r: You must enter your username before logging in.");
if(!$_POST['pa ssword']) die("Erro r: You must enter your password before logging in.");


//set cookie if checked
if(!empty($_POS T['stay_in']) ) {
$joined =''.$_POST[' username'].'[ ]'.md5($_POST[ 'password']). '';
setcookie('log in_cookie', $joined, 2147483647, '/', '../www/MyPage .htm');
} //end if



//verify user...
$get_user = mysql_query(&q uot;SELECT * FROM `familymembers` WHERE username = '".$_POS T['username'] ."' AND

user_password = '".md5($ _POST['passwor d'])."' ");
$q = mysql_fetch_obj ect($get_user);
if(!$q) die("Logi n Failure: An error occured, please verify your username and password are correct." );

//set session variables
$_SESSION['log ged_in'] = 1;
$_SESSION['use rname'] = $_POST['userna me'];
$_SESSION['pas sword'] = $_POST['passwo rd'];
session_write_c lose();

header(". ./www/Mypage.ph p");

} else {
//show login form
?>
<form name="log in" method="p ost" action="& lt;?php $_SERVER['PHP_ SELF']; ?>"> ;
<table> <tr>
<td>Usern ame:<input type="tex t" id="usern ame" name="use rname"> ;</td>
</tr>
<tr>
<td>Passw ord:<input type="pas sword" id="passw ord" name="pas sword"> ;</td>
</tr>
<tr>
<td>Submi t: <input type="sub mit" value="Su bmit" name="sub mit" id="submi t">< ;/td>
</tr>
<tr>
<td>Remem ber? <input type="che ckbox" name="sta y_in[]" checked=" yes">& lt;/td>
</tr>
</table>< br /> </form> <?php
}//end else
?>

  dean
  Subject: ""duece&q uot;" Date: Jun 14 2007 at 1:06 pm    
Duece in answer to your question i had the same problem its to do with the "\" ; it messes up the code, if you view it in notepad++ you''ll see that nearer the end of that line it turns into a comment and therefore doesnt read the ");" ; the only way i found to fix it was by adding another "\" ; so it was '\\'. Wether or not this will still block them from using "\" ; is another matter.
  dean
  Subject: "oops" Date: Jun 14 2007 at 1:14 pm    
Oops! didn't realise you posted twice, that was in answer to you'r "register " question
  dean
  Subject: "Error login.php" Date: Jun 14 2007 at 1:14 pm    
In answer to your second question i couldnt see much wrong or different to my code the only thing i could think of was the header location maybe put the precise location of it I.E include the http:// other then that i dont know, im only a php noob myself. On another note i'd like to thank bs0d for creating this tutorial, it has been really helpful for me.
  bs0d
  Subject: "Discuss in Forums" Date: Jun 14 2007 at 11:32 pm    

If you have specific issues, please discuss them in the forums. To answer your question, as the tutorial states, you may have to use ob_start();< /b> as the first line of code on your page to eliminate the "headers already sent" error(s).
  Finest
  Subject: "logout.php" Date: Jun 22 2007 at 10:28 pm    
Ok i belive that i have the correct format for the logout.php script. At first i had the same 2 similar problems as duece and corrected based on your advice. The problem is not that when i hit the logout link i dont think that it logs out instead im am redirected to my home page which is not my index page. i also set a part of my page to echo the $user but that is blank.. before i loged in i said welcome guest but now i cant tell if its still working dut to the logout problem. please advise.. this is the code for the whole logout page.


<?
ob_start();
session_start( );
require_once($_ SERVER['DOCUME NT_ROOT'].'/d b_connect.php' );
require_once(' db_connect.php ');
//check cookie
if ($_SESSION['lo gged_in'] != 1 && isset($_COOKIE[ 'login_cookie '])) {
list($user, $pass) = explode('[]', $_COOKIE['logi n_cookie']); $qu = mysql_query(&q uot;SELECT `user_password` FROM `members` WHERE `username` = '".addsl ashes($user).& quot;'") ;
if (mysql_num_rows ($qu) == 1) {
$passw = mysql_fetch_obj ect($qu);
if ($passw->use r_password == $pass) {
$_SESSION['log ged_in'] = 1;
$_SESSION['use rname'] = $user;
$_SESSION['pas sword'] = $pass;
}
}
}

if(!isset($_SES SION['username ']) && !isset($_SESSIO N['password'] )) {
$_SESSION['log ged_in'] = 0;
$user = "Guest&q uot;;
}
?>

<?php



/**

* Page which logs a user out of the system. They are then redirected

* back to the forum listing page.

*

* @package freeBulletin

*/




$_SESSION['log ged_in'] = 0;

setcookie('log in_cookie', "", time() - 60, '/', '.erotiqgarden .com');

session_destroy ();
header("L ocation: http://www.erot iqgarden.com&q uot;);
?>
  umbrae
  Subject: "Integrate" Date: Dec 21 2007 at 5:22 am    
Hi!

Thank you for your excellent tutorial. This is just what I've been looking for. I have a quick question though: is it possible to integrate this with your Comments Script? Kinda like this site~

Thanks in advance.
  bs0d
  Subject: "RE: Integrate" Date: Dec 24 2007 at 1:04 am    

Yes, you would just use the session variables to identify users in the members script in the comments script. It would be that easy.
  rookie
  Subject: "need help with logout function" Date: Nov 08 2008 at 4:08 am    
my error is as follows

Warning: session_destroy () [function.sessi on-destroy]: Trying to destroy uninitialized session in /home/wemwngdt/ public_html/log out.php on line 6

Warning: Cannot modify header information - headers already sent by (output started at /home/wemwngdt/ public_html/log out.php:6) in /home/wemwngdt/ public_html/log out.php on line 7

ive created a link on my member page to logout with the following code:

<?
$_SESSION['log ged_in'] = 0;

setcookie('log in_cookie', "", time() - 60, '/', '.index.htm') ;

session_destroy ();
header("L ocation: index.htm" ;);
?>

i also have page_header.php loading on member page. with the following:

<?
ob_start();
session_start() ;
require_once($_ SERVER['DOCUME NT_ROOT'].'/o pendb.php');
//check cookie
if ($_SESSION['lo gged_in'] != 1 && isset($_COOKIE[ 'login_cookie '])) {
list($user, $pass) = explode('[]', $_COOKIE['logi n_cookie']); $qu = mysql_query(&q uot;SELECT `user_password` FROM `members` WHERE `username` = '".addsl ashes($user).& quot;'") ;
if (mysql_num_rows ($qu) == 1) {
$passw = mysql_fetch_obj ect($qu);
if ($passw->use r_password == $pass) {
$_SESSION['log ged_in'] = 1;
$_SESSION['use rname'] = $user;
$_SESSION['pas sword'] = $pass;
}
}
}

if(!isset($_SES SION['username ']) && !isset($_SESSIO N['password'] )) {
$_SESSION['log ged_in'] = 0;
$user = "Guest&q uot;;
}
?>
and the loginpage with the following:

<?PHP include('page_ header.php'); ?>

<?
ob_start();
require_once($_ SERVER['DOCUME NT_ROOT'].'/o pendb.php');

if(isset($_SESS ION['username ']) && isset($_SESSION ['password']) ) {
//REDIRECT TO USERS PROFILE...
header("L ocation: welcome.php&qu ot;);
} //end if logged in

//IF SUBMIT BUTTON PRESSED
if(isset($_POST ['submit'])) {

if(!$_POST['us ername']) die("Erro r: You must enter your username before logging in.");
if(!$_POST['pa ssword']) die("Erro r: You must enter your password before logging in.");

//set cookie if checked
if(!empty($_POS T['stay_in']) ) {
$joined =''.$_POST[' username'].'[ ]'.md5($_POST[ 'password']). '';
setcookie('log in_cookie', $joined, 2147483647, '/', '.welcome.php ');
} //end if

//verify user...
$get_user = mysql_query(&q uot;SELECT * FROM `members` WHERE username = '".$_POS T['username'] ."' AND

user_password = '".md5($ _POST['passwor d'])."' ");
$q = mysql_fetch_obj ect($get_user);
if(!$q) die("Logi n Failure: An error occured, please verify your username and password are correct." );

//set session variables
$_SESSION['log ged_in'] = 1;
$_SESSION['use rname'] = $_POST['userna me'];
$_SESSION['pas sword'] = $_POST['passwo rd'];
session_write_c lose();

header("L ocation: welcome.php&qu ot;);

} else {
//show login form
?>
<form name="log in" method="p ost" action="& lt;? $_SERVER['PHP_ SELF']; ?>"> ;
<table> <tr>
<td>Usern ame:<input type="tex t" id="usern ame" name="use rname"> ;</td>
</tr>
<tr>
<td>Passw ord:<input type="pas sword" id="passw ord" name="pas sword"> ;</td>
</tr>
<tr>
<td>Submi t: <input type="sub mit" value="Su bmit" name="sub mit" id="submi t">< ;/td>
</tr>
<tr>
<td>Remem ber? <input type="che ckbox" name="sta y_in[]" checked=" yes">& lt;/td>
</tr>
</table>< br /> </form> <?
}//end else
?>



Sorry for the long post, everything seems to be working for me except for the logout issue help would be great thanks.

  branic729
  Subject: "upload in 000webhost.com" Date: May 30 2010 at 8:14 pm    
Hi, very nice script! I tried uploading the whole script and my files to my host at 000webhost.com with domain http://batchtu torials.netau.n et. I got some trouble with db_connect.php. It gives an error that it could not connect, etc. I hope someone can still contact me, because I saw that the most comments were from 2007. And by the way, I'm a starter at PHP :)
  zkniebs
  Subject: "branic729" Date: Jul 19 2010 at 1:55 am    
hey branic729, I'm also a starter at PHP and I use 000webhost.com too (though I use their free hosting). I do not know if anyone answered any of your questions, but I used several tutorials, including this one to teach myself and eventually put together a user system like this one. If you are still looking for some help you can email me at zkniebs@hotmail .com
  bs0d
  Subject: "000webhost" Date: Jul 20 2010 at 2:32 am    

I'm unfamiliar with working on that host/setup. A simple email to the server admin should give you the answer. It could be the reference to the host in the db_connect file.
You Must be logged in or a member to comment.


Tutorial Stats

Tutorial Stats

330,939 Views
41 Total Comments
4.8 Rating of 5 (5 Votes)

Options

Tutorial Options

· Login to Rate This Article
· Login to Post a Comment
· Read more by this author
Digg This Article! Del.icio.us: Bookmark This Article Reddit: Bookmark This Article BlinkList: Blink This Article! YahooMyWeb BlogMarks: Add This Mark! Furl: Save This Article Spurl: Mark This Article

Articles

Related    

· Simple PHP Tutorial
· One File Website
· Pagination with PHP
· Building a Comments Script
· Variable Scope



"AllSyntax.com" Copyright © 2002-2017; All rights lefted, all lefts righted.
Privacy Policy  |  Internet Rank