Click to See Complete Forum and Search --> : login problems
gilgalbiblewhee
Apr 3rd, 2010, 10:13 PM
I'm having logging problems. It keeps logging out when I click on the url and entering. These are my pages. First it's the index page where the rest are include files found in it:
index.php:
<?php
//twotexts
ob_start();
session_start();//the only thing related to the login
//...
login page: index.php
<?php
ob_start();
include("dbconnection.php");
?>
<div style="float: left; width: 100%; margin: 0px 0px 0px 0px; background-color: #7C7C7C; border: 1px solid #A5A498; border-width: 1px 1px 0px 1px;">
<span style="float: left; padding: 2px 10px 0px 12px; color: #FFFFFF; font-family: arial; font-weight:bold; font-size: 13px;">Login</span>
</div>
<div style="float: left; width: 100%; height: 120px; background-color: #B4B3A9; border: 1px solid #A5A498; margin: 0px 0px 0px 0px; overflow-x: hidden; overflow-y: auto;">
<?php
function login(){
?>
<table border="0">
<tr>
<td>Administrator:</td><td><input type="checkbox" id="adminid" name="admin" style="float: left; border: 1px solid #7C7C7C; background-color: #7C7C7C;" value="no" onClick="if(this.value=='no'){this.value='yes'; document.getElementById('register').style.display = 'none';} else{this.value='no';document.getElementById('register').style.display = 'block';};" /></td>
</tr>
<tr>
<td>Username:</td>
<td><input type="text" name="<?php //vb_login_username?>username" id="username" style="float: left; border: 1px solid #7C7C7C; font: 9px verdana, geneva, lucida, 'lucida grande', arial, helvetica, sans-serif; width: 100px; height: 15px;" value="User Name" onBlur="if (this.value == '') this.value = 'User Name';" onFocus="if (this.value == 'User Name') this.value = '';" /></td>
</tr>
<tr>
<td>Password:</td><td><input type="password" style="float: left; border: 1px solid #7C7C7C; font: 9pt verdana, geneva, lucida, 'lucida grande', arial, helvetica, sans-serif; width: 100px; height: 15px;" <?php //name="pass"?> name="<?php //vb_login_username?>pass" id="pass" /></td></tr>
<tr>
<td><a id="register" href="login/register.php" style="float: left; display: block; background-color: #7C7C7C; text-align: left; padding: 0px 0px 0px 5px; width: 80px; height: 20px; text-decoration: none; color: #ffffff; border: 1px solid #7C7C7C; font-weight: bold;" onMouseOver="this.style.backgroundColor='#B4B3A9'" onMouseOut="this.style.backgroundColor='#7C7C7C'">Register</a></td><td align="right"><input type="submit" style="float: left; border: 1px solid #7C7C7C; background-color: #7C7C7C; color: #ffffff; font: 9pt verdana, geneva, lucida, 'lucida grande', arial, helvetica, sans-serif; font-weight: bold; width: 100px; height: 20px;" name="submit" onMouseOver="this.style.backgroundColor='#B4B3A9'" onMouseOut="this.style.backgroundColor='#7C7C7C'" value="Login" /></td>
</tr>
</table>
<?php
}
//Checks if there is a login cookie
if(isset($_COOKIE['ID_my_site'])){ //if there is, it logs you in and directs you to the members page
$myusername = $_COOKIE['ID_my_site'];
$pass = $_COOKIE['Key_my_site'];
$admin = $_COOKIE['Admin_my_site'];
$user = $_COOKIE['User_my_site'];
$sql = "SELECT * FROM ";
if($admin=="yes"){
$sql .= $dbTable2;
}else{
$sql .= $dbTable;
}
$sql .= " WHERE username = '".mysql_real_escape_string($myusername)."'";
$check = mysql_query($sql)or die(mysql_error());
while($info = mysql_fetch_array( $check )){
if ($pass != $info['password']){
}else{
//print("Welcome ".$myusername."! <br />Visit your <a href=\"login/member.php\">member's stat</a> <br /><a href=\"login/logout.php\">Logout</a>");
//header("Location: login/member.php");
//header("Location: ");
}
}
}
//if the login form is submitted
if (isset($_POST['submit'])){ // if form has been submitted
if(!$_POST['username'] | !$_POST['pass']) {// makes sure they filled it in
//die('You did not fill in a required field.');
print('You did not fill in a required field.');
}// checks it against the database
if (!get_magic_quotes_gpc()){
$_POST['email'] = addslashes($_POST['email']);
}
$sql = "SELECT * FROM ";
if($admin=="yes"){
$sql .= $dbTable2;
}else{
$sql .= $dbTable;
}
$sql .= " WHERE username = '".$_POST['username']."'";
$check = mysql_query($sql)or die(mysql_error());
//Gives error if user dosen't exist
$check2 = mysql_num_rows($check);
if ($check2 == 0) {
//die('That user does not exist in our database. <a href=login/register.php>Click Here to Register</a>');
print('That user does not exist in our database.');
login();
}
while($info = mysql_fetch_array( $check )){
$_POST['pass'] = stripslashes($_POST['pass']);
$info['password'] = stripslashes($info['password']);
$_POST['pass'] = md5($_POST['pass']);
//gives error if the password is wrong
if ($_POST['pass'] != $info['password']){
//die('Incorrect password, please try again.');
print('Incorrect password, please try again.');
login();
}else{
// if login is ok then we add a cookie
$_POST['username'] = stripslashes($_POST['username']);
$hour = time() + 3600;
setcookie(ID_my_site, $_POST['username'], $hour);
setcookie(Key_my_site, $_POST['pass'], $hour);
if($_POST["admin"]=="yes"){
setcookie(Admin_my_site, $_POST['admin'], $hour);
print("<span style=\"float: left; text-align: left; padding: 5px 5px 5px 5px;\">Welcome ".$myusername."! <br />Visit your <a style=\"text-decoration: none;\" onmouseover=\"this.style.textDecoration='underline';\" onmouseout=\"this.style.textDecoration='none';\" href=\"login/member.php\">member's stat</a> <br /><a style=\"text-decoration: none;\" href=\"login/logout.php\" onmouseover=\"this.style.textDecoration='underline';\" onmouseout=\"this.style.textDecoration='none';\" >Logout</a></span>");
}else{
setcookie(User_my_site, $_POST['admin'], $hour);
print("<span style=\"float: left; text-align: left; padding: 5px 5px 5px 5px;\">Welcome <span id=\"myusername\">".$myusername."</span>! <br />Visit your <a style=\"text-decoration: none;\" href=\"login/member.php\" onmouseover=\"this.style.textDecoration='underline';\" onmouseout=\"this.style.textDecoration='none';\" >member's stat</a> <br /><a style=\"text-decoration: none;\" href=\"login/logout.php\" onmouseover=\"this.style.textDecoration='underline';\" onmouseout=\"this.style.textDecoration='none';\" >Logout</a></span>");
}
//then redirect them to the members area
//header("Location: login/member.php");
//print("Welcome".$username);
//header("Location: login/member.php");
//header("Location: ");
}
}
}else{
// if they are not logged in
login();
}
?>
</div>
logout.php
<?php
ob_start();
include("dbconnection.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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Logout</title>
</head>
<body>
<?php
$past = time() - 100;
//this makes the time in the past to destroy the cookie
setcookie(ID_my_site, gone, $past);
setcookie(Key_my_site, gone, $past);
setcookie(Admin_my_site, gone, $past);
header("Location: ../index.php");
?>
</body>
</html>
gilgalbiblewhee
Apr 3rd, 2010, 10:14 PM
register.php
<?php
include("dbconnection.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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Register</title>
</head>
<body bgcolor="#505050" text="#000000" link="#363636" vlink="#363636" alink="#d5ae83">
<div id="master" style="width: 1240px; height: 780px; margin: 0px auto; overflow: hidden; text-align: center;">
<div id="logo" style="float: left; margin: 0px; border: none; background-color: #ECECEC; width: 100%; height: 120px; padding: 0px 5px 0px 0px;">
<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" width="655" height="120" id="wheelofgod2" align="middle">
<param name="allowScriptAccess" value="sameDomain" />
<param name="movie" value="flashclips/wheelofgod2.swf" />
<param name="quality" value="high" />
<param name="bgcolor" value="#ECECEC" />
<embed src="../../flashclips/wheelofgod2.swf" quality="high" bgcolor="#ECECEC" width="655" height="120" name="wheelofgod" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />
</object>
</div>
<div id="leftbar" style="float: left; width: 200px; height: 1200px; margin: 5px 0px 0px 0px; background-color: #505050;">
<?php //$Colors = Array("FF0000", "0000FF", "009900", "FF9900", "660099", "00FFFF");
include("../../getFiles/links.php");
include("../../getFiles/updates.php");?>
</div>
<div id="main" style="float: left; margin: 5px 5px 5px 5px; background-color: #D2C5A0; border: 1px solid #B5A26F; width: 810px; height: 640px; padding: 5px 5px 5px 5px; overflow-y: auto;">
<?php
//This code runs if the form has been submitted
if (isset($_POST['submit'])){//This makes sure they did not leave any fields blank
if (!$_POST['username'] | !$_POST['pass'] | !$_POST['pass2']){
//die('You did not complete all of the required fields');
print('You did not complete all of the required fields');
}
// checks if the username is in use
if (!get_magic_quotes_gpc()){
$_POST['username'] = addslashes($_POST['username']);
}
$usercheck = $_POST['username'];
$check = mysql_query("SELECT username FROM ".$dbTable." WHERE username = '$usercheck'") or die(mysql_error());
$check2 = mysql_num_rows($check);
//if the name exists it gives an error
if ($check2 != 0) {
//die('Sorry, the username '.$_POST['username'].' is already in use.');
print('Sorry, the username '.$_POST['username'].' is already in use.');
}
// this makes sure both passwords entered match
if ($_POST['pass'] != $_POST['pass2']) {
//die('Your passwords did not match. ');
print('Your passwords did not match. ');
}
// here we encrypt the password and add slashes if needed
$_POST['pass'] = md5($_POST['pass']);
if (!get_magic_quotes_gpc()) {
$_POST['pass'] = addslashes($_POST['pass']);
$_POST['username'] = addslashes($_POST['username']);
}
// now we insert it into the database
$insert = "INSERT INTO ".$dbTable." (
...// ...
)";
//echo $insert;
//$add_member = mysql_query($insert);
?>
<div style="float: left; width: 100%; margin: 5px 0px 0px 0px; background: #7C7C7C; border: 1px solid #A5A498; border-width: 1px 1px 0px 1px;">
<span style="float: left; padding: 2px 10px 0px 12px; color: #FFFFFF; font-family: arial; font-weight:bold; font-size: 13px">Registered</span>
</div>
<p>Thank you <?php echo "<span style=\"font-weight: bold; font-style: italic;\">".$_POST['username']."</span>"; ?>, you have registered - you may now <a href="../index.php">login</a>.</p>
<?php
}else{
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<table border="0">
<tr><td>*Username:</td><td><input type="text" name="username" style="float: left; border: 1px solid #7C7C7C; font: 9pt verdana, geneva, lucida, 'lucida grande', arial, helvetica, sans-serif; width: 200px; height: 15px;" maxlength="60" /></td></tr>
<tr><td>*Password (10 characters):</td><td><input type="password" name="pass" style="float: left; border: 1px solid #7C7C7C; font: 9pt verdana, geneva, lucida, 'lucida grande', arial, helvetica, sans-serif; width: 200px; height: 15px;" maxlength="10" /></td></tr>
<tr><td>*Confirm Password (10 characters):</td><td><input type="password" name="pass2" style="float: left; border: 1px solid #7C7C7C; font: 9pt verdana, geneva, lucida, 'lucida grande', arial, helvetica, sans-serif; width: 200px; height: 15px;" maxlength="10" /></td></tr>
<tr>
<td>*First Name:</td>
<td><input name="fname" size="29" maxlength="30" style="float: left; border: 1px solid #7C7C7C; font: 9pt verdana, geneva, lucida, 'lucida grande', arial, helvetica, sans-serif; width: 200px; height: 15px;" /></td>
</tr>
<tr>
<td>*Last Name:</td>
<td><input name="lname" size="29" maxlength="40" style="float: left; border: 1px solid #7C7C7C; font: 9pt verdana, geneva, lucida, 'lucida grande', arial, helvetica, sans-serif; width: 200px; height: 15px;" /></td>
</tr>
<tr>
<td>*Your e-mail:</td>
<td><input name="email" size="29" maxlength="40" style="float: left; border: 1px solid #7C7C7C; font: 9pt verdana, geneva, lucida, 'lucida grande', arial, helvetica, sans-serif; width: 200px; height: 15px;" /></td>
</tr>
<tr>
<td>Your URL:</td>
<td><input name="url" size="29" maxlength="100" style="float: left; border: 1px solid #7C7C7C; font: 9pt verdana, geneva, lucida, 'lucida grande', arial, helvetica, sans-serif; width: 200px; height: 15px;" /></td>
</tr>
<tr>
<td>Additional URL:</td>
<td><input name="addnlurl" size="29" maxlength="100" style="float: left; border: 1px solid #7C7C7C; font: 9pt verdana, geneva, lucida, 'lucida grande', arial, helvetica, sans-serif; width: 200px; height: 15px;" /></td>
</tr>
<tr>
<td>
<input type="submit" style="float: left; border: 1px solid #7C7C7C; background-color: #7C7C7C; color: #ffffff; font: 9pt verdana, geneva, lucida, 'lucida grande', arial, helvetica, sans-serif; font-weight: bold; width: 200px; height: 20px; margin: 5px 5px 5px 5px;" onMouseOver="this.style.backgroundColor='#B4B3A9'" onMouseOut="this.style.backgroundColor='#7C7C7C'" name="submit" value="Register" />
</td>
<td>
<input type="reset" style="float: left; border: 1px solid #7C7C7C; background-color: #7C7C7C; color: #ffffff; font: 9pt verdana, geneva, lucida, 'lucida grande', arial, helvetica, sans-serif; font-weight: bold; width: 200px; height: 20px; margin: 5px 5px 5px 5px;" onMouseOver="this.style.backgroundColor='#B4B3A9'" onMouseOut="this.style.backgroundColor='#7C7C7C'" value="Reset" name="reset" />
</td>
</tr>
</table>
</form>
<?php
}
?>
</div>
<div id="rightbar" style="float: left; width: 200px; height: 1200px; margin: 5px 0px 0px 5px; background-color: #505050;">
<?php
include("index.php");
//include("../../getFiles/whattodo.php");
include("../../getFiles/posts.php");
?>
</div>
</div>
</div>
</body>
</html>
gilgalbiblewhee
Apr 3rd, 2010, 10:14 PM
member.php
<?php
ob_start();
include("dbconnection.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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Members Page</title>
</head>
<body bgcolor="#505050" text="#000000" link="#363636" vlink="#363636" alink="#d5ae83">
<div id="master" style="width: 1240px; height: 780px; margin: 0px auto; overflow: hidden; text-align: center;">
<div id="logo" style="float: left; margin: 0px; border: none; background-color: #ECECEC; width: 100%; height: 120px; padding: 0px 5px 0px 0px;">
<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" width="655" height="120" id="wheelofgod2" align="middle">
<param name="allowScriptAccess" value="sameDomain" />
<param name="movie" value="flashclips/wheelofgod2.swf" />
<param name="quality" value="high" />
<param name="bgcolor" value="#ECECEC" />
<embed src="../../flashclips/wheelofgod2.swf" quality="high" bgcolor="#ECECEC" width="655" height="120" name="wheelofgod" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />
</object>
</div>
<div id="leftbar" style="float: left; width: 200px; height: 1200px; margin: 5px 0px 0px 0px; background-color: #505050;">
<?php //$Colors = Array("FF0000", "0000FF", "009900", "FF9900", "660099", "00FFFF");
include("../../getFiles/links.php"); ?>
</div>
<div id="main" style="float: left; margin: 5px 5px 5px 5px; background-color: #D2C5A0; border: 1px solid #B5A26F; width: 810px; height: 640px; padding: 5px 5px 5px 5px; overflow-y: auto;">
<?php
//checks cookies to make sure they are logged in
if(isset($_COOKIE['ID_my_site'])){
$myusername = $_COOKIE['ID_my_site'];
$pass = $_COOKIE['Key_my_site'];
$admin = $_COOKIE['Admin_my_site'];
$user = $_COOKIE['User_my_site'];
$sql = "SELECT * FROM ";
if($admin=="yes"){
$sql .= $dbTable2;
}else{
$sql .= $dbTable;
}
$sql .= " WHERE username = '".mysql_real_escape_string($myusername)."'";
//echo $sql;
$check = mysql_query($sql)or die(mysql_error());
while($info = mysql_fetch_array( $check )){//if the cookie has the wrong password, they are taken to the login page
if ($pass != $info['password']){
header("Location: ../index.php");
}else{//otherwise they are shown the admin area
?>
<div style="float: left; width: 100%; margin: 5px 0px 0px 0px; background: #7C7C7C; border: 1px solid #A5A498; border-width: 1px 1px 0px 1px;">
<span style="float: left; padding: 2px 10px 0px 12px; color: #FFFFFF; font-family: arial; font-weight:bold; font-style: italic; font-size: 13px"><?php echo mysql_real_escape_string(strtoupper($myusername)); ?>'s Member Stat.</span>
</div>
<?php
include("memberStat.php");
echo "<a href=\"logout.php\">Logout</a>";
}
}
}else{//if the cookie does not exist, they are taken to the login screen
header("Location: ../index.php");
}
?>
</div>
<div id="rightbar" style="float: left; width: 200px; height: 1200px; margin: 5px 0px 0px 5px; background-color: #505050;">
<?php
include("index.php");
//include("../../getFiles/whattodo.php");
include("../../getFiles/updates.php");
include("../../getFiles/posts.php");
?>
</div>
</div>
</body>
</html>
kows
Apr 4th, 2010, 12:05 AM
cookies are a type of header; this means that they must be sent to the browser before any output is sent. you're sending output, and then trying to set cookies later on in your login script. move your login logic to the top of the script, and echo stuff later on. a separation of logic and presentation is always good practice, anyway. oh yeah, and it looks like you're trying to use constants for the name of your cookies (in your setcookie() calls), but the first parameter of this function should be a string. if this wasn't a modification you made accidentally when posting, your cookies would never get set properly because those constants don't exist.
also, I'd recommend not using addslashes() and using mysql_real_escape_string() instead. I do see that you've used the latter at least somewhere in your script, but it's best to pretty much never use the former, I'd say -- at least when you're dealing with raw data that will be used in a database situation.
I might also suggest that you only use cookies to store user information, and use sessions to store any temporary login information (like whether or not that person is an administrator -- cookies can be modified, after all). sessions will persist for 20 minutes by default (which can be changed), and so generally I store a cookie of the user's username and encrypted password to act as a "remember me" function.
and lastly, I would suggest that for development you run PHP in a strict environment so that you can easily see any warnings and errors that might be thrown at you -- to not catch some of these would seem like you're running on a production environment.
gilgalbiblewhee
Apr 6th, 2010, 01:04 PM
cookies are a type of header; this means that they must be sent to the browser before any output is sent. you're sending output, and then trying to set cookies later on in your login script. move your login logic to the top of the script, and echo stuff later on. a separation of logic and presentation is always good practice, anyway. oh yeah, and it looks like you're trying to use constants for the name of your cookies (in your setcookie() calls), but the first parameter of this function should be a string. if this wasn't a modification you made accidentally when posting, your cookies would never get set properly because those constants don't exist.
also, I'd recommend not using addslashes() and using mysql_real_escape_string() instead. I do see that you've used the latter at least somewhere in your script, but it's best to pretty much never use the former, I'd say -- at least when you're dealing with raw data that will be used in a database situation.
I might also suggest that you only use cookies to store user information, and use sessions to store any temporary login information (like whether or not that person is an administrator -- cookies can be modified, after all). sessions will persist for 20 minutes by default (which can be changed), and so generally I store a cookie of the user's username and encrypted password to act as a "remember me" function.
and lastly, I would suggest that for development you run PHP in a strict environment so that you can easily see any warnings and errors that might be thrown at you -- to not catch some of these would seem like you're running on a production environment.
Ok can you give me an example of how the login should be coded? Is there a good tutorial that you would recommend?
I got this tutorial from:
http://php.about.com/od/finishedphp1/ss/php_login_code_2.htm
kows
Apr 6th, 2010, 07:09 PM
well, my post goes through a few details of how you might go about fixing your current code.
penagate
Apr 6th, 2010, 11:17 PM
Please read kows' post and take his suggestions seriously. This will do more to improve your PHP skill than copying from an example or tutorial.
gilgalbiblewhee
Apr 7th, 2010, 08:16 AM
Please read kows' post and take his suggestions seriously. This will do more to improve your PHP skill than copying from an example or tutorial.
I appreciate what he's saying but I don't know in what order to set things up. I have headers within if statements. Are those correct?
It's been a few weeks I've been struggling in this.
kows
Apr 7th, 2010, 01:21 PM
I only said that you could not send headers after you've sent output to the browser. every time you echo or print something, or display HTML, you're sending output to the browser. if you wish to send cookies on a page, your logic for deciding whether or not these cookies should be set (or destroyed) must be done before you send any output to the browser. in your logout script, for example, you start outputting your HTML and then you try to destroy your cookies by calling setcookie() with a time stamp in the past -- normally, this would throw some sort of error that told you that you could not send headers after output is sent ...
... and then, I realized you were using output buffering (ob_start()). I would firmly suggest against using output buffering unless you actually have a reason to use it (which you don't in this case). it promotes improper coding by letting you get away with certain things (and that may seem like it makes things convenient for you, but I would argue against that). properly written and formatted scripts will be easier to maintain in the future -- in this case, properly written/formatted would mean that the majority of your login/logout logic should happen at the beginning of all of your scripts (which is what I mentioned before and above).
so, to answer your question -- headers can be called within IF statements, yes.
but, there are still other issues with your script that I've discussed in my previous post; for example, this snippet of code from index.php:
setcookie(ID_my_site, $_POST['username'], $hour);
setcookie(Key_my_site, $_POST['pass'], $hour);
if($_POST["admin"]=="yes"){
setcookie(Admin_my_site, $_POST['admin'], $hour);
print("<span style=\"float: left; text-align: left; padding: 5px 5px 5px 5px;\">Welcome ".$myusername."! <br />Visit your <a style=\"text-decoration: none;\" onmouseover=\"this.style.textDecoration='underline';\" onmouseout=\"this.style.textDecoration='none';\" href=\"login/member.php\">member's stat</a> <br /><a style=\"text-decoration: none;\" href=\"login/logout.php\" onmouseover=\"this.style.textDecoration='underline';\" onmouseout=\"this.style.textDecoration='none';\" >Logout</a></span>");
}else{
setcookie(User_my_site, $_POST['admin'], $hour);
print("<span style=\"float: left; text-align: left; padding: 5px 5px 5px 5px;\">Welcome <span id=\"myusername\">".$myusername."</span>! <br />Visit your <a style=\"text-decoration: none;\" href=\"login/member.php\" onmouseover=\"this.style.textDecoration='underline';\" onmouseout=\"this.style.textDecoration='none';\" >member's stat</a> <br /><a style=\"text-decoration: none;\" href=\"login/logout.php\" onmouseover=\"this.style.textDecoration='underline';\" onmouseout=\"this.style.textDecoration='none';\" >Logout</a></span>");
} ignoring the horrendous HTML (you shouldn't use echo/print to emit HTML), you're calling setcookie() four times and you're using constants to define the names of these cookies. however, the constants don't exist (and I'm not even sure you know what a constant is) and when PHP looks for these constants they will be null, which means you're setting cookies with null names. this means there is no possible way for you to reference them, so that isn't very helpful. briefly, here is the extremely simple difference between how to call or use constants, variables, strings, and functions:
CONSTANT
$variable
"string"
'string'
function()
so, in your code, you can see that you're trying to use a constant to define a cookie name (ID_my_site), but you need to use strings:
setcookie("my_cookie_name", "my_cookie_value", time() + 3600);
then, I could reference $_COOKIE['my_cookie_name'] to get the value "my_cookie_value" after a full reload of the current page (cookies don't take affect until you've loaded a new page).
and then, there's the thing I mentioned about sessions. sessions would be better than cookies in your case (in my opinion) simply because you're setting a cookie for just an hour. cookies are generally used to store long term information -- not short term. sessions will persist for up to 20 minutes by default and will store any data on the server rather than the client (which is good for information that may need a bit more security), and a user doesn't need anything enabled in their browser to make sessions work. I would suggest that you read up on them here (http://ca3.php.net/manual/en/session.examples.basic.php) through the simple example.
however, as a final note, if you are not really understanding PHP and this tutorial/script is your first step into it, I would highly suggest you take a step back and look into some beginner tutorials -- perhaps the ones from W3Schools would be a good start.
and don't be afraid to ask questions if you don't understand anything I just wrote!
gilgalbiblewhee
Apr 10th, 2010, 03:14 AM
I understand php. I've been working on it for at least 3 years now. That part of the tutorial didn't make sense where the quotes "" should appear but I left it there anyways for the time being.
But the login is new to me.
So I blocked the ob_start(). The session_start() stays in the main index file. The code below is the include file for logging in.
I added quotes setcookie("ID_my_site"....
But the rest I'm not sure how to put in order. There is so many nested if statements that I'm afraid I could ruin the code if I were to play around.
Do you mean this should be set in the beginning:
//gives error if the password is wrong
if ($_POST['pass'] != $info['password']){
//die('Incorrect password, please try again.');
print('Incorrect password, please try again.');
login();
}else{
// if login is ok then we add a cookie
$_POST['username'] = stripslashes($_POST['username']);
$hour = time() + 3600;
setcookie("ID_my_site", $_POST['username'], $hour);
setcookie("Key_my_site", $_POST['pass'], $hour);...?
My code updated:
<?php
//ob_start();
include("dbconnection.php");
function login(){
?>
<table border="0">
<tr>
<td>Administrator:</td><td><input type="checkbox" id="adminid" name="admin" style="float: left; border: 1px solid #7C7C7C; background-color: #7C7C7C;" value="no" onClick="if(this.value=='no'){this.value='yes'; document.getElementById('register').style.display = 'none';} else{this.value='no';document.getElementById('register').style.display = 'block';};" /></td>
</tr>
<tr>
<td>Username:</td>
<td><input type="text" name="<?php //vb_login_username?>username" id="username" style="float: left; border: 1px solid #7C7C7C; font: 9px verdana, geneva, lucida, 'lucida grande', arial, helvetica, sans-serif; width: 100px; height: 15px;" value="User Name" onBlur="if (this.value == '') this.value = 'User Name';" onFocus="if (this.value == 'User Name') this.value = '';" /></td>
</tr>
<tr>
<td>Password:</td><td><input type="password" style="float: left; border: 1px solid #7C7C7C; font: 9pt verdana, geneva, lucida, 'lucida grande', arial, helvetica, sans-serif; width: 100px; height: 15px;" <?php //name="pass"?> name="<?php //vb_login_username?>pass" id="pass" /></td></tr>
<tr>
<td><a id="register" href="login/register.php" style="float: left; display: block; background-color: #7C7C7C; text-align: left; padding: 0px 0px 0px 5px; width: 80px; height: 20px; text-decoration: none; color: #ffffff; border: 1px solid #7C7C7C; font-weight: bold;" onMouseOver="this.style.backgroundColor='#B4B3A9'" onMouseOut="this.style.backgroundColor='#7C7C7C'">Register</a></td><td align="right"><input type="submit" style="float: left; border: 1px solid #7C7C7C; background-color: #7C7C7C; color: #ffffff; font: 9pt verdana, geneva, lucida, 'lucida grande', arial, helvetica, sans-serif; font-weight: bold; width: 100px; height: 20px;" name="submit" onMouseOver="this.style.backgroundColor='#B4B3A9'" onMouseOut="this.style.backgroundColor='#7C7C7C'" value="Login" /></td>
</tr>
</table>
<?php
}
?>
<div style="float: left; width: 100%; margin: 0px 0px 0px 0px; background-color: #7C7C7C; border: 1px solid #A5A498; border-width: 1px 1px 0px 1px;">
<span style="float: left; padding: 2px 10px 0px 12px; color: #FFFFFF; font-family: arial; font-weight:bold; font-size: 13px;">Login</span>
</div>
<div style="float: left; width: 100%; height: 120px; background-color: #B4B3A9; border: 1px solid #A5A498; margin: 0px 0px 0px 0px; overflow-x: hidden; overflow-y: auto;">
<?php
//Checks if there is a login cookie
if(isset($_COOKIE['ID_my_site'])){ //if there is, it logs you in and directs you to the members page
$myusername = $_COOKIE['ID_my_site'];
$pass = $_COOKIE['Key_my_site'];
$admin = $_COOKIE['Admin_my_site'];
$user = $_COOKIE['User_my_site'];
$sql = "SELECT * FROM ";
if($admin=="yes"){
$sql .= $dbTable2;
}else{
$sql .= $dbTable;
}
$sql .= " WHERE username = '".mysql_real_escape_string($myusername)."'";
$check = mysql_query($sql)or die(mysql_error());
while($info = mysql_fetch_array( $check )){
if ($pass != $info['password']){
}else{
//print("Welcome ".$myusername."! <br />Visit your <a href=\"login/member.php\">member's stat</a> <br /><a href=\"login/logout.php\">Logout</a>");
//header("Location: login/member.php");
//header("Location: ");
}
}
}
//if the login form is submitted
if (isset($_POST['submit'])){ // if form has been submitted
if(!$_POST['username'] || !$_POST['pass']) {// makes sure they filled it in
//die('You did not fill in a required field.');
print('You did not fill in a required field.');
}// checks it against the database
if (!get_magic_quotes_gpc()){
$_POST['email'] = addslashes($_POST['email']);
}
$sql = "SELECT * FROM ";
if($admin=="yes"){
$sql .= $dbTable2;
}else{
$sql .= $dbTable;
}
$sql .= " WHERE username = '".$_POST['username']."'";
$check = mysql_query($sql)or die(mysql_error());
//Gives error if user dosen't exist
$check2 = mysql_num_rows($check);
if ($check2 == 0) {
//die('That user does not exist in our database. <a href=login/register.php>Click Here to Register</a>');
print('That user does not exist in our database.');
login();
}
while($info = mysql_fetch_array( $check )){
$_POST['pass'] = stripslashes($_POST['pass']);
$info['password'] = stripslashes($info['password']);
$_POST['pass'] = md5($_POST['pass']);
//gives error if the password is wrong
if ($_POST['pass'] != $info['password']){
//die('Incorrect password, please try again.');
print('Incorrect password, please try again.');
login();
}else{
// if login is ok then we add a cookie
$_POST['username'] = stripslashes($_POST['username']);
$hour = time() + 3600;
setcookie("ID_my_site", $_POST['username'], $hour);
setcookie("Key_my_site", $_POST['pass'], $hour);
if($_POST["admin"]=="yes"){
setcookie("Admin_my_site", $_POST['admin'], $hour);
print("<span style=\"float: left; text-align: left; padding: 5px 5px 5px 5px;\">Welcome ".$myusername."! <br />Visit your <a style=\"text-decoration: none;\" onmouseover=\"this.style.textDecoration='underline';\" onmouseout=\"this.style.textDecoration='none';\" href=\"login/member.php\">member's stat</a> <br /><a style=\"text-decoration: none;\" href=\"login/logout.php\" onmouseover=\"this.style.textDecoration='underline';\" onmouseout=\"this.style.textDecoration='none';\" >Logout</a></span>");
}else{
setcookie("User_my_site", $_POST['admin'], $hour);
print("<span style=\"float: left; text-align: left; padding: 5px 5px 5px 5px;\">Welcome <span id=\"myusername\">".$myusername."</span>! <br />Visit your <a style=\"text-decoration: none;\" href=\"login/member.php\" onmouseover=\"this.style.textDecoration='underline';\" onmouseout=\"this.style.textDecoration='none';\" >member's stat</a> <br /><a style=\"text-decoration: none;\" href=\"login/logout.php\" onmouseover=\"this.style.textDecoration='underline';\" onmouseout=\"this.style.textDecoration='none';\" >Logout</a></span>");
}
//then redirect them to the members area
//header("Location: login/member.php");
//print("Welcome".$username);
//header("Location: login/member.php");
//header("Location: ");
}
}
}else{
// if they are not logged in
login();
}
?>
</div>
kows
Apr 10th, 2010, 02:11 PM
not really. here, I've made some small changes all over the place (they're highlighted in red), feel free to take a look:
<?php
//say goodbye to magic_quotes_gpc! no false security.
//fix magic_quotes_gpc() being on
if(get_magic_quotes_gpc())
{
foreach($_GET as $k => $v)
{
$_GET[$k] = stripslashes($v);
}
foreach($_POST as $k => $v)
{
$_POST[$k] = stripslashes($v);
}
foreach($_COOKIE as $k => $v)
{
$_COOKIE[$k] = stripslashes($v);
}
}
//ob_start();
include("dbconnection.php");
//I got rid of your function. no need for it
//Checks if there is a login cookie
if(isset($_COOKIE['ID_my_site'])){ //if there is, it logs you in and directs you to the members page
$myusername = $_COOKIE['ID_my_site'];
$pass = $_COOKIE['Key_my_site'];
$admin = $_COOKIE['Admin_my_site'];
$user = $_COOKIE['User_my_site'];
$sql = "SELECT * FROM ";
if($admin=="yes"){
$sql .= $dbTable2;
}else{
$sql .= $dbTable;
}
$sql .= " WHERE username = '".mysql_real_escape_string($myusername)."'";
$check = mysql_query($sql)or die(mysql_error());
while($info = mysql_fetch_array( $check )){
//you don't need to check if the passwords do not match, just check if they DO match
/*
if ($pass != $info['password']){
}else{
*/
if($pass == $info['password']){
//you can uncomment these headers now if you'd like
//print("Welcome ".$myusername."! <br />Visit your <a href=\"login/member.php\">member's stat</a> <br /><a href=\"login/logout.php\">Logout</a>");
//header("Location: login/member.php");
//header("Location: ");
}
}
}
//variable to keep track of whether to show the user the login form or not
$showlogin = true; //we show the form by default, -unless- we know they have logged in
//if the login form is submitted
if (isset($_POST['submit'])){ // if form has been submitted
if(!$_POST['username'] || !$_POST['pass']) {// makes sure they filled it in
//die('You did not fill in a required field.');
print('You did not fill in a required field.');
}// checks it against the database
//don't need this if anymore, but we need the stuff inside of it
//if (!get_magic_quotes_gpc()){
//$_POST['email'] = addslashes($_POST['email']);
//we use mysql_real_escape_string(), not addslashes()
$_POST['email'] = mysql_real_escape_string($_POST['email']);
//we also need to sanitize the username! but use a variable:
$db['username'] = mysql_real_escape_string($_POST['username']);
//end of the if we no longer need
//}
$sql = "SELECT * FROM ";
if($admin=="yes"){
$sql .= $dbTable2;
}else{
$sql .= $dbTable;
}
$sql .= " WHERE username = '".$db['username']."'";
$check = mysql_query($sql) or die(mysql_error());
//Gives error if user dosen't exist
$check2 = mysql_num_rows($check);
if ($check2 == 0) {
//die('That user does not exist in our database. <a href=login/register.php>Click Here to Register</a>');
print('That user does not exist in our database.');
//login(); //we don't want to echo out a form right away!
}
while($info = mysql_fetch_array( $check )){
/* you don't need to do this anymore.
$_POST['pass'] = stripslashes($_POST['pass']);
$info['password'] = stripslashes($info['password']); //you should have never needed to do this. the database doesn't store extra slashes.
*/
$_POST['pass'] = md5($_POST['pass']);
//gives error if the password is wrong
if ($_POST['pass'] != $info['password']){
//die('Incorrect password, please try again.');
print('Incorrect password, please try again.');
//login(); //we don't want to echo out a form right away!
}else{
// if login is ok then we add a cookie
//$_POST['username'] = stripslashes($_POST['username']); //no more stripslashes
$hour = time() + 3600;
setcookie("ID_my_site", $_POST['username'], $hour);
setcookie("Key_my_site", $_POST['pass'], $hour);
//they are logged in. no need to show the login form
$showlogin = false;
if($_POST["admin"]=="yes"){
setcookie("Admin_my_site", $_POST['admin'], $hour);
//no printing! this is -logic- time
//print("<span style=\"float: left; text-align: left; padding: 5px 5px 5px 5px;\">Welcome ".$myusername."! <br />Visit your <a style=\"text-decoration: none;\" onmouseover=\"this.style.textDecoration='underline';\" onmouseout=\"this.style.textDecoration='none';\" href=\"login/member.php\">member's stat</a> <br /><a style=\"text-decoration: none;\" href=\"login/logout.php\" onmouseover=\"this.style.textDecoration='underline';\" onmouseout=\"this.style.textDecoration='none';\" >Logout</a></span>");
}else{
setcookie("User_my_site", $_POST['admin'], $hour);
//no printing! this is -logic- time
//print("<span style=\"float: left; text-align: left; padding: 5px 5px 5px 5px;\">Welcome <span id=\"myusername\">".$myusername."</span>! <br />Visit your <a style=\"text-decoration: none;\" href=\"login/member.php\" onmouseover=\"this.style.textDecoration='underline';\" onmouseout=\"this.style.textDecoration='none';\" >member's stat</a> <br /><a style=\"text-decoration: none;\" href=\"login/logout.php\" onmouseover=\"this.style.textDecoration='underline';\" onmouseout=\"this.style.textDecoration='none';\" >Logout</a></span>");
}
//you can uncomment these redirects now
//then redirect them to the members area
//header("Location: login/member.php");
//print("Welcome".$username);
//header("Location: login/member.php");
}
}
}
//commented this out
/*else{
// if they are not logged in
login();
}*/
//if we are supposed to show the login form, then let's show it
if($showlogin){
?>
<div style="float: left; width: 100%; margin: 0px 0px 0px 0px; background-color: #7C7C7C; border: 1px solid #A5A498; border-width: 1px 1px 0px 1px;">
<span style="float: left; padding: 2px 10px 0px 12px; color: #FFFFFF; font-family: arial; font-weight:bold; font-size: 13px;">Login</span>
</div>
<div style="float: left; width: 100%; height: 120px; background-color: #B4B3A9; border: 1px solid #A5A498; margin: 0px 0px 0px 0px; overflow-x: hidden; overflow-y: auto;">
<table border="0">
<tr>
<td>Administrator:</td><td><input type="checkbox" id="adminid" name="admin" style="float: left; border: 1px solid #7C7C7C; background-color: #7C7C7C;" value="no" onClick="if(this.value=='no'){this.value='yes'; document.getElementById('register').style.display = 'none';} else{this.value='no';document.getElementById('register').style.display = 'block';};" /></td>
</tr>
<tr>
<td>Username:</td>
<td><input type="text" name="<?php //vb_login_username?>username" id="username" style="float: left; border: 1px solid #7C7C7C; font: 9px verdana, geneva, lucida, 'lucida grande', arial, helvetica, sans-serif; width: 100px; height: 15px;" value="User Name" onBlur="if (this.value == '') this.value = 'User Name';" onFocus="if (this.value == 'User Name') this.value = '';" /></td>
</tr>
<tr>
<td>Password:</td><td><input type="password" style="float: left; border: 1px solid #7C7C7C; font: 9pt verdana, geneva, lucida, 'lucida grande', arial, helvetica, sans-serif; width: 100px; height: 15px;" <?php //name="pass"?> name="<?php //vb_login_username?>pass" id="pass" /></td></tr>
<tr>
<td><a id="register" href="login/register.php" style="float: left; display: block; background-color: #7C7C7C; text-align: left; padding: 0px 0px 0px 5px; width: 80px; height: 20px; text-decoration: none; color: #ffffff; border: 1px solid #7C7C7C; font-weight: bold;" onMouseOver="this.style.backgroundColor='#B4B3A9'" onMouseOut="this.style.backgroundColor='#7C7C7C'">Register</a></td><td align="right"><input type="submit" style="float: left; border: 1px solid #7C7C7C; background-color: #7C7C7C; color: #ffffff; font: 9pt verdana, geneva, lucida, 'lucida grande', arial, helvetica, sans-serif; font-weight: bold; width: 100px; height: 20px;" name="submit" onMouseOver="this.style.backgroundColor='#B4B3A9'" onMouseOut="this.style.backgroundColor='#7C7C7C'" value="Login" /></td>
</tr>
</table>
</div>
<?php } //end if $showlogin ?>
kows
Apr 10th, 2010, 02:12 PM
and because my post was too long to make a comment afterward, here it is:
of course, that's all untested, but it should be okay. other than the things I mentioned in that code, there are plenty of other things you can do to better this code. for example, when you query the database to see if the user exists you already know you should only be returning one result (one user per username), but you have a while looping through the results of the query. all you need to do is fetch them once, like so:
$info = mysql_fetch_assoc($query);
hope that at least gives you a bit of insight, or something!
edit: oh yeah, almost forgot! instead of just printing out your errors as they happen (I didn't comment them out), consider something like this (this would be within your login validation [or just general form validation]):
$errors = array();
if($_SERVER['REQUEST_METHOD'] == "POST"){
if(empty($_POST['username'])){
$errors[] = "username was empty";
}
if(empty($_POST['password'])){
$errors[] = "password was empty";
}
if(empty($_POST['email'])){
$errors[] = "e-mail was empty";
}
if(count($errors) == 0){
/* put the rest of your login logic in here, and continue checking if
* count($errors) is 0 before you go to the next "level" of validation
*/
}
}
then, later on (presumably on your form):
<h1>Login</h1>
<?php if(count($errors)): ?>
<h2>The following errors occurred:</h2>
<ul>
<?php foreach($errors as $error): ?>
<li><?php echo $error; ?></li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
<!-- now your form goes here -->
TheBigB
Apr 11th, 2010, 12:36 PM
A little thing I've noticed is that you give specific feedback when the username does not exist.
This can be risky. It makes the job of a bruteforcer a heck of a lot easier when it can validate the username.
gilgalbiblewhee
Apr 11th, 2010, 06:31 PM
A little thing I've noticed is that you give specific feedback when the username does not exist.
This can be risky. It makes the job of a bruteforcer a heck of a lot easier when it can validate the username.
What do you mean? Kows, give me some time to look at your posting.
TheBigB
Apr 11th, 2010, 06:41 PM
I was aiming at a part in index.php
$sql .= " WHERE username = '".$_POST['username']."'";
$check = mysql_query($sql)or die(mysql_error());
//Gives error if user dosen't exist
$check2 = mysql_num_rows($check);
if ($check2 == 0) {
//die('That user does not exist in our database. <a href=login/register.php>Click Here to Register</a>');
print('That user does not exist in our database.');
login();
}
You should give the same message for username and password errors.
Like: "Username or password incorrect."
gilgalbiblewhee
Apr 14th, 2010, 06:09 PM
not really. here, I've made some small changes all over the place (they're highlighted in red), feel free to take a look:
<?php
//say goodbye to magic_quotes_gpc! no false security.
//fix magic_quotes_gpc() being on
if(get_magic_quotes_gpc())
{
foreach($_GET as $k => $v)
{
$_GET[$k] = stripslashes($v);
}
foreach($_POST as $k => $v)
{
$_POST[$k] = stripslashes($v);
}
foreach($_COOKIE as $k => $v)
{
$_COOKIE[$k] = stripslashes($v);
}
}
//ob_start();
include("dbconnection.php");
//I got rid of your function. no need for it
//Checks if there is a login cookie
if(isset($_COOKIE['ID_my_site'])){ //if there is, it logs you in and directs you to the members page
$myusername = $_COOKIE['ID_my_site'];
$pass = $_COOKIE['Key_my_site'];
$admin = $_COOKIE['Admin_my_site'];
$user = $_COOKIE['User_my_site'];
$sql = "SELECT * FROM ";
if($admin=="yes"){
$sql .= $dbTable2;
}else{
$sql .= $dbTable;
}
$sql .= " WHERE username = '".mysql_real_escape_string($myusername)."'";
$check = mysql_query($sql)or die(mysql_error());
while($info = mysql_fetch_array( $check )){
//you don't need to check if the passwords do not match, just check if they DO match
/*
if ($pass != $info['password']){
}else{
*/
if($pass == $info['password']){
//you can uncomment these headers now if you'd like
//print("Welcome ".$myusername."! <br />Visit your <a href=\"login/member.php\">member's stat</a> <br /><a href=\"login/logout.php\">Logout</a>");
//header("Location: login/member.php");
//header("Location: ");
}
}
}
//variable to keep track of whether to show the user the login form or not
$showlogin = true; //we show the form by default, -unless- we know they have logged in
//if the login form is submitted
if (isset($_POST['submit'])){ // if form has been submitted
if(!$_POST['username'] || !$_POST['pass']) {// makes sure they filled it in
//die('You did not fill in a required field.');
print('You did not fill in a required field.');
}// checks it against the database
//don't need this if anymore, but we need the stuff inside of it
//if (!get_magic_quotes_gpc()){
//$_POST['email'] = addslashes($_POST['email']);
//we use mysql_real_escape_string(), not addslashes()
$_POST['email'] = mysql_real_escape_string($_POST['email']);
//we also need to sanitize the username! but use a variable:
$db['username'] = mysql_real_escape_string($_POST['username']);
//end of the if we no longer need
//}
$sql = "SELECT * FROM ";
if($admin=="yes"){
$sql .= $dbTable2;
}else{
$sql .= $dbTable;
}
$sql .= " WHERE username = '".$db['username']."'";
$check = mysql_query($sql) or die(mysql_error());
//Gives error if user dosen't exist
$check2 = mysql_num_rows($check);
if ($check2 == 0) {
//die('That user does not exist in our database. <a href=login/register.php>Click Here to Register</a>');
print('That user does not exist in our database.');
//login(); //we don't want to echo out a form right away!
}
while($info = mysql_fetch_array( $check )){
/* you don't need to do this anymore.
$_POST['pass'] = stripslashes($_POST['pass']);
$info['password'] = stripslashes($info['password']); //you should have never needed to do this. the database doesn't store extra slashes.
*/
$_POST['pass'] = md5($_POST['pass']);
//gives error if the password is wrong
if ($_POST['pass'] != $info['password']){
//die('Incorrect password, please try again.');
print('Incorrect password, please try again.');
//login(); //we don't want to echo out a form right away!
}else{
// if login is ok then we add a cookie
//$_POST['username'] = stripslashes($_POST['username']); //no more stripslashes
$hour = time() + 3600;
setcookie("ID_my_site", $_POST['username'], $hour);//line 116
setcookie("Key_my_site", $_POST['pass'], $hour);//line 117
//they are logged in. no need to show the login form
$showlogin = false;
if($_POST["admin"]=="yes"){
setcookie("Admin_my_site", $_POST['admin'], $hour);
//no printing! this is -logic- time
//print("<span style=\"float: left; text-align: left; padding: 5px 5px 5px 5px;\">Welcome ".$myusername."! <br />Visit your <a style=\"text-decoration: none;\" onmouseover=\"this.style.textDecoration='underline';\" onmouseout=\"this.style.textDecoration='none';\" href=\"login/member.php\">member's stat</a> <br /><a style=\"text-decoration: none;\" href=\"login/logout.php\" onmouseover=\"this.style.textDecoration='underline';\" onmouseout=\"this.style.textDecoration='none';\" >Logout</a></span>");
}else{
setcookie("User_my_site", $_POST['admin'], $hour);//line 129
//no printing! this is -logic- time
//print("<span style=\"float: left; text-align: left; padding: 5px 5px 5px 5px;\">Welcome <span id=\"myusername\">".$myusername."</span>! <br />Visit your <a style=\"text-decoration: none;\" href=\"login/member.php\" onmouseover=\"this.style.textDecoration='underline';\" onmouseout=\"this.style.textDecoration='none';\" >member's stat</a> <br /><a style=\"text-decoration: none;\" href=\"login/logout.php\" onmouseover=\"this.style.textDecoration='underline';\" onmouseout=\"this.style.textDecoration='none';\" >Logout</a></span>");
}
//you can uncomment these redirects now
//then redirect them to the members area
//header("Location: login/member.php");
//print("Welcome".$username);
//header("Location: login/member.php");
}
}
}
//commented this out
/*else{
// if they are not logged in
login();
}*/
//if we are supposed to show the login form, then let's show it
if($showlogin){
?>
<div style="float: left; width: 100%; margin: 0px 0px 0px 0px; background-color: #7C7C7C; border: 1px solid #A5A498; border-width: 1px 1px 0px 1px;">
<span style="float: left; padding: 2px 10px 0px 12px; color: #FFFFFF; font-family: arial; font-weight:bold; font-size: 13px;">Login</span>
</div>
<div style="float: left; width: 100%; height: 120px; background-color: #B4B3A9; border: 1px solid #A5A498; margin: 0px 0px 0px 0px; overflow-x: hidden; overflow-y: auto;">
<table border="0">
<tr>
<td>Administrator:</td><td><input type="checkbox" id="adminid" name="admin" style="float: left; border: 1px solid #7C7C7C; background-color: #7C7C7C;" value="no" onClick="if(this.value=='no'){this.value='yes'; document.getElementById('register').style.display = 'none';} else{this.value='no';document.getElementById('register').style.display = 'block';};" /></td>
</tr>
<tr>
<td>Username:</td>
<td><input type="text" name="<?php //vb_login_username?>username" id="username" style="float: left; border: 1px solid #7C7C7C; font: 9px verdana, geneva, lucida, 'lucida grande', arial, helvetica, sans-serif; width: 100px; height: 15px;" value="User Name" onBlur="if (this.value == '') this.value = 'User Name';" onFocus="if (this.value == 'User Name') this.value = '';" /></td>
</tr>
<tr>
<td>Password:</td><td><input type="password" style="float: left; border: 1px solid #7C7C7C; font: 9pt verdana, geneva, lucida, 'lucida grande', arial, helvetica, sans-serif; width: 100px; height: 15px;" <?php //name="pass"?> name="<?php //vb_login_username?>pass" id="pass" /></td></tr>
<tr>
<td><a id="register" href="login/register.php" style="float: left; display: block; background-color: #7C7C7C; text-align: left; padding: 0px 0px 0px 5px; width: 80px; height: 20px; text-decoration: none; color: #ffffff; border: 1px solid #7C7C7C; font-weight: bold;" onMouseOver="this.style.backgroundColor='#B4B3A9'" onMouseOut="this.style.backgroundColor='#7C7C7C'">Register</a></td><td align="right"><input type="submit" style="float: left; border: 1px solid #7C7C7C; background-color: #7C7C7C; color: #ffffff; font: 9pt verdana, geneva, lucida, 'lucida grande', arial, helvetica, sans-serif; font-weight: bold; width: 100px; height: 20px;" name="submit" onMouseOver="this.style.backgroundColor='#B4B3A9'" onMouseOut="this.style.backgroundColor='#7C7C7C'" value="Login" /></td>
</tr>
</table>
</div>
<?php } //end if $showlogin ?>
There's a problem with the header:
Warning: Cannot modify header information - headers already sent by (output started at C:...index.php:13) in C:...login\index.php on line 116
Warning: Cannot modify header information - headers already sent by (output started at C:...index.php:13) in C:...login\index.php on line 117
Warning: Cannot modify header information - headers already sent by (output started at C:...index.php:13) in C:...login\index.php on line 129
penagate
Apr 14th, 2010, 07:08 PM
//fix magic_quotes_gpc() being on
Magic quotes is recursive so you should use something like array_walk_recursive to reverse it.
penagate
Apr 14th, 2010, 07:09 PM
There's a problem with the header:
Why can't I send headers?
kows
Apr 14th, 2010, 07:10 PM
so you have to make sure there is no output before those cookies are sent. extra spaces, print statements, etc. I didn't exactly say to just take what I had changed and try to directly use that, either. it was to give you an idea of what I meant. there doesn't seem to be (at a glance) anything wrong with what I gave you though. if this is a page you are including somewhere it won't work, either.
edit: and penagate's link about sending headers would be an excellent start to learning to debug!
gilgalbiblewhee
Apr 14th, 2010, 08:17 PM
Why can't I send headers?
Ok I'm looking at your posting.
(output started at D:\dev\php\test.php:3)
Does that mean that it's line 3 of test.php that's causing the error?
So the setting of cookies has to be before the <head>. How about before <html>?
penagate
Apr 14th, 2010, 09:02 PM
Perhaps the wording of my post is not clear enough. The headers must be sent before the response body. The response body is what appears when you "View source" in the browser, including all HTML and any characters (even spaces) before the HTML.
A complete response looks something like this:
HTTP/1.1 200 OK
Content-type: text/html
Set-Cookie: foo=bar
<!DOCTYPE html>
<!-- ... -->
gilgalbiblewhee
Apr 14th, 2010, 10:21 PM
Perhaps the wording of my post is not clear enough. The headers must be sent before the response body. The response body is what appears when you "View source" in the browser, including all HTML and any characters (even spaces) before the HTML.
A complete response looks something like this:
HTTP/1.1 200 OK
Content-type: text/html
Set-Cookie: foo=bar
<!DOCTYPE html>
<!-- ... -->
Ok. Just wanted to make sure. Now there is no header warning but when I log in the login box disappears:
<?php
//twotexts
//ob_start();
session_start();
//say goodbye to magic_quotes_gpc! no false security.
//fix magic_quotes_gpc() being on
if(get_magic_quotes_gpc())
{
foreach($_GET as $k => $v)
{
$_GET[$k] = stripslashes($v);
}
foreach($_POST as $k => $v)
{
$_POST[$k] = stripslashes($v);
}
foreach($_COOKIE as $k => $v)
{
$_COOKIE[$k] = stripslashes($v);
}
}
//ob_start();
include("dbconnection.php");
//I got rid of your function. no need for it
//Checks if there is a login cookie
if(isset($_COOKIE['ID_my_site'])){ //if there is, it logs you in and directs you to the members page
$myusername = $_COOKIE['ID_my_site'];
$pass = $_COOKIE['Key_my_site'];
$admin = $_COOKIE['Admin_my_site'];
$user = $_COOKIE['User_my_site'];
$sql = "SELECT * FROM ";
if($admin=="yes"){
$sql .= $dbTable2;
}else{
$sql .= $dbTable;
}
$sql .= " WHERE username = '".mysql_real_escape_string($myusername)."'";
$check = mysql_query($sql)or die(mysql_error());
while($info = mysql_fetch_array( $check )){
//you don't need to check if the passwords do not match, just check if they DO match
/*
if ($pass != $info['password']){
}else{
*/
if($pass == $info['password']){
//you can uncomment these headers now if you'd like
//print("Welcome ".$myusername."! <br />Visit your <a href=\"login/member.php\">member's stat</a> <br /><a href=\"login/logout.php\">Logout</a>");
//header("Location: login/member.php");
//header("Location: ");
}
}
}
//variable to keep track of whether to show the user the login form or not
$showlogin = true; //we show the form by default, -unless- we know they have logged in
//if the login form is submitted
if (isset($_POST['submit'])){ // if form has been submitted
if(!$_POST['username'] || !$_POST['pass']) {// makes sure they filled it in
//die('You did not fill in a required field.');
print('You did not fill in a required field.');
}// checks it against the database
//don't need this if anymore, but we need the stuff inside of it
//if (!get_magic_quotes_gpc()){
//$_POST['email'] = addslashes($_POST['email']);
//we use mysql_real_escape_string(), not addslashes()
$_POST['email'] = mysql_real_escape_string($_POST['email']);
//we also need to sanitize the username! but use a variable:
$db['username'] = mysql_real_escape_string($_POST['username']);
//end of the if we no longer need
//}
$sql = "SELECT * FROM ";
if($admin=="yes"){
$sql .= $dbTable2;
}else{
$sql .= $dbTable;
}
$sql .= " WHERE username = '".$db['username']."'";
$check = mysql_query($sql) or die(mysql_error());
//Gives error if user dosen't exist
$check2 = mysql_num_rows($check);
if ($check2 == 0) {
//die('That user does not exist in our database. <a href=login/register.php>Click Here to Register</a>');
print('That user does not exist in our database.');
//login(); //we don't want to echo out a form right away!
}
while($info = mysql_fetch_array( $check )){
/* you don't need to do this anymore.
$_POST['pass'] = stripslashes($_POST['pass']);
$info['password'] = stripslashes($info['password']); //you should have never needed to do this. the database doesn't store extra slashes.
*/
$_POST['pass'] = md5($_POST['pass']);
//gives error if the password is wrong
if ($_POST['pass'] != $info['password']){
//die('Incorrect password, please try again.');
print('Incorrect password, please try again.');
//login(); //we don't want to echo out a form right away!
}else{
// if login is ok then we add a cookie
//$_POST['username'] = stripslashes($_POST['username']); //no more stripslashes
$hour = time() + 3600;
setcookie("ID_my_site", $_POST['username'], $hour);
setcookie("Key_my_site", $_POST['pass'], $hour);
//they are logged in. no need to show the login form
$showlogin = false;
if($_POST["admin"]=="yes"){
setcookie("Admin_my_site", $_POST['admin'], $hour);
//no printing! this is -logic- time
//print("<span style=\"float: left; text-align: left; padding: 5px 5px 5px 5px;\">Welcome ".$myusername."! <br />Visit your <a style=\"text-decoration: none;\" onmouseover=\"this.style.textDecoration='underline';\" onmouseout=\"this.style.textDecoration='none';\" href=\"login/member.php\">member's stat</a> <br /><a style=\"text-decoration: none;\" href=\"login/logout.php\" onmouseover=\"this.style.textDecoration='underline';\" onmouseout=\"this.style.textDecoration='none';\" >Logout</a></span>");
}else{
setcookie("User_my_site", $_POST['admin'], $hour);
//no printing! this is -logic- time
//print("<span style=\"float: left; text-align: left; padding: 5px 5px 5px 5px;\">Welcome <span id=\"myusername\">".$myusername."</span>! <br />Visit your <a style=\"text-decoration: none;\" href=\"login/member.php\" onmouseover=\"this.style.textDecoration='underline';\" onmouseout=\"this.style.textDecoration='none';\" >member's stat</a> <br /><a style=\"text-decoration: none;\" href=\"login/logout.php\" onmouseover=\"this.style.textDecoration='underline';\" onmouseout=\"this.style.textDecoration='none';\" >Logout</a></span>");
}
//you can uncomment these redirects now
//then redirect them to the members area
//header("Location: login/member.php");
//print("Welcome".$username);
//header("Location: login/member.php");
}
}
}
//commented this out
/*else{
// if they are not logged in
login();
}*/
$_SESSION['logged_in'] = 1;
?>
<!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">
kows
Apr 14th, 2010, 11:13 PM
yes, that's because you aren't telling your script to do anything once you are logged in. all of your redirect headers are commented out. the login isn't supposed to show once you're logged in. that's when you would be redirecting to a "successfully logged in" page, or something.
gilgalbiblewhee
Apr 15th, 2010, 12:14 AM
yes, that's because you aren't telling your script to do anything once you are logged in. all of your redirect headers are commented out. the login isn't supposed to show once you're logged in. that's when you would be redirecting to a "successfully logged in" page, or something.
What confuses me are the if statements. Since I've put most of the code at the top the welcome appears at the top. But if I cut off and paste the if statements which contain the prints I'm afraid of messing up the code.
kows
Apr 15th, 2010, 12:33 AM
if you're afraid of screwing stuff up, you might be in the wrong line of work. make a back-up of the file and just play with it. you won't learn how things work if you don't get your hands dirty.
in your case, instead of all of those prints and stuff, use a variable to display a message. then, you can later embed this message into your mark-up. take the error displaying example I showed you here (http://www.vbforums.com/showpost.php?p=3774659&postcount=12) and try to apply that to your code; you'll have an $errors array and continually add onto it instead of print()ing out messages. then, later on in your mark-up (where ever you deem appropriate), you check if the errors array has anything in it -- if so, you display those errors. otherwise, you do nothing. keep in mind also that it's only an example -- you don't have to only check for empty variables. the point of it is using an array to record all of your error messages and then displaying them later. then, you'll have a simple way of checking whether or not an error occurred on this page by checking the count() of the $errors array (if it's above 0, an error occurred).
as penagate said, separation of presentation and logic is good practice, and enforcing this style of programming now will make you a better programmer. it also makes easier-to-maintain code, especially if you're working with a team of some kind.
gilgalbiblewhee
Apr 15th, 2010, 11:05 AM
Ok thanks I'm working on it. The logout is giving the header problems as well:
<?php
//ob_start();
include("dbconnection.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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Logout</title>
</head>
<body>
<?php
$past = time() - 100;
//this makes the time in the past to destroy the cookie
setcookie("ID_my_site", gone, $past);
setcookie("Key_my_site", gone, $past);
setcookie("Admin_my_site", gone, $past);
header("Location: ../index.php");
?>
</body>
</html>
kows
Apr 15th, 2010, 12:37 PM
I really don't see what you're not understanding (there have been 3 or 4 posts in this thread alone about this [and a link to a comprehensive post made by penagate about why you might not be able to send headers]): you cannot send headers after you have sent output. output is defined in this case as ANYTHING that you echo out to be sent to the browser. you are echoing out a ton of HTML, and in the middle of this HTML you're then trying to set cookies (aka send headers).
the bottom line: you cannot set cookies (send headers) after you have sent output (echoed/printed anything). place your logic (setting cookies, sending headers) at the top of your script (away from your presentation [or mark-up (or HTML)]).
hope that helps. :/
gilgalbiblewhee
Apr 15th, 2010, 01:31 PM
I really don't see what you're not understanding (there have been 3 or 4 posts in this thread alone about this [and a link to a comprehensive post made by penagate about why you might not be able to send headers]): you cannot send headers after you have sent output. output is defined in this case as ANYTHING that you echo out to be sent to the browser. you are echoing out a ton of HTML, and in the middle of this HTML you're then trying to set cookies (aka send headers).
the bottom line: you cannot set cookies (send headers) after you have sent output (echoed/printed anything). place your logic (setting cookies, sending headers) at the top of your script (away from your presentation [or mark-up (or HTML)]).
hope that helps. :/
That's right. Like this:
<?php
//ob_start();
include("dbconnection.php");
$past = time() - 100;
//this makes the time in the past to destroy the cookie
setcookie("ID_my_site", gone, $past);
setcookie("Key_my_site", gone, $past);
setcookie("Admin_my_site", gone, $past);
header("Location: ../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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Logout</title>
</head>
<body>
<?php
?>
</body>
</html>
gilgalbiblewhee
Apr 15th, 2010, 01:46 PM
But going back to the login I'm trying to put together the print within the <div> and it gives me this error:
Warning: mysql_fetch_array() expects parameter 1 to be resource, null given in C:\...\login\index.php on line 35
<div style="float: left; width: 100%; margin: 0px 0px 0px 0px; background-color: #7C7C7C; border: 1px solid #A5A498; border-width: 1px 1px 0px 1px;">
<span style="float: left; padding: 2px 10px 0px 12px; color: #FFFFFF; font-family: arial; font-weight:bold; font-size: 13px;">Login</span>
</div>
<div style="float: left; width: 100%; height: 120px; background-color: #B4B3A9; border: 1px solid #A5A498; margin: 0px 0px 0px 0px; overflow-x: hidden; overflow-y: auto;"><?php
//if we are supposed to show the login form, then let's show it
if($showlogin=false){
?>
<table border="0">
<tr>
<td>Administrator:</td><td><input type="checkbox" id="adminid" name="admin" style="float: left; border: 1px solid #7C7C7C; background-color: #7C7C7C;" value="no" onClick="if(this.value=='no'){this.value='yes'; document.getElementById('register').style.display = 'none';} else{this.value='no';document.getElementById('register').style.display = 'block';};" /></td>
</tr><?php
$check2 = mysql_num_rows($check);
if ($check2 == 0){
print("<tr><td colspan=2 style=\"float: left; text-align: left; color: red; height: 20px; width: 100%; display: block; border: 1px solid black; overflow: hidden;\">That username does not exist in our database.</td></tr>");
}
?><tr>
<td>Username:</td>
<td><input type="text" name="username" id="username" style="float: left; border: 1px solid #7C7C7C; font: 9px verdana, geneva, lucida, 'lucida grande', arial, helvetica, sans-serif; width: 100px; height: 15px;" value="User Name" onBlur="if (this.value == '') this.value = 'User Name';" onFocus="if (this.value == 'User Name') this.value = '';" /></td>
</tr><?php
while($info = mysql_fetch_array($check)){
if ($_POST['pass'] != $info['password']){
print("<tr><td colspan=2 style=\"float: left; text-align: left; color: red; height: 20px; width: 100%; display: block; border: 1px solid black; overflow: hidden;\">Incorrect password, please try again.</td></tr>");
}
}
?>
<tr>
<td>Password:</td><td><input type="password" style="float: left; border: 1px solid #7C7C7C; font: 9pt verdana, geneva, lucida, 'lucida grande', arial, helvetica, sans-serif; width: 100px; height: 15px;" name="pass" id="pass" /></td></tr>
<tr>
<td><a id="register" href="login/register.php" style="float: left; display: block; background-color: #7C7C7C; text-align: left; padding: 0px 0px 0px 5px; width: 80px; height: 20px; text-decoration: none; color: #ffffff; border: 1px solid #7C7C7C; font-weight: bold;" onMouseOver="this.style.backgroundColor='#B4B3A9'" onMouseOut="this.style.backgroundColor='#7C7C7C'">Register</a></td><td align="right"><input type="submit" style="float: left; border: 1px solid #7C7C7C; background-color: #7C7C7C; color: #ffffff; font: 9pt verdana, geneva, lucida, 'lucida grande', arial, helvetica, sans-serif; font-weight: bold; width: 100px; height: 20px;" name="submit" onMouseOver="this.style.backgroundColor='#B4B3A9'" onMouseOut="this.style.backgroundColor='#7C7C7C'" value="Login" /></td>
</tr>
</table>
<?php
}else{
//if(isset($_POST['submit'])){
while($info = mysql_fetch_array($check)){
if($pass == $info['password']){
print("Welcome ".$myusername."! <br />Visit your <a href=\"login/member.php\">member's stat</a> <br /><a href=\"login/logout.php\">Logout</a>");
}else{print("Welcome ".$myusername."! <br />Visit your <a href=\"login/member.php\">member's stat</a> <br /><a href=\"login/logout.php\">Logout</a>");}
}
//}
}
?></div>
The while part was broken (taken) from:
//Checks if there is a login cookie
if(isset($_COOKIE['ID_my_site'])){ //if there is, it logs you in and directs you to the members page
$myusername = $_COOKIE['ID_my_site'];
$pass = $_COOKIE['Key_my_site'];
$admin = $_COOKIE['Admin_my_site'];
$user = $_COOKIE['User_my_site'];
$sql = "SELECT * FROM ";
if($admin=="yes"){
$sql .= $dbTable2;
}else{
$sql .= $dbTable;
}
$sql .= " WHERE username = '".mysql_real_escape_string($myusername)."'";
$check = mysql_query($sql)or die(mysql_error());
/* while($info = mysql_fetch_array( $check )){
if($pass == $info['password']){
//you can uncomment these headers now if you'd like
print("Welcome ".$myusername."! <br />Visit your <a href=\"login/member.php\">member's stat</a> <br /><a href=\"login/logout.php\">Logout</a>");
//header("Location: login/member.php");
//header("Location: ");
}
}*/
}
kows
Apr 15th, 2010, 04:13 PM
you never define $check in the code you posted that has an error. the parameter passed to mysql_fetch_array() needs to be a result from mysql_query(). you're also trying to use a while loop where you are only returning one record (and thus don't need to use a loop. you just need to make a call to mysql_fetch_array() or mysql_fetch_assoc()).
gilgalbiblewhee
Apr 16th, 2010, 05:53 PM
you never define $check in the code you posted that has an error. the parameter passed to mysql_fetch_array() needs to be a result from mysql_query(). you're also trying to use a while loop where you are only returning one record (and thus don't need to use a loop. you just need to make a call to mysql_fetch_array() or mysql_fetch_assoc()).
But it makes me wonder if the following should be brought down as well within the <div> or left above since it involves cookies:
while($info = mysql_fetch_array($check)){
$_POST['pass'] = md5($_POST['pass']);
//gives error if the password is wrong
if ($_POST['pass'] != $info['password']){
//die('Incorrect password, please try again.');
print('Incorrect password, please try again.');
//login(); //we don't want to echo out a form right away!
}else{
// if login is ok then we add a cookie
//$_POST['username'] = stripslashes($_POST['username']); //no more stripslashes
$hour = time() + 3600;
setcookie("ID_my_site", $_POST['username'], $hour);
setcookie("Key_my_site", $_POST['pass'], $hour);
//they are logged in. no need to show the login form
$showlogin = false;
if($_POST["admin"]=="yes"){
setcookie("Admin_my_site", $_POST['admin'], $hour);
//no printing! this is -logic- time
//print("<span style=\"float: left; text-align: left; padding: 5px 5px 5px 5px;\">Welcome ".$myusername."! <br />Visit your <a style=\"text-decoration: none;\" onmouseover=\"this.style.textDecoration='underline';\" onmouseout=\"this.style.textDecoration='none';\" href=\"login/member.php\">member's stat</a> <br /><a style=\"text-decoration: none;\" href=\"login/logout.php\" onmouseover=\"this.style.textDecoration='underline';\" onmouseout=\"this.style.textDecoration='none';\" >Logout</a></span>");
}else{
setcookie("User_my_site", $_POST['admin'], $hour);
//no printing! this is -logic- time
//print("<span style=\"float: left; text-align: left; padding: 5px 5px 5px 5px;\">Welcome <span id=\"myusername\">".$myusername."</span>! <br />Visit your <a style=\"text-decoration: none;\" href=\"login/member.php\" onmouseover=\"this.style.textDecoration='underline';\" onmouseout=\"this.style.textDecoration='none';\" >member's stat</a> <br /><a style=\"text-decoration: none;\" href=\"login/logout.php\" onmouseover=\"this.style.textDecoration='underline';\" onmouseout=\"this.style.textDecoration='none';\" >Logout</a></span>");
}
//you can uncomment these redirects now
//then redirect them to the members area
//header("Location: login/member.php");
//print("Welcome".$username);
//header("Location: login/member.php");
}
}
kows
Apr 16th, 2010, 06:42 PM
as I've tried to tell you -- use a variable of some sort (or an array of errors like I mentioned) to figure out where the errors are. you can set a flag variable for password if the password was wrong and then check whether that flag is set later on when you're displaying your form.
gilgalbiblewhee
Apr 17th, 2010, 12:46 AM
as I've tried to tell you -- use a variable of some sort (or an array of errors like I mentioned) to figure out where the errors are. you can set a flag variable for password if the password was wrong and then check whether that flag is set later on when you're displaying your form.
Ok I did that:
<?php
//twotexts
session_start();
//say goodbye to magic_quotes_gpc! no false security.
//fix magic_quotes_gpc() being on
if(get_magic_quotes_gpc()){
foreach($_GET as $k => $v){
$_GET[$k] = stripslashes($v);
}
foreach($_POST as $k => $v){
$_POST[$k] = stripslashes($v);
}
foreach($_COOKIE as $k => $v){
$_COOKIE[$k] = stripslashes($v);
}
}
include("dbconnection.php");
//I got rid of your function. no need for it
//Checks if there is a login cookie
if(isset($_COOKIE['ID_my_site'])){ //if there is, it logs you in and directs you to the members page
$myusername = $_COOKIE['ID_my_site'];
$pass = $_COOKIE['Key_my_site'];
$admin = $_COOKIE['Admin_my_site'];
$user = $_COOKIE['User_my_site'];
$sql = "SELECT * FROM ";
if($admin=="yes"){
$sql .= $dbTable2;
}else{
$sql .= $dbTable;
}
$sql .= " WHERE username = '".mysql_real_escape_string($myusername)."'";
$check = mysql_query($sql)or die(mysql_error());
while($info = mysql_fetch_array( $check )){
if($pass == $info['password']){
$writeusername = "Welcome ".$myusername."! <br />Visit your <a href=\"login/member.php\">member's stat</a> <br /><a href=\"login/logout.php\">Logout</a>";
}
}
}
//variable to keep track of whether to show the user the login form or not
$showlogin = true; //we show the form by default, -unless- we know they have logged in
//if the login form is submitted
if (isset($_POST['submit'])){ // if form has been submitted
if(!$_POST['username'] || !$_POST['pass']) {// makes sure they filled it in
$writeemptyfield = "<tr><td>You did not fill in a required field.</td></tr>";
}// checks it against the database
$_POST['email'] = mysql_real_escape_string($_POST['email']);
$db['username'] = mysql_real_escape_string($_POST['username']);
$sql = "SELECT * FROM ";
if($admin=="yes"){
$sql .= $dbTable2;
}else{
$sql .= $dbTable;
}
$sql .= " WHERE username = '".$db['username']."'";
$check = mysql_query($sql) or die(mysql_error());
//Gives error if user dosen't exist
$check2 = mysql_num_rows($check);
if ($check2 == 0) {
$writeusernoexist = "<tr><td>That user does not exist in our database.</td></tr>";
}
while($info = mysql_fetch_array( $check )){
$_POST['pass'] = md5($_POST['pass']);
//gives error if the password is wrong
if ($_POST['pass'] != $info['password']){
$writewrongpassword = "<tr><td>Incorrect password, please try again.</td></tr>";
}else{
// if login is ok then we add a cookie
$hour = time() + 3600;
setcookie("ID_my_site", $_POST['username'], $hour);
setcookie("Key_my_site", $_POST['pass'], $hour);
//they are logged in. no need to show the login form
$showlogin = false;
if($_POST["admin"]=="yes"){
setcookie("Admin_my_site", $_POST['admin'], $hour);
}else{
setcookie("User_my_site", $_POST['admin'], $hour);
}
}
}
}
$_SESSION['logged_in'] = 1;
...
?>
and
<?php
//ob_start();
include("dbconnection.php");
if(isset($_COOKIE['ID_my_site'])){
function login(){
print("<span style=\"float: left; text-align: left; padding: 5px 5px 5px 5px;\">Welcome <span id=\"myusername\">".$myusername."</span>! <br />Visit your <a style=\"text-decoration: none;\" href=\"login/member.php\" onmouseover=\"this.style.textDecoration='underline';\" onmouseout=\"this.style.textDecoration='none';\" >member's stat</a> <br /><a style=\"text-decoration: none;\" href=\"login/logout.php\" onmouseover=\"this.style.textDecoration='underline';\" onmouseout=\"this.style.textDecoration='none';\" >Logout</a></span>");
}
}else{
function login(){
?>
<table border="0">
<tr>
<td>Administrator:</td><td><input type="checkbox" id="adminid" name="admin" style="float: left; border: 1px solid #7C7C7C; background-color: #7C7C7C;" value="no" onClick="if(this.value=='no'){this.value='yes'; document.getElementById('register').style.display = 'none';} else{this.value='no';document.getElementById('register').style.display = 'block';};" /></td>
</tr>
<?php echo $writeemptyfield; ?>
<?php echo $writeusernoexist; ?>
<tr>
<td>Username:</td>
<td><input type="text" name="username" id="username" style="float: left; border: 1px solid #7C7C7C; font: 9px verdana, geneva, lucida, 'lucida grande', arial, helvetica, sans-serif; width: 100px; height: 15px;" value="User Name" onBlur="if (this.value == '') this.value = 'User Name';" onFocus="if (this.value == 'User Name') this.value = '';" /></td>
</tr>
<?php echo $writewrongpassword; ?>
<tr>
<td>Password:</td><td><input type="password" style="float: left; border: 1px solid #7C7C7C; font: 9pt verdana, geneva, lucida, 'lucida grande', arial, helvetica, sans-serif; width: 100px; height: 15px;" name="pass" id="pass" /></td></tr>
<tr>
<td><a id="register" href="login/register.php" style="float: left; display: block; background-color: #7C7C7C; text-align: left; padding: 0px 0px 0px 5px; width: 80px; height: 20px; text-decoration: none; color: #ffffff; border: 1px solid #7C7C7C; font-weight: bold;" onMouseOver="this.style.backgroundColor='#B4B3A9'" onMouseOut="this.style.backgroundColor='#7C7C7C'">Register</a></td><td align="right"><input type="submit" style="float: left; border: 1px solid #7C7C7C; background-color: #7C7C7C; color: #ffffff; font: 9pt verdana, geneva, lucida, 'lucida grande', arial, helvetica, sans-serif; font-weight: bold; width: 100px; height: 20px;" name="submit" onMouseOver="this.style.backgroundColor='#B4B3A9'" onMouseOut="this.style.backgroundColor='#7C7C7C'" value="Login" /></td>
</tr>
</table>
<?php
}
}
?>
<div style="float: left; width: 100%; margin: 0px 0px 0px 0px; background-color: #7C7C7C; border: 1px solid #A5A498; border-width: 1px 1px 0px 1px;">
<span style="float: left; padding: 2px 10px 0px 12px; color: #FFFFFF; font-family: arial; font-weight:bold; font-size: 13px;">Login</span>
</div>
<div style="float: left; width: 100%; height: 120px; background-color: #B4B3A9; border: 1px solid #A5A498; margin: 0px 0px 0px 0px; overflow-x: hidden; overflow-y: auto;">
<?php login(); ?>
</div>
But it's not functioning properly. When I log in it doesn't show "Welcome $username". The $username shows blank.
kows
Apr 17th, 2010, 11:06 AM
ack! why are you using a function to display all of this again? quit that ;) you only need the original IF statement you have, you don't need to create a function to echo anything.
functions are useful when you're going to be re-using code. they're unnecessary in your case. also, on why your variable wouldn't work -- you need to learn a little about variable scope (http://php.net/manual/en/language.variables.scope.php). if you define a variable in the global scope (outside of a function), then it isn't available inside of the function. you could use the global keyword to make it available, but you'll have to read the link if you want to continue doing that.
anyway, this is what you should be trying to do -- I've removed your function once again and I've even cleaned up the print statement you have to make it readable.
<?php include("dbconnection.php"); ?>
<div style="float: left; width: 100%; margin: 0px 0px 0px 0px; background-color: #7C7C7C; border: 1px solid #A5A498; border-width: 1px 1px 0px 1px;">
<span style="float: left; padding: 2px 10px 0px 12px; color: #FFFFFF; font-family: arial; font-weight:bold; font-size: 13px;">Login</span>
</div>
<div style="float: left; width: 100%; height: 120px; background-color: #B4B3A9; border: 1px solid #A5A498; margin: 0px 0px 0px 0px; overflow-x: hidden; overflow-y: auto;">
<?php if(isset($_COOKIE['ID_my_site'])){ ?>
<span style="float: left; text-align: left; padding: 5px 5px 5px 5px;">
Welcome <span id="myusername">{$myusername}</span>!<br />
Visit your <a style="text-decoration: none;" href="login/member.php" onmouseover="this.style.textDecoration='underline';" onmouseout="this.style.textDecoration='none';" >member's stat</a><br />
<a style="text-decoration: none;" href="login/logout.php" onmouseover="this.style.textDecoration='underline';" onmouseout="this.style.textDecoration='none';" >Logout</a>
</span>
<?php }else { ?>
<table border="0">
<tr>
<td>Administrator:</td><td><input type="checkbox" id="adminid" name="admin" style="float: left; border: 1px solid #7C7C7C; background-color: #7C7C7C;" value="no" onClick="if(this.value=='no'){this.value='yes'; document.getElementById('register').style.display = 'none';} else{this.value='no';document.getElementById('register').style.display = 'block';};" /></td>
</tr>
<?php echo $writeemptyfield; ?>
<?php echo $writeusernoexist; ?>
<tr>
<td>Username:</td>
<td><input type="text" name="username" id="username" style="float: left; border: 1px solid #7C7C7C; font: 9px verdana, geneva, lucida, 'lucida grande', arial, helvetica, sans-serif; width: 100px; height: 15px;" value="User Name" onBlur="if (this.value == '') this.value = 'User Name';" onFocus="if (this.value == 'User Name') this.value = '';" /></td>
</tr>
<?php echo $writewrongpassword; ?>
<tr>
<td>Password:</td><td><input type="password" style="float: left; border: 1px solid #7C7C7C; font: 9pt verdana, geneva, lucida, 'lucida grande', arial, helvetica, sans-serif; width: 100px; height: 15px;" name="pass" id="pass" /></td></tr>
<tr>
<td><a id="register" href="login/register.php" style="float: left; display: block; background-color: #7C7C7C; text-align: left; padding: 0px 0px 0px 5px; width: 80px; height: 20px; text-decoration: none; color: #ffffff; border: 1px solid #7C7C7C; font-weight: bold;" onMouseOver="this.style.backgroundColor='#B4B3A9'" onMouseOut="this.style.backgroundColor='#7C7C7C'">Register</a></td><td align="right"><input type="submit" style="float: left; border: 1px solid #7C7C7C; background-color: #7C7C7C; color: #ffffff; font: 9pt verdana, geneva, lucida, 'lucida grande', arial, helvetica, sans-serif; font-weight: bold; width: 100px; height: 20px;" name="submit" onMouseOver="this.style.backgroundColor='#B4B3A9'" onMouseOut="this.style.backgroundColor='#7C7C7C'" value="Login" /></td>
</tr>
</table>
<?php } ?>
</div>
logically, this will do exactly what you've done before. it's just better structured and written in a way that should be more maintainable than what you have done.
you may also want to look into using a stylesheet instead of having all of that inline CSS. as far as maintainability goes, your HTML will be incredibly difficult to change in the future if you choose to do so.
gilgalbiblewhee
Apr 17th, 2010, 04:42 PM
ack! why are you using a function to display all of this again? quit that ;) you only need the original IF statement you have, you don't need to create a function to echo anything.
functions are useful when you're going to be re-using code. they're unnecessary in your case. also, on why your variable wouldn't work -- you need to learn a little about variable scope (http://php.net/manual/en/language.variables.scope.php). if you define a variable in the global scope (outside of a function), then it isn't available inside of the function. you could use the global keyword to make it available, but you'll have to read the link if you want to continue doing that.
anyway, this is what you should be trying to do -- I've removed your function once again and I've even cleaned up the print statement you have to make it readable.
<?php include("dbconnection.php"); ?>
<div style="float: left; width: 100%; margin: 0px 0px 0px 0px; background-color: #7C7C7C; border: 1px solid #A5A498; border-width: 1px 1px 0px 1px;">
<span style="float: left; padding: 2px 10px 0px 12px; color: #FFFFFF; font-family: arial; font-weight:bold; font-size: 13px;">Login</span>
</div>
<div style="float: left; width: 100%; height: 120px; background-color: #B4B3A9; border: 1px solid #A5A498; margin: 0px 0px 0px 0px; overflow-x: hidden; overflow-y: auto;">
<?php if(isset($_COOKIE['ID_my_site'])){ ?>
<span style="float: left; text-align: left; padding: 5px 5px 5px 5px;">
Welcome <span id="myusername">{$myusername}</span>!<br />
Visit your <a style="text-decoration: none;" href="login/member.php" onmouseover="this.style.textDecoration='underline';" onmouseout="this.style.textDecoration='none';" >member's stat</a><br />
<a style="text-decoration: none;" href="login/logout.php" onmouseover="this.style.textDecoration='underline';" onmouseout="this.style.textDecoration='none';" >Logout</a>
</span>
<?php }else { ?>
<table border="0">
<tr>
<td>Administrator:</td><td><input type="checkbox" id="adminid" name="admin" style="float: left; border: 1px solid #7C7C7C; background-color: #7C7C7C;" value="no" onClick="if(this.value=='no'){this.value='yes'; document.getElementById('register').style.display = 'none';} else{this.value='no';document.getElementById('register').style.display = 'block';};" /></td>
</tr>
<?php echo $writeemptyfield; ?>
<?php echo $writeusernoexist; ?>
<tr>
<td>Username:</td>
<td><input type="text" name="username" id="username" style="float: left; border: 1px solid #7C7C7C; font: 9px verdana, geneva, lucida, 'lucida grande', arial, helvetica, sans-serif; width: 100px; height: 15px;" value="User Name" onBlur="if (this.value == '') this.value = 'User Name';" onFocus="if (this.value == 'User Name') this.value = '';" /></td>
</tr>
<?php echo $writewrongpassword; ?>
<tr>
<td>Password:</td><td><input type="password" style="float: left; border: 1px solid #7C7C7C; font: 9pt verdana, geneva, lucida, 'lucida grande', arial, helvetica, sans-serif; width: 100px; height: 15px;" name="pass" id="pass" /></td></tr>
<tr>
<td><a id="register" href="login/register.php" style="float: left; display: block; background-color: #7C7C7C; text-align: left; padding: 0px 0px 0px 5px; width: 80px; height: 20px; text-decoration: none; color: #ffffff; border: 1px solid #7C7C7C; font-weight: bold;" onMouseOver="this.style.backgroundColor='#B4B3A9'" onMouseOut="this.style.backgroundColor='#7C7C7C'">Register</a></td><td align="right"><input type="submit" style="float: left; border: 1px solid #7C7C7C; background-color: #7C7C7C; color: #ffffff; font: 9pt verdana, geneva, lucida, 'lucida grande', arial, helvetica, sans-serif; font-weight: bold; width: 100px; height: 20px;" name="submit" onMouseOver="this.style.backgroundColor='#B4B3A9'" onMouseOut="this.style.backgroundColor='#7C7C7C'" value="Login" /></td>
</tr>
</table>
<?php } ?>
</div>
logically, this will do exactly what you've done before. it's just better structured and written in a way that should be more maintainable than what you have done.
you may also want to look into using a stylesheet instead of having all of that inline CSS. as far as maintainability goes, your HTML will be incredibly difficult to change in the future if you choose to do so.
Welcome {$myusername}! It doesn't show the username. I don't understand. Once I log in it refreshes and makes me log in a 2nd time. The 2nd time it refreshes it shows Welcome {$myusername}!.
kows
Apr 17th, 2010, 06:41 PM
err. of course, that's because I was in a hurry and when I removed your print I didn't update that. {$myusername} is in HTML now; you'd need to replace that with:
<?php echo $myusername; ?>
your login is showing you as not logged on because you're using cookies. the cookie is being set, however a cookie doesn't actually become usable until you've loaded a new page. this can be gotten around by you having a redirect (to the "members" page) after the cookies are set (using the header() function). if you were to use sessions (as I recommended previously), this wouldn't be an issue.
gilgalbiblewhee
Apr 18th, 2010, 02:12 AM
err. of course, that's because I was in a hurry and when I removed your print I didn't update that. {$myusername} is in HTML now; you'd need to replace that with:
<?php echo $myusername; ?>
your login is showing you as not logged on because you're using cookies. the cookie is being set, however a cookie doesn't actually become usable until you've loaded a new page. this can be gotten around by you having a redirect (to the "members" page) after the cookies are set (using the header() function). if you were to use sessions (as I recommended previously), this wouldn't be an issue.
Why isn't it logging out?
<?php
//ob_start();
include("dbconnection.php");
$past = time() - 100;
//this makes the time in the past to destroy the cookie
setcookie("ID_my_site", gone, $past);
setcookie("Key_my_site", gone, $past);
setcookie("Admin_my_site", gone, $past);
header("Location: ../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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Logout</title>
</head>
<body>
<?php
?>
</body>
</html>
I put the header in the login and it worked. I forgot that this was excluded. But what's replacing the ob_start that it worked?
gilgalbiblewhee
Apr 18th, 2010, 02:13 AM
and because my post was too long to make a comment afterward, here it is:
of course, that's all untested, but it should be okay. other than the things I mentioned in that code, there are plenty of other things you can do to better this code. for example, when you query the database to see if the user exists you already know you should only be returning one result (one user per username), but you have a while looping through the results of the query. all you need to do is fetch them once, like so:
$info = mysql_fetch_assoc($query);
hope that at least gives you a bit of insight, or something!
edit: oh yeah, almost forgot! instead of just printing out your errors as they happen (I didn't comment them out), consider something like this (this would be within your login validation [or just general form validation]):
$errors = array();
if($_SERVER['REQUEST_METHOD'] == "POST"){
if(empty($_POST['username'])){
$errors[] = "username was empty";
}
if(empty($_POST['password'])){
$errors[] = "password was empty";
}
if(empty($_POST['email'])){
$errors[] = "e-mail was empty";
}
if(count($errors) == 0){
/* put the rest of your login logic in here, and continue checking if
* count($errors) is 0 before you go to the next "level" of validation
*/
}
}
then, later on (presumably on your form):
<h1>Login</h1>
<?php if(count($errors)): ?>
<h2>The following errors occurred:</h2>
<ul>
<?php foreach($errors as $error): ?>
<li><?php echo $error; ?></li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
<!-- now your form goes here -->
Should I include this?
kows
Apr 18th, 2010, 12:01 PM
Should I include this?
.. you can't just "include it." it's an example of the logic behind displaying errors. it isn't something that will just work for you. you'd need to apply it to work for your situation.
I put the header in the login and it worked. I forgot that this was excluded. But what's replacing the ob_start that it worked?
but, I don't understand what you mean. nothing is replacing ob_start(). output buffering is not needed to send headers. output buffering stops all output from going to the browser until you tell it to. this shouldn't be used as a way to get around having to send headers before output, though.
Why isn't it logging out?
possibly because you're trying to set the value of the cookie to a constant that doesn't exist (you need to use strings, as I've mentioned before). this may or may not be a problem.
gilgalbiblewhee
Apr 18th, 2010, 04:34 PM
.. you can't just "include it." it's an example of the logic behind displaying errors. it isn't something that will just work for you. you'd need to apply it to work for your situation.
but, I don't understand what you mean. nothing is replacing ob_start(). output buffering is not needed to send headers. output buffering stops all output from going to the browser until you tell it to. this shouldn't be used as a way to get around having to send headers before output, though.
possibly because you're trying to set the value of the cookie to a constant that doesn't exist (you need to use strings, as I've mentioned before). this may or may not be a problem.
Ok the first part didn't work when I enserted the errors:
index.php
session_start();
include("dbconnection.php");
//say goodbye to magic_quotes_gpc! no false security.
/*
$errors = array();
if($_SERVER['REQUEST_METHOD'] == "POST"){
if(empty($_POST['username'])){
$errors[] = "username was empty";
}
if(empty($_POST['password'])){
$errors[] = "password was empty";
}
if(empty($_POST['email'])){
$errors[] = "e-mail was empty";
}
if(count($errors) == 0){*/
//fix magic_quotes_gpc() being on
if(get_magic_quotes_gpc()){
foreach($_GET as $k => $v){
$_GET[$k] = stripslashes($v);
}
foreach($_POST as $k => $v){
$_POST[$k] = stripslashes($v);
}
foreach($_COOKIE as $k => $v){
$_COOKIE[$k] = stripslashes($v);
}
}
//Checks if there is a login cookie
if(isset($_COOKIE['ID_my_site'])){ //if there is, it logs you in and directs you to the members page
$myusername = $_COOKIE['ID_my_site'];
$pass = $_COOKIE['Key_my_site'];
$admin = $_COOKIE['Admin_my_site'];
$user = $_COOKIE['User_my_site'];
$sql = "SELECT * FROM ";
if($admin=="yes"){
$sql .= $dbTable2;
}else{
$sql .= $dbTable;
}
$sql .= " WHERE username = '".mysql_real_escape_string($myusername)."'";
$check = mysql_query($sql)or die(mysql_error());
while($info = mysql_fetch_array( $check )){
if($pass == $info['password']){
$writeusername = "Welcome ".$myusername."! <br />Visit your <a href=\"login/member.php\">member's stat</a> <br /><a href=\"login/logout.php\">Logout</a>";
}
}
}
//variable to keep track of whether to show the user the login form or not
$showlogin = true; //we show the form by default, -unless- we know they have logged in
//if the login form is submitted
if (isset($_POST['submit'])){ // if form has been submitted
if(!$_POST['username'] || !$_POST['pass']) {// makes sure they filled it in
$writeemptyfield = "<tr><td colspan=\"2\" style=\"text-align: left; color: red;\">You did not fill in a required field.</td></tr>";
}// checks it against the database
$_POST['email'] = mysql_real_escape_string($_POST['email']);
$db['username'] = mysql_real_escape_string($_POST['username']);
$sql = "SELECT * FROM ";
if($admin=="yes"){
$sql .= $dbTable2;
}else{
$sql .= $dbTable;
}
$sql .= " WHERE username = '".$db['username']."'";
$check = mysql_query($sql) or die(mysql_error());
//Gives error if user dosen't exist
$check2 = mysql_num_rows($check);
if ($check2 == 0) {
$writeusernoexist = "<tr><td colspan=\"2\" style=\"text-align: left; color: red;\">That user does not exist in our database.</td></tr>";
}
while($info = mysql_fetch_array( $check )){
$_POST['pass'] = md5($_POST['pass']);
//gives error if the password is wrong
if ($_POST['pass'] != $info['password']){
$writewrongpassword = "<tr><td colspan=\"2\" style=\"text-align: left; color: red;\">Incorrect password, please try again.</td></tr>";
}else{
// if login is ok then we add a cookie
$hour = time() + 3600;
setcookie("ID_my_site", $_POST['username'], $hour);
setcookie("Key_my_site", $_POST['pass'], $hour);
//they are logged in. no need to show the login form
$showlogin = false;
if($_POST["admin"]=="yes"){
setcookie("Admin_my_site", $_POST['admin'], $hour);
}else{
setcookie("User_my_site", $_POST['admin'], $hour);
}
header("Location: ../index.php");
}
}
}
/* }
}*/
$_SESSION['logged_in'] = 1;
?>
I don't understand what's missing in this logout script? It's redirecting back to the index page where you have the script above.
logout.php
<?php
//ob_start();
include("dbconnection.php");
$past = time() - 100;
//this makes the time in the past to destroy the cookie
setcookie("ID_my_site", gone, $past);
setcookie("Key_my_site", gone, $past);
setcookie("Admin_my_site", gone, $past);
header("Location: ../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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Logout</title>
</head>
<body>
<?php
?>
</body>
</html>
kows
Apr 18th, 2010, 11:26 PM
you didn't even change anything :/
possibly because you're trying to set the value of the cookie to a constant that doesn't exist (you need to use strings, as I've mentioned before). this may or may not be a problem.
this is the code that needs to change from using constants to "strings".
setcookie("ID_my_site", gone, $past);
setcookie("Key_my_site", gone, $past);
setcookie("Admin_my_site", gone, $past);
as for the $errors thing not working -- take it one step at a time. if you don't understand it, don't just throw it into your script and hope it works. it won't. I tried to tell you it was simply an example of a concept; it is not something you could actually use in your script. don't worry about that for now.
gilgalbiblewhee
Apr 19th, 2010, 04:50 AM
you didn't even change anything :/
setcookie("ID_my_site", gone, $past);
setcookie("Key_my_site", gone, $past);
setcookie("Admin_my_site", gone, $past);
How?
setcookie("ID_my_site", "gone", $past);
setcookie("Key_my_site", "gone", $past);
setcookie("Admin_my_site", "gone", $past);
You mean like that?
kows
Apr 19th, 2010, 08:02 AM
yes.
gilgalbiblewhee
Apr 19th, 2010, 03:46 PM
yes.
Didn't work.
penagate
Apr 19th, 2010, 11:08 PM
Your script should end after transmitting the Location header. There is no point in sending a response body as well as a redirection header.
The Location header must be an absolute URL.
<?php
# ...
header('HTTP/1.1 303 See Other');
header('Location: http://example.com/index.php');
?>
You are making it difficult for us to assist you because your responses (such as "Didn't work") are unhelpful. If it does not work, tell us exactly what happens and what you expect to happen instead.
kows
Apr 19th, 2010, 11:09 PM
are you including the logout page in another page, or anything? I don't see any reason for it to not be working. the only thing I can think of offhand is that the domain might be changing (from www.domain.com to domain.com, for example) and this may be causing problems because you're not specifying a domain when you set your cookies. this would mean that some of your links are linking to another subdomain under the same domain name. but it also seems like this may not be the case.
and also what penagate said about the location header!
gilgalbiblewhee
Apr 19th, 2010, 11:22 PM
Your script should end after transmitting the Location header. There is no point in sending a response body as well as a redirection header.
The Location header must be an absolute URL.
<?php
# ...
header('HTTP/1.1 303 See Other');
header('Location: http://example.com/index.php');
?>
You are making it difficult for us to assist you because your responses (such as "Didn't work") are unhelpful. If it does not work, tell us exactly what happens and what you expect to happen instead.
Oh I see. The logout page is a different page. I thought you would understand when you read the script wrapped with the html tags. What it does is the link is a new page and after logging out redirects to the main index page. But the main index page shows logged in after I attempt to log out.
penagate
Apr 19th, 2010, 11:58 PM
Are you using a session? If so, you need to destroy the session as well as delete other cookies.
menre
Apr 20th, 2010, 05:58 AM
There is alot to read and take in here. I finding the postings informative and interesting so far. I am working on a project at the moment and I was a bit worried when I read Kows quote below.
and lastly, I would suggest that for development you run PHP in a strict environment so that you can easily see any warnings and errors that might be thrown at you -- to not catch some of these would seem like you're running on a production environment.
Could you explain this a bit further please? I want to be sure that I am testing my work properly before I get to the deployment stage. I am using both Xampp and Mamp for my work at the moment and I will upload the final work to a live server later. Am I developing on a strict environment at the moment?
Menre
kows
Apr 20th, 2010, 08:27 AM
I doubt it -- but I've never used either of those and I don't know what they set up for the php.ini file when installing. to run in a strict environment is just to change the value of the error_reporting value in the php.ini file to show all errors. for example, this is what my development machine runs PHP with:
error_reporting = E_ALL | E_STRICT
this will display all errors (E_ALL) and allow PHP to show you run-time notices that will suggest any changes that should be made to your code to ensure forward-compatibility (E_STRICT).
for example, if I create this PHP file and try to run it:
<?php echo $myvar; ?>
I get the following message printed out:
Notice: Undefined variable: myvar in C:\webdev\php\strict.php on line 1
this happens because I haven't initialized my variable before using it, and E_ALL will let me know so.
gilgalbiblewhee
Apr 20th, 2010, 10:17 AM
Are you using a session? If so, you need to destroy the session as well as delete other cookies.
It's not working:
<?php
// Initialize the session.
// If you are using session_name("something"), don't forget it now!
session_start();
// Unset all of the session variables.
$_SESSION = array();
// If it's desired to kill the session, also delete the session cookie.
// Note: This will destroy the session, and not just the session data!
if (ini_get("session.use_cookies")) {
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]
);
}
// Finally, destroy the session.
session_destroy();
/*
session_start();
include("dbconnection.php");
$past = time() - 100;
//this makes the time in the past to destroy the cookie
setcookie("ID_my_site", "gone", $past);
setcookie("Key_my_site", "gone", $past);
setcookie("Admin_my_site", "gone", $past);
*/
header("Location: ../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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Logout</title>
</head>
<body>
<?php
?>
</body>
</html>
penagate
Apr 20th, 2010, 07:32 PM
Look,
Here is an example. I cannot make it much simpler than this. It consists of three files: index.php, login.php, and logout.php.
<?php
# index.php
session_start();
$logged_in = isset($_SESSION['logged_in']);
?><!DOCTYPE html>
<p>You are <?php if (!$logged_in) echo 'not '?>logged in.</p>
<?php if ($logged_in): ?>
<form action="logout.php" method="POST">
<input type="submit" value="Log out">
</form>
<?php else: ?>
<form action="login.php" method="POST">
<input type="submit" value="Log in">
</form>
<?php endif; ?>
<?php
# login.php
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
session_start();
$_SESSION['logged_in'] = true;
header('HTTP/1.1 303 See Other');
}
header('Location: http://'.$_SERVER['SERVER_NAME'].'/index.php');
?>
<?php
# logout.php
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
session_start();
session_destroy();
header('HTTP/1.1 303 See Other');
}
header('Location: http://'.$_SERVER['SERVER_NAME'].'/index.php');
?>
gilgalbiblewhee
Apr 20th, 2010, 08:50 PM
Look,
Here is an example. I cannot make it much simpler than this. It consists of three files: index.php, login.php, and logout.php.
<?php
# index.php
session_start();
$logged_in = isset($_SESSION['logged_in']);
?><!DOCTYPE html>
<p>You are <?php if (!$logged_in) echo 'not '?>logged in.</p>
<?php if ($logged_in): ?>
<form action="logout.php" method="POST">
<input type="submit" value="Log out">
</form>
<?php else: ?>
<form action="login.php" method="POST">
<input type="submit" value="Log in">
</form>
<?php endif; ?>
<?php
# login.php
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
session_start();
$_SESSION['logged_in'] = true;
header('HTTP/1.1 303 See Other');
}
header('Location: http://'.$_SERVER['SERVER_NAME'].'/index.php');
?>
<?php
# logout.php
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
session_start();
session_destroy();
header('HTTP/1.1 303 See Other');
}
header('Location: http://'.$_SERVER['SERVER_NAME'].'/index.php');
?>
I'm trying to understand. One's giving me one solution and another's giving me something else.
penagate
Apr 20th, 2010, 09:09 PM
I've no idea what you mean by that.
gilgalbiblewhee
Apr 20th, 2010, 09:53 PM
I've no idea what you mean by that.
What's this:
header('HTTP/1.1 303 See Other');
penagate
Apr 20th, 2010, 10:23 PM
The 303 status code instructs the user agent not to cache the response and to follow up the resource specified in the Location header. The reason for redirection after handling a POST request is to avoid the annoying "Do you want to resend the data" message that occurs if the user navigates back then forward or refreshes the page. The 303 redirection means that the page is not cached and so this problem does not occur. You should always use this approach to handling posted data; if not, it is easy for the user to accidentally perform a POST action twice, which can have severe consequences (for example, if that action is to delete some data).
menre
Apr 21st, 2010, 03:58 AM
Maybe I am running my work in a none strict environment. I followed your explanation to create and run a file, but the error message that I had expected was not displayed. I tried to echo a variable that I did not define and intialize. I was expecting an error message to occure at run time, but none and my other code was printed out successfully. Or am I doing something wrong? In the XAMPP environment that I am working in, I cannot find the php.ini file.
You can see my code below.
<html>
<head>
<title>Modern Day car dealers</title>
</head>
<body>
<?php
echo "<p>Welcome to Modern Day car dealers!</p>";
?>
<?php
$carsInStock = array("Honda", "Volvo", "Ford", "Toyota");
$prices = array("$23,000", "$34,000", "$36,000", "$22,000");
echo "At Modern Day car dealers, a brand new" . " " . "$carsInStock[3]" . " " .
" car costs only" . " " . "$prices[3].";
echo "<br />";
echo "$decoration"; //I was expecting an error here as it was never declared
?>
<?php echo $myvar; ?> //I lifted this from your post and was also expecting an error
</body>
</html>
When I run the code above, I get the output below.
Welcome to Modern Day car dealers!
At Modern Day car dealers, a brand new Toyota car costs only $22,000.
kows
Apr 21st, 2010, 12:08 PM
I don't know what XAMPP or any of those package setups use as defaults; you'll just have to find the php.ini file! display_errors and error_reporting needs to be set to display messages, that's all.
gilgalbiblewhee
Apr 21st, 2010, 12:30 PM
The 303 status code instructs the user agent not to cache the response and to follow up the resource specified in the Location header. The reason for redirection after handling a POST request is to avoid the annoying "Do you want to resend the data" message that occurs if the user navigates back then forward or refreshes the page. The 303 redirection means that the page is not cached and so this problem does not occur. You should always use this approach to handling posted data; if not, it is easy for the user to accidentally perform a POST action twice, which can have severe consequences (for example, if that action is to delete some data).
You're code does impress me. I'm wondering if all the if statements in my script necessary:
session_start();
include("dbconnection.php");
//say goodbye to magic_quotes_gpc! no false security.
/*
$errors = array();
if($_SERVER['REQUEST_METHOD'] == "POST"){
if(empty($_POST['username'])){
$errors[] = "username was empty";
}
if(empty($_POST['password'])){
$errors[] = "password was empty";
}
if(empty($_POST['email'])){
$errors[] = "e-mail was empty";
}
if(count($errors) == 0){*/
//fix magic_quotes_gpc() being on
if(get_magic_quotes_gpc()){
foreach($_GET as $k => $v){
$_GET[$k] = stripslashes($v);
}
foreach($_POST as $k => $v){
$_POST[$k] = stripslashes($v);
}
foreach($_COOKIE as $k => $v){
$_COOKIE[$k] = stripslashes($v);
}
}
//Checks if there is a login cookie
if(isset($_COOKIE['ID_my_site'])){ //if there is, it logs you in and directs you to the members page
$myusername = $_COOKIE['ID_my_site'];
$pass = $_COOKIE['Key_my_site'];
$admin = $_COOKIE['Admin_my_site'];
$user = $_COOKIE['User_my_site'];
$sql = "SELECT * FROM ";
if($admin=="yes"){
$sql .= $dbTable2;
}else{
$sql .= $dbTable;
}
$sql .= " WHERE username = '".mysql_real_escape_string($myusername)."'";
$check = mysql_query($sql)or die(mysql_error());
while($info = mysql_fetch_array( $check )){
if($pass == $info['password']){
$writeusername = "Welcome ".$myusername."! <br />Visit your <a href=\"login/member.php\">member's stat</a> <br /><a href=\"login/logout.php\">Logout</a>";
}
}
}
//variable to keep track of whether to show the user the login form or not
$showlogin = true; //we show the form by default, -unless- we know they have logged in
//if the login form is submitted
if (isset($_POST['submit'])){ // if form has been submitted
if(!$_POST['username'] || !$_POST['pass']) {// makes sure they filled it in
$writeemptyfield = "<tr><td colspan=\"2\" style=\"text-align: left; color: red;\">You did not fill in a required field.</td></tr>";
}// checks it against the database
$_POST['email'] = mysql_real_escape_string($_POST['email']);
$db['username'] = mysql_real_escape_string($_POST['username']);
$sql = "SELECT * FROM ";
if($admin=="yes"){
$sql .= $dbTable2;
}else{
$sql .= $dbTable;
}
$sql .= " WHERE username = '".$db['username']."'";
$check = mysql_query($sql) or die(mysql_error());
//Gives error if user dosen't exist
$check2 = mysql_num_rows($check);
if ($check2 == 0) {
$writeusernoexist = "<tr><td colspan=\"2\" style=\"text-align: left; color: red;\">That user does not exist in our database.</td></tr>";
}
while($info = mysql_fetch_array( $check )){
$_POST['pass'] = md5($_POST['pass']);
//gives error if the password is wrong
if ($_POST['pass'] != $info['password']){
$writewrongpassword = "<tr><td colspan=\"2\" style=\"text-align: left; color: red;\">Incorrect password, please try again.</td></tr>";
}else{
// if login is ok then we add a cookie
$hour = time() + 3600;
setcookie("ID_my_site", $_POST['username'], $hour);
setcookie("Key_my_site", $_POST['pass'], $hour);
//they are logged in. no need to show the login form
$showlogin = false;
if($_POST["admin"]=="yes"){
setcookie("Admin_my_site", $_POST['admin'], $hour);
}else{
setcookie("User_my_site", $_POST['admin'], $hour);
}
header("Location: ../index.php");
}
}
}
/* }
}*/
$_SESSION['logged_in'] = 1;
SambaNeko
Apr 21st, 2010, 12:41 PM
menre - the php.ini file for xampp is located in the "php" directory, in your xampp root (so "C:\xampp\php\", if you installed in the default location on Windows). The file even outlines suggestions for you:
; Common Values:
; E_ALL & ~E_NOTICE (Show all errors, except for notices and coding standards warnings.)
; E_ALL & ~E_NOTICE | E_STRICT (Show all errors, except for notices)
; E_COMPILE_ERROR|E_RECOVERABLE_ERROR|E_ERROR|E_CORE_ERROR (Show only errors)
; E_ALL | E_STRICT (Show all errors, warnings and notices including coding standards.)
; Default Value: E_ALL & ~E_NOTICE
; Development Value: E_ALL | E_STRICT
; Production Value: E_ALL & ~E_DEPRECATED
; http://php.net/error-reporting
error_reporting = E_ALL & ~E_NOTICE & ~E_DEPRECATED
Only the last line (the one that's not commented out by a semicolon) is the actual setting.
kows
Apr 22nd, 2010, 01:24 AM
I'm wondering if all the if statements in my script necessary
no, most of them aren't. however, if the if statements in your code are not the problem (which they aren't), then I believe they're serving their purpose. it's up to you to find a more logical, efficient way to handle your data afterward (of course, we're here to provide help with that in the future, too).
gilgalbiblewhee
Apr 22nd, 2010, 01:56 AM
no, most of them aren't. however, if the if statements in your code are not the problem (which they aren't), then I believe they're serving their purpose. it's up to you to find a more logical, efficient way to handle your data afterward (of course, we're here to provide help with that in the future, too).
I'm still stuck. Penagate gave the examples. The examples alone work but when I paste my code in it, it doesn't work.
Penagate's version:
<?php
# index.php
session_start();
$logged_in = isset($_SESSION['logged_in']);
?>
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Logout</title>
</head>
<body>
<p>You are <?php if (!$logged_in) echo 'not '?>logged in.</p>
<?php if ($logged_in): ?>
<form action="logout.php" method="POST">
<input type="submit" value="Log out">
</form>
<?php else: ?>
<form action="login.php" method="POST">
<input type="submit" value="Log in">
</form>
<?php endif; ?>
</body>
</html>
<?php
# login.php
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
session_start();
$_SESSION['logged_in'] = true;
header('HTTP/1.1 303 See Other');
}
header('Location: index.php');
?>
<?php
# logout.php
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
session_start();
session_destroy();
header('HTTP/1.1 303 See Other');
}
header('Location: 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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Logout</title>
</head>
<body>
<?php
?>
</body>
</html>
Now my version:
<?php
# index.php
session_start();
$logged_in = isset($_SESSION['logged_in']);
?>
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Logout</title>
</head>
<body>
<p>You are <?php if (!$logged_in) echo 'not '?>logged in.</p>
<?php if ($logged_in): ?>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="POST">
<span style="float: left; text-align: left; padding: 5px 5px 5px 5px;">
Welcome <span id="myusername"><?php echo $myusername; ?> </span>!<br />
Visit your <a style="text-decoration: none;" href="login/member.php" onmouseover="this.style.textDecoration='underline';" onmouseout="this.style.textDecoration='none';" >member's stat</a><br />
<a style="text-decoration: none;" href="login/logout.php" onmouseover="this.style.textDecoration='underline';" onmouseout="this.style.textDecoration='none';" >Logout</a>
</span>
</form>
<?php else: ?>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="POST">
<table border="0">
<tr>
<td>Administrator:</td><td><input type="checkbox" id="adminid" name="admin" style="float: left; border: 1px solid #7C7C7C; background-color: #7C7C7C;" value="no" onClick="if(this.value=='no'){this.value='yes'; document.getElementById('register').style.display = 'none';} else{this.value='no';document.getElementById('register').style.display = 'block';};" /></td>
</tr>
<?php echo $writeemptyfield; ?>
<?php echo $writeusernoexist; ?>
<tr>
<td>Username:</td>
<td><input type="text" name="username" id="username" style="float: left; border: 1px solid #7C7C7C; font: 9px verdana, geneva, lucida, 'lucida grande', arial, helvetica, sans-serif; width: 100px; height: 15px;" value="User Name" onBlur="if (this.value == '') this.value = 'User Name';" onFocus="if (this.value == 'User Name') this.value = '';" /></td>
</tr>
<?php echo $writewrongpassword; ?>
<tr>
<td>Password:</td><td><input type="password" style="float: left; border: 1px solid #7C7C7C; font: 9pt verdana, geneva, lucida, 'lucida grande', arial, helvetica, sans-serif; width: 100px; height: 15px;" name="pass" id="pass" /></td></tr>
<tr>
<td><a id="register" href="login/register.php" style="float: left; display: block; background-color: #7C7C7C; text-align: left; padding: 0px 0px 0px 5px; width: 80px; height: 20px; text-decoration: none; color: #ffffff; border: 1px solid #7C7C7C; font-weight: bold;" onMouseOver="this.style.backgroundColor='#B4B3A9'" onMouseOut="this.style.backgroundColor='#7C7C7C'">Register</a></td><td align="right"><input type="submit" style="float: left; border: 1px solid #7C7C7C; background-color: #7C7C7C; color: #ffffff; font: 9pt verdana, geneva, lucida, 'lucida grande', arial, helvetica, sans-serif; font-weight: bold; width: 100px; height: 20px;" name="submit" onMouseOver="this.style.backgroundColor='#B4B3A9'" onMouseOut="this.style.backgroundColor='#7C7C7C'" value="Login" /></td>
</tr>
</table>
</form>
<?php endif; ?>
</body>
</html>
The login's the same. And the logout I haven't looked at yet. It's not logging in. It's showing that I haven't logged in.
kows
Apr 22nd, 2010, 02:05 AM
uhh.. that would be because you're missing the most crucial part of that code -- the code that logs you in:
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$_SESSION['logged_in'] = true;
}
your script is posting to $_SERVER['PHP_SELF'] (which means itself) -- if you are not setting $_SESSION['logged_in'] within that script (which unless you cut it out, you're not), then you're never going to get logged in.
penagate
Apr 22nd, 2010, 02:08 AM
Well, you are posting to the same location, but you don't have any code which handles the post request. Just change the form target to login.php.
gilgalbiblewhee
Apr 22nd, 2010, 10:25 AM
Well, you are posting to the same location, but you don't have any code which handles the post request. Just change the form target to login.php.
Ok. That's right. What about the logout then?
<?php
# logout.php
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
session_start();
session_destroy();
header('HTTP/1.1 303 See Other');
}
header('Location: 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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Logout</title>
</head>
<body>
<?php
?>
</body>
</html>It's not logging out.
Also if I'm going to use the checking in the db table then I will have to copy paste the following within the if statement if ($_SERVER['REQUEST_METHOD'] == 'POST'){ of login.php, right?
if($_SERVER['REQUEST_METHOD'] == "POST"){
if(empty($_POST['username'])){
$errors[] = "username was empty";
}
if(empty($_POST['password'])){
$errors[] = "password was empty";
}
if(empty($_POST['email'])){
$errors[] = "e-mail was empty";
}
if(count($errors) == 0){*/
//fix magic_quotes_gpc() being on
if(get_magic_quotes_gpc()){
foreach($_GET as $k => $v){
$_GET[$k] = stripslashes($v);
}
foreach($_POST as $k => $v){
$_POST[$k] = stripslashes($v);
}
foreach($_COOKIE as $k => $v){
$_COOKIE[$k] = stripslashes($v);
}
}
//Checks if there is a login cookie
if(isset($_COOKIE['ID_my_site'])){ //if there is, it logs you in and directs you to the members page
$myusername = $_COOKIE['ID_my_site'];
$pass = $_COOKIE['Key_my_site'];
$admin = $_COOKIE['Admin_my_site'];
$user = $_COOKIE['User_my_site'];
$sql = "SELECT * FROM ";
if($admin=="yes"){
$sql .= $dbTable2;
}else{
$sql .= $dbTable;
}
$sql .= " WHERE username = '".mysql_real_escape_string($myusername)."'";
$check = mysql_query($sql)or die(mysql_error());
while($info = mysql_fetch_array( $check )){
if($pass == $info['password']){
$writeusername = "Welcome ".$myusername."! <br />Visit your <a href=\"login/member.php\">member's stat</a> <br /><a href=\"login/logout.php\">Logout</a>";
}
}
}
//variable to keep track of whether to show the user the login form or not
$showlogin = true; //we show the form by default, -unless- we know they have logged in
//if the login form is submitted
if (isset($_POST['submit'])){ // if form has been submitted
if(!$_POST['username'] || !$_POST['pass']) {// makes sure they filled it in
$writeemptyfield = "<tr><td colspan=\"2\" style=\"text-align: left; color: red;\">You did not fill in a required field.</td></tr>";
}// checks it against the database
$_POST['email'] = mysql_real_escape_string($_POST['email']);
$db['username'] = mysql_real_escape_string($_POST['username']);
$sql = "SELECT * FROM ";
if($admin=="yes"){
$sql .= $dbTable2;
}else{
$sql .= $dbTable;
}
$sql .= " WHERE username = '".$db['username']."'";
$check = mysql_query($sql) or die(mysql_error());
//Gives error if user dosen't exist
$check2 = mysql_num_rows($check);
if ($check2 == 0) {
$writeusernoexist = "<tr><td colspan=\"2\" style=\"text-align: left; color: red;\">That user does not exist in our database.</td></tr>";
}
while($info = mysql_fetch_array( $check )){
$_POST['pass'] = md5($_POST['pass']);
//gives error if the password is wrong
if ($_POST['pass'] != $info['password']){
$writewrongpassword = "<tr><td colspan=\"2\" style=\"text-align: left; color: red;\">Incorrect password, please try again.</td></tr>";
}else{
// if login is ok then we add a cookie
$hour = time() + 3600;
setcookie("ID_my_site", $_POST['username'], $hour);
setcookie("Key_my_site", $_POST['pass'], $hour);
//they are logged in. no need to show the login form
$showlogin = false;
if($_POST["admin"]=="yes"){
setcookie("Admin_my_site", $_POST['admin'], $hour);
}else{
setcookie("User_my_site", $_POST['admin'], $hour);
}
header("Location: login/login.php");
}
}
}
/* }
}*/
penagate
Apr 22nd, 2010, 07:07 PM
Why have you put that HTML into the log out page? As I said before, you do not need any response body after the redirection headers.
Are you POSTing the log out request as I did in my example?
Also if I'm going to use the checking in the db table then I will have to copy paste the following within the if statement
Yes, correct.
gilgalbiblewhee
Apr 22nd, 2010, 09:10 PM
Why have you put that HTML into the log out page? As I said before, you do not need any response body after the redirection headers.
Are you POSTing the log out request as I did in my example?
Yes, correct.
Aaaaahh! I learn new things every day. I was using the <a> tag to try to log out.
penagate
Apr 22nd, 2010, 09:22 PM
As a rule of thumb, use GET for any action which does not change state and POST for those which do.
You should be able to GET all links on a page without consequence.
gilgalbiblewhee
Apr 22nd, 2010, 09:26 PM
As a rule of thumb, use GET for any action which does not change state and POST for those which do.
You should be able to GET all links on a page without consequence.
Something tells me this is not right:
<?php
# index.php
session_start();
$logged_in = isset($_SESSION['logged_in']);
include("../dbconnection.php");
//say goodbye to magic_quotes_gpc! no false security.
$errors = array();
if($_SERVER['REQUEST_METHOD'] == "POST"){
if(empty($_POST['username'])){
$errors[] = "username was empty";
}
if(empty($_POST['password'])){
$errors[] = "password was empty";
}
if(empty($_POST['email'])){
$errors[] = "e-mail was empty";
}
if(count($errors) == 0){
//fix magic_quotes_gpc() being on
if(get_magic_quotes_gpc()){
foreach($_GET as $k => $v){
$_GET[$k] = stripslashes($v);
}
foreach($_POST as $k => $v){
$_POST[$k] = stripslashes($v);
}
foreach($_COOKIE as $k => $v){
$_COOKIE[$k] = stripslashes($v);
}
}
//Checks if there is a login cookie
if(isset($_COOKIE['ID_my_site'])){ //if there is, it logs you in and directs you to the members page
$myusername = $_COOKIE['ID_my_site'];
$pass = $_COOKIE['Key_my_site'];
$admin = $_COOKIE['Admin_my_site'];
$user = $_COOKIE['User_my_site'];
$sql = "SELECT * FROM ";
if($admin=="yes"){
$sql .= $dbTable2;
}else{
$sql .= $dbTable;
}
$sql .= " WHERE username = '".mysql_real_escape_string($myusername)."'";
$check = mysql_query($sql)or die(mysql_error());
while($info = mysql_fetch_array( $check )){
if($pass == $info['password']){
$writeusername = "Welcome ".$myusername."! <br />Visit your <a href=\"login/member.php\">member's stat</a> <br /><a href=\"login/logout.php\">Logout</a>";
}
}
}
//variable to keep track of whether to show the user the login form or not
$showlogin = true; //we show the form by default, -unless- we know they have logged in
//if the login form is submitted
if (isset($_POST['submit'])){ // if form has been submitted
if(!$_POST['username'] || !$_POST['pass']) {// makes sure they filled it in
$writeemptyfield = "<tr><td colspan=\"2\" style=\"text-align: left; color: red;\">You did not fill in a required field.</td></tr>";
}// checks it against the database
$_POST['email'] = mysql_real_escape_string($_POST['email']);
$db['username'] = mysql_real_escape_string($_POST['username']);
$sql = "SELECT * FROM ";
if($admin=="yes"){
$sql .= $dbTable2;
}else{
$sql .= $dbTable;
}
$sql .= " WHERE username = '".$db['username']."'";
$check = mysql_query($sql) or die(mysql_error());
//Gives error if user dosen't exist
$check2 = mysql_num_rows($check);
if ($check2 == 0) {
$writeusernoexist = "<tr><td colspan=\"2\" style=\"text-align: left; color: red;\">That user does not exist in our database.</td></tr>";
}
while($info = mysql_fetch_array( $check )){
$_POST['pass'] = md5($_POST['pass']);
//gives error if the password is wrong
if ($_POST['pass'] != $info['password']){
$writewrongpassword = "<tr><td colspan=\"2\" style=\"text-align: left; color: red;\">Incorrect password, please try again.</td></tr>";
}else{
// if login is ok then we add a cookie
$hour = time() + 3600;
setcookie("ID_my_site", $_POST['username'], $hour);
setcookie("Key_my_site", $_POST['pass'], $hour);
//they are logged in. no need to show the login form
$showlogin = false;
if($_POST["admin"]=="yes"){
setcookie("Admin_my_site", $_POST['admin'], $hour);
}else{
setcookie("User_my_site", $_POST['admin'], $hour);
}
header("Location: login/login.php");
}
}
}
}
}
//$_SESSION['logged_in'] = 1;
?>
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Login</title>
</head>
<body>
<?php if ($logged_in): ?>
<form action="<?php echo "logout.php";//$_SERVER['PHP_SELF'];?>" method="POST">
<span style="float: left; text-align: left; padding: 5px 5px 5px 5px;">
Welcome <span id="myusername"><?php echo $myusername; ?> </span>!<br />
Visit your <a style="text-decoration: none;" href="login/member.php" onmouseover="this.style.textDecoration='underline';" onmouseout="this.style.textDecoration='none';" >member's stat</a><br />
<input type="submit" style="float: left; border: 1px solid #7C7C7C; background-color: #7C7C7C; color: #ffffff; font: 9pt verdana, geneva, lucida, 'lucida grande', arial, helvetica, sans-serif; font-weight: bold; width: 100px; height: 20px;" name="submit" onMouseOver="this.style.backgroundColor='#B4B3A9'" onMouseOut="this.style.backgroundColor='#7C7C7C'" value="Logout" />
</span>
</form>
<?php else: ?>
<form action="<?php echo "login.php";//$_SERVER['PHP_SELF'];?>" method="POST">
<table border="0">
<tr>
<td>Administrator:</td><td><input type="checkbox" id="adminid" name="admin" style="float: left; border: 1px solid #7C7C7C; background-color: #7C7C7C;" value="no" onClick="if(this.value=='no'){this.value='yes'; document.getElementById('register').style.display = 'none';} else{this.value='no';document.getElementById('register').style.display = 'block';};" /></td>
</tr>
<?php echo $writeemptyfield; ?>
<?php echo $writeusernoexist; ?>
<tr>
<td>Username:</td>
<td><input type="text" name="username" id="username" style="float: left; border: 1px solid #7C7C7C; font: 9px verdana, geneva, lucida, 'lucida grande', arial, helvetica, sans-serif; width: 100px; height: 15px;" value="User Name" onBlur="if (this.value == '') this.value = 'User Name';" onFocus="if (this.value == 'User Name') this.value = '';" /></td>
</tr>
<?php echo $writewrongpassword; ?>
<tr>
<td>Password:</td><td><input type="password" style="float: left; border: 1px solid #7C7C7C; font: 9pt verdana, geneva, lucida, 'lucida grande', arial, helvetica, sans-serif; width: 100px; height: 15px;" name="pass" id="pass" /></td></tr>
<tr>
<td><a id="register" href="login/register.php" style="float: left; display: block; background-color: #7C7C7C; text-align: left; padding: 0px 0px 0px 5px; width: 80px; height: 20px; text-decoration: none; color: #ffffff; border: 1px solid #7C7C7C; font-weight: bold;" onMouseOver="this.style.backgroundColor='#B4B3A9'" onMouseOut="this.style.backgroundColor='#7C7C7C'">Register</a></td><td align="right"><input type="submit" style="float: left; border: 1px solid #7C7C7C; background-color: #7C7C7C; color: #ffffff; font: 9pt verdana, geneva, lucida, 'lucida grande', arial, helvetica, sans-serif; font-weight: bold; width: 100px; height: 20px;" name="submit" onMouseOver="this.style.backgroundColor='#B4B3A9'" onMouseOut="this.style.backgroundColor='#7C7C7C'" value="Login" /></td>
</tr>
</table>
</form>
<?php endif; ?>
</body>
</html>
Maybe the top part should be in the login? But then what should be added in the index.php?
penagate
Apr 22nd, 2010, 10:10 PM
It looks fine to me. What do you feel is not right about it?
The query code and the HTML could be tidied a little (starting by separating the CSS into its own file) but they are not "wrong" per se.
gilgalbiblewhee
Apr 22nd, 2010, 10:56 PM
It looks fine to me. What do you feel is not right about it?
The query code and the HTML could be tidied a little (starting by separating the CSS into its own file) but they are not "wrong" per se.
It doesn't show the username:
Welcome !
Also when I put a non-existent username it logs in.
penagate
Apr 22nd, 2010, 11:24 PM
Ah, I didn't read the code carefully enough.
Your login processing logic should be in login.php. The log in example I gave you does not take any parameters.
Did you write that code?
menre
Apr 23rd, 2010, 06:19 AM
Thanks guys. I have now changed the original php.ini file and it shows errors on a page. The old file has the code below.
Common Values:
; E_ALL & ~E_NOTICE (Show all errors, except for notices and coding standards warnings.)
; E_ALL & ~E_NOTICE | E_STRICT (Show all errors, except for notices)
; E_COMPILE_ERROR|E_RECOVERABLE_ERROR|E_ERROR|E_CORE_ERROR (Show only errors)
; E_ALL | E_STRICT (Show all errors, warnings and notices including coding standards.)
; Default Value: E_ALL & ~E_NOTICE
; Development Value: E_ALL | E_STRICT
; Production Value: E_ALL & ~E_DEPRECATED
; http://php.net/error-reporting
error_reporting = E_ALL & ~E_NOTICE & ~E_DEPRECATED
After changing it, the new file looks like what is shown below.
Common Values:
; E_ALL & ~E_NOTICE (Show all errors, except for notices and coding standards warnings.)
; E_ALL & ~E_NOTICE | E_STRICT (Show all errors, except for notices)
; E_COMPILE_ERROR|E_RECOVERABLE_ERROR|E_ERROR|E_CORE_ERROR (Show only errors)
; E_ALL | E_STRICT (Show all errors, warnings and notices including coding standards.)
; Default Value: E_ALL & ~E_NOTICE
; Development Value: E_ALL | E_STRICT
; Production Value: E_ALL & ~E_DEPRECATED
; http://php.net/error-reporting
error_reporting = E_ALL | E_STRICT
And when I previewed my work below,
<html>
<head>
<title>Modern Day car dealers</title>
</head>
<body>
<?php
echo "<p>Welcome to Modern Day car dealers!</p>";
?>
<?php
$carsInStock = array("Honda", "Volvo", "Ford", "Toyota");
$prices = array("$23,000", "$34,000", "$36,000", "$22,000");
echo "At Modern Day car dealers, a brand new" . " " . "$carsInStock[3]" .
" " . " car costs only" . " " . "$prices[3].";
echo "<br />";
echo "$decoration";
?>
<?php echo $myvar; ?>
</body>
</html>
it shows the information below.
Welcome to Modern Day car dealers!
At Modern Day car dealers, a brand new Toyota car costs only $22,000.
Notice: Undefined variable: decoration in C:\xampp\htdocs\menre\md.php on line 19
Notice: Undefined variable: myvar in C:\xampp\htdocs\menre\md.php on line 23
gilgalbiblewhee
Apr 23rd, 2010, 03:19 PM
Ah, I didn't read the code carefully enough.
Your login processing logic should be in login.php. The log in example I gave you does not take any parameters.
Did you write that code?
What do you mean write? I used your method with 3 php files: login.php, logout.php and index.php.
I think the checking the $_POST[] should be in the login.php. But then I'm guessing that the index.php page needs to read cookies which the login.php has set right?
<?php
# index.php
session_start();
$logged_in = isset($_SESSION['logged_in']);
include("../dbconnection.php");
//say goodbye to magic_quotes_gpc! no false security.
$errors = array();
if($_SERVER['REQUEST_METHOD'] == "POST"){
if(empty($_POST['username'])){
$errors[] = "username was empty";
}
if(empty($_POST['password'])){
$errors[] = "password was empty";
}
if(empty($_POST['email'])){
$errors[] = "e-mail was empty";
}
if(count($errors) == 0){
//fix magic_quotes_gpc() being on
if(get_magic_quotes_gpc()){
foreach($_GET as $k => $v){
$_GET[$k] = stripslashes($v);
}
foreach($_POST as $k => $v){
$_POST[$k] = stripslashes($v);
}
foreach($_COOKIE as $k => $v){
$_COOKIE[$k] = stripslashes($v);
}
}
//Checks if there is a login cookie
if(isset($_COOKIE['ID_my_site'])){ //if there is, it logs you in and directs you to the members page
$myusername = $_COOKIE['ID_my_site'];
$pass = $_COOKIE['Key_my_site'];
$admin = $_COOKIE['Admin_my_site'];
$user = $_COOKIE['User_my_site'];
$sql = "SELECT * FROM ";
if($admin=="yes"){
$sql .= $dbTable2;
}else{
$sql .= $dbTable;
}
$sql .= " WHERE username = '".mysql_real_escape_string($myusername)."'";
$check = mysql_query($sql)or die(mysql_error());
while($info = mysql_fetch_array( $check )){
if($pass == $info['password']){
$writeusername = "Welcome ".$myusername."! <br />Visit your <a href=\"member.php\">member's stat</a> <br /><a href=\"login/logout.php\">Logout</a>";
}
}
}
//variable to keep track of whether to show the user the login form or not
$showlogin = true; //we show the form by default, -unless- we know they have logged in
//if the login form is submitted
if (isset($_POST['submit'])){ // if form has been submitted
if(!$_POST['username'] || !$_POST['pass']) {// makes sure they filled it in
$writeemptyfield = "<tr><td colspan=\"2\" style=\"text-align: left; color: red;\">You did not fill in a required field.</td></tr>";
}// checks it against the database
$_POST['email'] = mysql_real_escape_string($_POST['email']);
$db['username'] = mysql_real_escape_string($_POST['username']);
$sql = "SELECT * FROM ";
if($admin=="yes"){
$sql .= $dbTable2;
}else{
$sql .= $dbTable;
}
$sql .= " WHERE username = '".$db['username']."'";
$check = mysql_query($sql) or die(mysql_error());
//Gives error if user dosen't exist
$check2 = mysql_num_rows($check);
if ($check2 == 0) {
$writeusernoexist = "<tr><td colspan=\"2\" style=\"text-align: left; color: red;\">That user does not exist in our database.</td></tr>";
}
while($info = mysql_fetch_array( $check )){
$_POST['pass'] = md5($_POST['pass']);
//gives error if the password is wrong
if ($_POST['pass'] != $info['password']){
$writewrongpassword = "<tr><td colspan=\"2\" style=\"text-align: left; color: red;\">Incorrect password, please try again.</td></tr>";
}else{
// if login is ok then we add a cookie
$hour = time() + 3600;
setcookie("ID_my_site", $_POST['username'], $hour);
setcookie("Key_my_site", $_POST['pass'], $hour);
//they are logged in. no need to show the login form
$showlogin = false;
if($_POST["admin"]=="yes"){
setcookie("Admin_my_site", $_POST['admin'], $hour);
}else{
setcookie("User_my_site", $_POST['admin'], $hour);
}
header("Location: login.php");
}
}
}
}
}
//$_SESSION['logged_in'] = 1;
?>
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Login</title>
</head>
<body>
<?php if ($logged_in): ?>
<form action="<?php echo "logout.php";//$_SERVER['PHP_SELF'];?>" method="POST">
<span style="float: left; text-align: left; padding: 5px 5px 5px 5px;">
Welcome <span id="myusername"><?php echo $myusername; ?> </span>!<br />
Visit your <a style="text-decoration: none;" href="member.php" onmouseover="this.style.textDecoration='underline';" onmouseout="this.style.textDecoration='none';" >member's stat</a><br />
<input type="submit" style="float: left; border: 1px solid #7C7C7C; background-color: #7C7C7C; color: #ffffff; font: 9pt verdana, geneva, lucida, 'lucida grande', arial, helvetica, sans-serif; font-weight: bold; width: 100px; height: 20px;" name="submit" onMouseOver="this.style.backgroundColor='#B4B3A9'" onMouseOut="this.style.backgroundColor='#7C7C7C'" value="Logout" />
</span>
</form>
<?php else: ?>
<form action="<?php echo "login.php";//$_SERVER['PHP_SELF'];?>" method="POST">
<table border="0">
<tr>
<td>Administrator:</td><td><input type="checkbox" id="adminid" name="admin" style="float: left; border: 1px solid #7C7C7C; background-color: #7C7C7C;" value="no" onClick="if(this.value=='no'){this.value='yes'; document.getElementById('register').style.display = 'none';} else{this.value='no';document.getElementById('register').style.display = 'block';};" /></td>
</tr>
<?php echo $writeemptyfield; ?>
<?php echo $writeusernoexist; ?>
<tr>
<td>Username:</td>
<td><input type="text" name="username" id="username" style="float: left; border: 1px solid #7C7C7C; font: 9px verdana, geneva, lucida, 'lucida grande', arial, helvetica, sans-serif; width: 100px; height: 15px;" value="User Name" onBlur="if (this.value == '') this.value = 'User Name';" onFocus="if (this.value == 'User Name') this.value = '';" /></td>
</tr>
<?php echo $writewrongpassword; ?>
<tr>
<td>Password:</td><td><input type="password" style="float: left; border: 1px solid #7C7C7C; font: 9pt verdana, geneva, lucida, 'lucida grande', arial, helvetica, sans-serif; width: 100px; height: 15px;" name="pass" id="pass" /></td></tr>
<tr>
<td><a id="register" href="login/register.php" style="float: left; display: block; background-color: #7C7C7C; text-align: left; padding: 0px 0px 0px 5px; width: 80px; height: 20px; text-decoration: none; color: #ffffff; border: 1px solid #7C7C7C; font-weight: bold;" onMouseOver="this.style.backgroundColor='#B4B3A9'" onMouseOut="this.style.backgroundColor='#7C7C7C'">Register</a></td><td align="right"><input type="submit" style="float: left; border: 1px solid #7C7C7C; background-color: #7C7C7C; color: #ffffff; font: 9pt verdana, geneva, lucida, 'lucida grande', arial, helvetica, sans-serif; font-weight: bold; width: 100px; height: 20px;" name="submit" onMouseOver="this.style.backgroundColor='#B4B3A9'" onMouseOut="this.style.backgroundColor='#7C7C7C'" value="Login" /></td>
</tr>
</table>
</form>
<?php endif; ?>
</body>
</html>
<?php
# login.php
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
session_start();
$_SESSION['logged_in'] = true;
header('HTTP/1.1 303 See Other');
}
header('Location: index.php');
?>
<?php
# logout.php
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
session_start();
session_destroy();
header('HTTP/1.1 303 See Other');
}
header('Location: index.php');
?>
gilgalbiblewhee
Apr 29th, 2010, 03:46 PM
What do you mean write? I used your method with 3 php files: login.php, logout.php and index.php.
I think the checking the $_POST[] should be in the login.php. But then I'm guessing that the index.php page needs to read cookies which the login.php has set right?
<?php
# index.php
session_start();
$logged_in = isset($_SESSION['logged_in']);
include("../dbconnection.php");
//say goodbye to magic_quotes_gpc! no false security.
$errors = array();
if($_SERVER['REQUEST_METHOD'] == "POST"){
if(empty($_POST['username'])){
$errors[] = "username was empty";
}
if(empty($_POST['password'])){
$errors[] = "password was empty";
}
if(empty($_POST['email'])){
$errors[] = "e-mail was empty";
}
if(count($errors) == 0){
//fix magic_quotes_gpc() being on
if(get_magic_quotes_gpc()){
foreach($_GET as $k => $v){
$_GET[$k] = stripslashes($v);
}
foreach($_POST as $k => $v){
$_POST[$k] = stripslashes($v);
}
foreach($_COOKIE as $k => $v){
$_COOKIE[$k] = stripslashes($v);
}
}
//Checks if there is a login cookie
if(isset($_COOKIE['ID_my_site'])){ //if there is, it logs you in and directs you to the members page
$myusername = $_COOKIE['ID_my_site'];
$pass = $_COOKIE['Key_my_site'];
$admin = $_COOKIE['Admin_my_site'];
$user = $_COOKIE['User_my_site'];
$sql = "SELECT * FROM ";
if($admin=="yes"){
$sql .= $dbTable2;
}else{
$sql .= $dbTable;
}
$sql .= " WHERE username = '".mysql_real_escape_string($myusername)."'";
$check = mysql_query($sql)or die(mysql_error());
while($info = mysql_fetch_array( $check )){
if($pass == $info['password']){
$writeusername = "Welcome ".$myusername."! <br />Visit your <a href=\"member.php\">member's stat</a> <br /><a href=\"login/logout.php\">Logout</a>";
}
}
}
//variable to keep track of whether to show the user the login form or not
$showlogin = true; //we show the form by default, -unless- we know they have logged in
//if the login form is submitted
if (isset($_POST['submit'])){ // if form has been submitted
if(!$_POST['username'] || !$_POST['pass']) {// makes sure they filled it in
$writeemptyfield = "<tr><td colspan=\"2\" style=\"text-align: left; color: red;\">You did not fill in a required field.</td></tr>";
}// checks it against the database
$_POST['email'] = mysql_real_escape_string($_POST['email']);
$db['username'] = mysql_real_escape_string($_POST['username']);
$sql = "SELECT * FROM ";
if($admin=="yes"){
$sql .= $dbTable2;
}else{
$sql .= $dbTable;
}
$sql .= " WHERE username = '".$db['username']."'";
$check = mysql_query($sql) or die(mysql_error());
//Gives error if user dosen't exist
$check2 = mysql_num_rows($check);
if ($check2 == 0) {
$writeusernoexist = "<tr><td colspan=\"2\" style=\"text-align: left; color: red;\">That user does not exist in our database.</td></tr>";
}
while($info = mysql_fetch_array( $check )){
$_POST['pass'] = md5($_POST['pass']);
//gives error if the password is wrong
if ($_POST['pass'] != $info['password']){
$writewrongpassword = "<tr><td colspan=\"2\" style=\"text-align: left; color: red;\">Incorrect password, please try again.</td></tr>";
}else{
// if login is ok then we add a cookie
$hour = time() + 3600;
setcookie("ID_my_site", $_POST['username'], $hour);
setcookie("Key_my_site", $_POST['pass'], $hour);
//they are logged in. no need to show the login form
$showlogin = false;
if($_POST["admin"]=="yes"){
setcookie("Admin_my_site", $_POST['admin'], $hour);
}else{
setcookie("User_my_site", $_POST['admin'], $hour);
}
header("Location: login.php");
}
}
}
}
}
//$_SESSION['logged_in'] = 1;
?>
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Login</title>
</head>
<body>
<?php if ($logged_in): ?>
<form action="<?php echo "logout.php";//$_SERVER['PHP_SELF'];?>" method="POST">
<span style="float: left; text-align: left; padding: 5px 5px 5px 5px;">
Welcome <span id="myusername"><?php echo $myusername; ?> </span>!<br />
Visit your <a style="text-decoration: none;" href="member.php" onmouseover="this.style.textDecoration='underline';" onmouseout="this.style.textDecoration='none';" >member's stat</a><br />
<input type="submit" style="float: left; border: 1px solid #7C7C7C; background-color: #7C7C7C; color: #ffffff; font: 9pt verdana, geneva, lucida, 'lucida grande', arial, helvetica, sans-serif; font-weight: bold; width: 100px; height: 20px;" name="submit" onMouseOver="this.style.backgroundColor='#B4B3A9'" onMouseOut="this.style.backgroundColor='#7C7C7C'" value="Logout" />
</span>
</form>
<?php else: ?>
<form action="<?php echo "login.php";//$_SERVER['PHP_SELF'];?>" method="POST">
<table border="0">
<tr>
<td>Administrator:</td><td><input type="checkbox" id="adminid" name="admin" style="float: left; border: 1px solid #7C7C7C; background-color: #7C7C7C;" value="no" onClick="if(this.value=='no'){this.value='yes'; document.getElementById('register').style.display = 'none';} else{this.value='no';document.getElementById('register').style.display = 'block';};" /></td>
</tr>
<?php echo $writeemptyfield; ?>
<?php echo $writeusernoexist; ?>
<tr>
<td>Username:</td>
<td><input type="text" name="username" id="username" style="float: left; border: 1px solid #7C7C7C; font: 9px verdana, geneva, lucida, 'lucida grande', arial, helvetica, sans-serif; width: 100px; height: 15px;" value="User Name" onBlur="if (this.value == '') this.value = 'User Name';" onFocus="if (this.value == 'User Name') this.value = '';" /></td>
</tr>
<?php echo $writewrongpassword; ?>
<tr>
<td>Password:</td><td><input type="password" style="float: left; border: 1px solid #7C7C7C; font: 9pt verdana, geneva, lucida, 'lucida grande', arial, helvetica, sans-serif; width: 100px; height: 15px;" name="pass" id="pass" /></td></tr>
<tr>
<td><a id="register" href="login/register.php" style="float: left; display: block; background-color: #7C7C7C; text-align: left; padding: 0px 0px 0px 5px; width: 80px; height: 20px; text-decoration: none; color: #ffffff; border: 1px solid #7C7C7C; font-weight: bold;" onMouseOver="this.style.backgroundColor='#B4B3A9'" onMouseOut="this.style.backgroundColor='#7C7C7C'">Register</a></td><td align="right"><input type="submit" style="float: left; border: 1px solid #7C7C7C; background-color: #7C7C7C; color: #ffffff; font: 9pt verdana, geneva, lucida, 'lucida grande', arial, helvetica, sans-serif; font-weight: bold; width: 100px; height: 20px;" name="submit" onMouseOver="this.style.backgroundColor='#B4B3A9'" onMouseOut="this.style.backgroundColor='#7C7C7C'" value="Login" /></td>
</tr>
</table>
</form>
<?php endif; ?>
</body>
</html>
<?php
# login.php
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
session_start();
$_SESSION['logged_in'] = true;
header('HTTP/1.1 303 See Other');
}
header('Location: index.php');
?>
<?php
# logout.php
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
session_start();
session_destroy();
header('HTTP/1.1 303 See Other');
}
header('Location: index.php');
?>
So what should I do?
penagate
Apr 29th, 2010, 07:08 PM
You need to read my reply again. I have already advised you what to do.
gilgalbiblewhee
May 11th, 2010, 04:50 PM
You need to read my reply again. I have already advised you what to do.
Which post number? I'm not reading all 76 postings. I took a break from this because it's tiring to my eyes.
gilgalbiblewhee
Jun 12th, 2010, 10:16 PM
Ok I want to finish this. Why isn't the username showing when I login?
<?php
# login.php
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
session_start();
$_SESSION['logged_in'] = true;
header('HTTP/1.1 303 See Other');
}
header('Location: index.php');
?>
<?php
# index.php
session_start();
$logged_in = isset($_SESSION['logged_in']);
include("../dbconnection.php");
//say goodbye to magic_quotes_gpc! no false security.
$errors = array();
if($_SERVER['REQUEST_METHOD'] == "POST"){
if(empty($_POST['username'])){
$errors[] = "username was empty";
}
if(empty($_POST['password'])){
$errors[] = "password was empty";
}
if(empty($_POST['email'])){
$errors[] = "e-mail was empty";
}
if(count($errors) == 0){
//fix magic_quotes_gpc() being on
if(get_magic_quotes_gpc()){
foreach($_GET as $k => $v){
$_GET[$k] = stripslashes($v);
}
foreach($_POST as $k => $v){
$_POST[$k] = stripslashes($v);
}
foreach($_COOKIE as $k => $v){
$_COOKIE[$k] = stripslashes($v);
}
}
//Checks if there is a login cookie
if(isset($_COOKIE['ID_my_site'])){ //if there is, it logs you in and directs you to the members page
$myusername = $_COOKIE['ID_my_site'];
$pass = $_COOKIE['Key_my_site'];
$admin = $_COOKIE['Admin_my_site'];
$user = $_COOKIE['User_my_site'];
$sql = "SELECT * FROM ";
if($admin=="yes"){
$sql .= $dbTable2;
}else{
$sql .= $dbTable;
}
$sql .= " WHERE username = '".mysql_real_escape_string($myusername)."'";
$check = mysql_query($sql)or die(mysql_error());
while($info = mysql_fetch_array( $check )){
if($pass == $info['password']){
$writeusername = "Welcome ".$myusername."! <br />Visit your <a href=\"member.php\">member's stat</a> <br /><a href=\"login/logout.php\">Logout</a>";
}
}
}
//variable to keep track of whether to show the user the login form or not
$showlogin = true; //we show the form by default, -unless- we know they have logged in
//if the login form is submitted
if (isset($_POST['submit'])){ // if form has been submitted
if(!$_POST['username'] || !$_POST['pass']) {// makes sure they filled it in
$writeemptyfield = "<tr><td colspan=\"2\" style=\"text-align: left; color: red;\">You did not fill in a required field.</td></tr>";
}// checks it against the database
$_POST['email'] = mysql_real_escape_string($_POST['email']);
$db['username'] = mysql_real_escape_string($_POST['username']);
$sql = "SELECT * FROM ";
if($admin=="yes"){
$sql .= $dbTable2;
}else{
$sql .= $dbTable;
}
$sql .= " WHERE username = '".$db['username']."'";
$check = mysql_query($sql) or die(mysql_error());
//Gives error if user dosen't exist
$check2 = mysql_num_rows($check);
if ($check2 == 0) {
$writeusernoexist = "<tr><td colspan=\"2\" style=\"text-align: left; color: red;\">That user does not exist in our database.</td></tr>";
}
while($info = mysql_fetch_array( $check )){
$_POST['pass'] = md5($_POST['pass']);
//gives error if the password is wrong
if ($_POST['pass'] != $info['password']){
$writewrongpassword = "<tr><td colspan=\"2\" style=\"text-align: left; color: red;\">Incorrect password, please try again.</td></tr>";
}else{
// if login is ok then we add a cookie
$hour = time() + 3600;
setcookie("ID_my_site", $_POST['username'], $hour);
setcookie("Key_my_site", $_POST['pass'], $hour);
//they are logged in. no need to show the login form
$showlogin = false;
if($_POST["admin"]=="yes"){
setcookie("Admin_my_site", $_POST['admin'], $hour);
}else{
setcookie("User_my_site", $_POST['admin'], $hour);
}
header("Location: login.php");
}
}
}
}
}
//$_SESSION['logged_in'] = 1;
?>
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Login</title>
</head>
<body>
<?php if ($logged_in): ?>
<form action="<?php echo "logout.php";//$_SERVER['PHP_SELF'];?>" method="POST">
<span style="float: left; text-align: left; padding: 5px 5px 5px 5px;">
Welcome <span id="myusername"><?php echo $writeusername; ?> </span>!<br />
Visit your <a style="text-decoration: none;" href="member.php" onmouseover="this.style.textDecoration='underline';" onmouseout="this.style.textDecoration='none';" >member's stat</a><br />
<input type="submit" style="float: left; border: 1px solid #7C7C7C; background-color: #7C7C7C; color: #ffffff; font: 9pt verdana, geneva, lucida, 'lucida grande', arial, helvetica, sans-serif; font-weight: bold; width: 100px; height: 20px;" name="submit" onMouseOver="this.style.backgroundColor='#B4B3A9'" onMouseOut="this.style.backgroundColor='#7C7C7C'" value="Logout" />
</span>
</form>
<?php else: ?>
<form action="<?php echo "login.php";//$_SERVER['PHP_SELF'];?>" method="POST">
<table border="0">
<tr>
<td>Administrator:</td><td><input type="checkbox" id="adminid" name="admin" style="float: left; border: 1px solid #7C7C7C; background-color: #7C7C7C;" value="no" onClick="if(this.value=='no'){this.value='yes'; document.getElementById('register').style.display = 'none';} else{this.value='no';document.getElementById('register').style.display = 'block';};" /></td>
</tr>
<?php echo $writeemptyfield; ?>
<?php echo $writeusernoexist; ?>
<tr>
<td>Username:</td>
<td><input type="text" name="username" id="username" style="float: left; border: 1px solid #7C7C7C; font: 9px verdana, geneva, lucida, 'lucida grande', arial, helvetica, sans-serif; width: 100px; height: 15px;" value="User Name" onBlur="if (this.value == '') this.value = 'User Name';" onFocus="if (this.value == 'User Name') this.value = '';" /></td>
</tr>
<?php echo $writewrongpassword; ?>
<tr>
<td>Password:</td><td><input type="password" style="float: left; border: 1px solid #7C7C7C; font: 9pt verdana, geneva, lucida, 'lucida grande', arial, helvetica, sans-serif; width: 100px; height: 15px;" name="pass" id="pass" /></td></tr>
<tr>
<td><a id="register" href="login/register.php" style="float: left; display: block; background-color: #7C7C7C; text-align: left; padding: 0px 0px 0px 5px; width: 80px; height: 20px; text-decoration: none; color: #ffffff; border: 1px solid #7C7C7C; font-weight: bold;" onMouseOver="this.style.backgroundColor='#B4B3A9'" onMouseOut="this.style.backgroundColor='#7C7C7C'">Register</a></td><td align="right"><input type="submit" style="float: left; border: 1px solid #7C7C7C; background-color: #7C7C7C; color: #ffffff; font: 9pt verdana, geneva, lucida, 'lucida grande', arial, helvetica, sans-serif; font-weight: bold; width: 100px; height: 20px;" name="submit" onMouseOver="this.style.backgroundColor='#B4B3A9'" onMouseOut="this.style.backgroundColor='#7C7C7C'" value="Login" /></td>
</tr>
</table>
</form>
<?php endif; ?>
</body>
</html>
kows
Jun 12th, 2010, 11:07 PM
in this script? all you do is POST to login.php, where $_SESSION['logged_in'] is set -- then, when you redirect back to index.php, you're not POSTing anymore, so your index.php script doesn't process the login or do any of that stuff.
the problem here is that you have authentication-oriented logic mixed with greeting-logic. once you have authenticated the user (should be done in login.php), you can store the username in the session or something so that you don't need to query the database every time you want it.
login.php should authenticate the login. index.php should greet the user.
gilgalbiblewhee
Jun 13th, 2010, 12:23 AM
in this script? all you do is POST to login.php, where $_SESSION['logged_in'] is set -- then, when you redirect back to index.php, you're not POSTing anymore, so your index.php script doesn't process the login or do any of that stuff.
the problem here is that you have authentication-oriented logic mixed with greeting-logic. once you have authenticated the user (should be done in login.php), you can store the username in the session or something so that you don't need to query the database every time you want it.
login.php should authenticate the login. index.php should greet the user.
I'm trying to echo $sql but nothing shows wherever i put it.
kows
Jun 13th, 2010, 02:27 AM
well, that means you must not have read my post. anything between these lines in your script is not being executed:
if($_SERVER['REQUEST_METHOD'] == "POST"){
// .. all of the code here is never been executed
}
the request method is only ever "POST" after you've submitted a form. what you're doing is submitting the form (index.php) to another script (login.php) and then redirecting that page back to the form (index.php). once you submit the form, login.php's REQUEST_METHOD is POST. once you redirect from login.php to index.php, the REQUEST_METHOD is back to GET (default). you should be authenticating the user and getting user information in login.php.
gilgalbiblewhee
Jun 14th, 2010, 08:48 PM
well, that means you must not have read my post. anything between these lines in your script is not being executed:
if($_SERVER['REQUEST_METHOD'] == "POST"){
// .. all of the code here is never been executed
}
the request method is only ever "POST" after you've submitted a form. what you're doing is submitting the form (index.php) to another script (login.php) and then redirecting that page back to the form (index.php). once you submit the form, login.php's REQUEST_METHOD is POST. once you redirect from login.php to index.php, the REQUEST_METHOD is back to GET (default). you should be authenticating the user and getting user information in login.php.Even if I block them it doesn't change anything.
kows
Jun 14th, 2010, 08:55 PM
.. block what? please say so if you're having a hard time understanding something. you're not trying to block anything -- you need to move things around. the login authentication that is inside your index.php script should be moved to your login.php script.
gilgalbiblewhee
Jun 14th, 2010, 09:00 PM
.. block what? please say so if you're having a hard time understanding something. you're not trying to block anything -- you need to move things around. the login authentication that is inside your index.php script should be moved to your login.php script.
Oh so you mean the following has to move to login.php:
if($_SERVER['REQUEST_METHOD'] == "POST"){
if(empty($_POST['username'])){
$errors[] = "username was empty";
}
if(empty($_POST['password'])){
$errors[] = "password was empty";
}
if(empty($_POST['email'])){
$errors[] = "e-mail was empty";
}
if(count($errors) == 0){
//fix magic_quotes_gpc() being on
if(get_magic_quotes_gpc()){
foreach($_GET as $k => $v){
$_GET[$k] = stripslashes($v);
}
foreach($_POST as $k => $v){
$_POST[$k] = stripslashes($v);
}
foreach($_COOKIE as $k => $v){
$_COOKIE[$k] = stripslashes($v);
}
}
//Checks if there is a login cookie
if(isset($_COOKIE['ID_my_site'])){ //if there is, it logs you in and directs you to the members page
$myusername = $_COOKIE['ID_my_site'];
$pass = $_COOKIE['Key_my_site'];
$admin = $_COOKIE['Admin_my_site'];
$user = $_COOKIE['User_my_site'];
$sql = "SELECT * FROM ";
if($admin=="yes"){
$sql .= $dbTable2;
}else{
$sql .= $dbTable;
}
$sql .= " WHERE username = '".mysql_real_escape_string($myusername)."'";
$check = mysql_query($sql)or die(mysql_error());
while($info = mysql_fetch_array( $check )){
if($pass == $info['password']){
$writeusername = "Welcome ".$myusername."! <br />Visit your <a href=\"member.php\">member's stat</a> <br /><a href=\"login/logout.php\">Logout</a>";
}
}
}
//variable to keep track of whether to show the user the login form or not
$showlogin = true; //we show the form by default, -unless- we know they have logged in
//if the login form is submitted
if (isset($_POST['submit'])){ // if form has been submitted
if(!$_POST['username'] || !$_POST['pass']) {// makes sure they filled it in
$writeemptyfield = "<tr><td colspan=\"2\" style=\"text-align: left; color: red;\">You did not fill in a required field.</td></tr>";
}// checks it against the database
$_POST['email'] = mysql_real_escape_string($_POST['email']);
$db['username'] = mysql_real_escape_string($_POST['username']);
$sql = "SELECT * FROM ";
if($admin=="yes"){
$sql .= $dbTable2;
}else{
$sql .= $dbTable;
}
$sql .= " WHERE username = '".$db['username']."'";
$check = mysql_query($sql) or die(mysql_error());
//Gives error if user dosen't exist
$check2 = mysql_num_rows($check);
if ($check2 == 0) {
$writeusernoexist = "<tr><td colspan=\"2\" style=\"text-align: left; color: red;\">That user does not exist in our database.</td></tr>";
}
while($info = mysql_fetch_array( $check )){
$_POST['pass'] = md5($_POST['pass']);
//gives error if the password is wrong
if ($_POST['pass'] != $info['password']){
$writewrongpassword = "<tr><td colspan=\"2\" style=\"text-align: left; color: red;\">Incorrect password, please try again.</td></tr>";
}else{
// if login is ok then we add a cookie
$hour = time() + 3600;
setcookie("ID_my_site", $_POST['username'], $hour);
setcookie("Key_my_site", $_POST['pass'], $hour);
//they are logged in. no need to show the login form
$showlogin = false;
if($_POST["admin"]=="yes"){
setcookie("Admin_my_site", $_POST['admin'], $hour);
}else{
setcookie("User_my_site", $_POST['admin'], $hour);
}
header("Location: login.php");
}
}
}
}
}
kows
Jun 14th, 2010, 10:39 PM
yes. except you are sending a header at the end that redirects to login.php, and you'll want to get rid of that.
vbforums.com
Copyright Internet.com Inc., All Rights Reserved.