Jump to content

Log in


Hooch
 Share

Recommended Posts

Hello all, and thank you W3Schools for a helpfull site.I was wondering how you could have a page that shows if your logged in or logged out. But if you are logged out, the script doesn't block the rest of the page.I was hoping to keep the main page the same for users no matter logged in or out. Just have a button/link to log in or out within a table of the header.So I tried making a header that was in an includes folder. Then the whole of the header is before the php that checks to see if your logged in. This way no matter what the header will show.I then made my main page that included the header.php file.Now the php code that says if your logged in or not seems to be working, but I want it to say Hello "username here". Here is my problem.Could someone please look at my code to find out why the username doesn't show up?Here's a more simplified look at my code..

<?php  if (!$_COOKIE['id']){  echo "<a href=\"signup.html\">Register </a><a href=\"login.html\">Log In</a>";  die("");  }echo "Welcome";// username here?>

How would you code this to add the username from the database?And where is the best place to add the database connection? Here is the code for the connection...is this ok?

// Connect to the database          $server = "localhost";          $dbuser = "&^*^%";          $dbpass = "%^$%^";          $dbname = ")**^^";          mysql_connect($server,$dbuser,$dbpass) or die ("Could not establish connection"); // make connection          mysql_select_db($dbname); // select database          // Get users information          $result = mysql_query("SELECT * FROM `users` WHERE `id` = '".$u."' LIMIT 1");          while($r=mysql_fetch_array($result)){          

I have successfully added 3 members to my test site. I can log in and out no problem. Thanks for your time...Hooch

Link to comment
Share on other sites

I got the username showing up now after "welcome - ". But it's only showing the 1st name in the database....not the user who actually is signed in. Here's my code.

<table width="700" height="100" border="0" align="center" cellpadding="0" cellspacing="0" bordercolor="#00FF00">	<tr>        <td height="81" colspan="4" background="images/header-700-81.jpg"> </td>	</tr>	<tr>       <td width="62" height="19">  <?php  if (!$_COOKIE['id']){  echo "<a href=\"signup.html\">Register</a>";  echo "  ";  echo "<a href=\"login.html\">Log In</a>";  die("");  }  echo "Welcome - ";  ?>    </td>  <td width="212" height="19">  <?php  // Connect to the database  $server = "localhost";  $dbuser = "user";  $dbpass = "pass";  $dbname = "bd_name";  mysql_connect($server,$dbuser,$dbpass) or die ("connection error"); // make connection  mysql_select_db($dbname); // select database  // Get users information  $result = mysql_query("SELECT * FROM users LIMIT 1");  while($r=mysql_fetch_array($result))  {  $username=$r["username"];  echo "$username";  }  ?>   	 </td>        <td width="212" height="19"> </td>  <td width="214"> </td>	</tr></table>

Thank you for any help. Hooch

Link to comment
Share on other sites

It looks like you took out there WHERE clause in the SQL statement. Use the same SQL statement you had the first time when you search for the ID. Also, it is a good idea to make sure you escape any text strings going into a query:

$result = mysql_query("SELECT * FROM `users` WHERE `id` = '".mysql_escape_string($u)."' LIMIT 1");

It helps prevent something called SQL injection. You also don't need the LIMIT 1 here (you can probably assume there is only 1 user with the ID).

Link to comment
Share on other sites

Try this one, the ID was wrong. This uses the same id that is in the cookie.

<table width="700" height="100" border="0" align="center" cellpadding="0" cellspacing="0" bordercolor="#00FF00">	<tr>        <td height="81" colspan="4" background="images/header-700-81.jpg"> </td>	</tr>	<tr>       <td width="62" height="19">  <?php  if (!$_COOKIE['id']){  echo "<a href=\"signup.html\">Register</a>";  echo "  ";  echo "<a href=\"login.html\">Log In</a>";  die("");  }  echo "Welcome - ";  ?>    </td>  <td width="212" height="19">  <?php  // Connect to the database  $server = "localhost";  $dbuser = "user";  $dbpass = "pass";  $dbname = "bd_name";  mysql_connect($server,$dbuser,$dbpass) or die ("connection error"); // make connection  mysql_select_db($dbname); // select database  // Get users information  $result = mysql_query("SELECT * FROM users WHERE id='".mysql_escape_string($_COOKIE['id'])."'");  $r=mysql_fetch_assoc($result))  echo $r["username"];  ?>    	</td>        <td width="212" height="19"> </td>  <td width="214"> </td>	</tr></table>

Link to comment
Share on other sites

BINGO!!! Thank you soo much!! :):) You da man!!Oh..BTW incase anyone is following alongI had to change 1 thing in your code.$r=mysql_fetch_assoc($result)) to$r=mysql_fetch_assoc($result);Again thank you very very much.

Link to comment
Share on other sites

I was wondering how you could have a page that shows if your logged in or logged out. But if you are logged out, the script doesn't block the rest of the page.I was hoping to keep the main page the same for users no matter logged in or out. Just have a button/link to log in or out within a table of the header.
I thought this would work...but because of the die command I loose the restof my page if I'm not logged in. Is there a way around this with the way I'm going here? Thank you..Hooch
Link to comment
Share on other sites

Yeah, of course. You should think of your page in terms of sections, or boxes. You probably have a top header or something, which never changes from page to page or if you're logged in or not. Then maybe you have a box on the left side, where you have your page menu. That's another box. Then you have the main page content itself, and maybe a box somewhere to handle the login/welcome stuff. Each of these is its own box, or section.It sounds like you have everything else working, except the login box will kill the page if the user is not logged in. That's just because you threw in a "die()" in the code if they are not logged in, the die function stops page execution at that point. All you need to do is restructure the page to remove the die, which will require an if/else statement (you already have the 'if' part).I pasted the code below. All I did was take the last code I posted above, and I restructured it a little. The way the code works now, is that it builds a message based on if the user is logged in or not (the message is either a login form or a welcome message), and then displays that one message in the spot where it goes.

<table width="700" height="100" border="0" align="center" cellpadding="0" cellspacing="0" bordercolor="#00FF00">  <tr>    <td height="81" colspan="4" background="images/header-700-81.jpg"> </td>  </tr>  <tr>    <td width="62" height="19"><?php$msgbox = "";if (!$_COOKIE['id']){  $msgbox .= "<a href=\"signup.html\">Register</a>";  $msgbox .= "  ";  $msgbox .= "<a href=\"login.html\">Log In</a>";}else{  $msgbox .= "Welcome - ";  // Connect to the database  $server = "localhost";  $dbuser = "user";  $dbpass = "pass";  $dbname = "bd_name";  mysql_connect($server,$dbuser,$dbpass) or die ("connection error"); // make connection  mysql_select_db($dbname); // select database  // Get users information  $result = mysql_query("SELECT * FROM users WHERE id='".mysql_escape_string($_COOKIE['id'])."'");  $r=mysql_fetch_assoc($result);  $msgbox .= $r["username"];}echo $msgbox;?>    </td>        <td width="212" height="19"> </td>    <td width="212" height="19"> </td>    <td width="214"> </td>  </tr></table>

Link to comment
Share on other sites

I hope I can change the subject a bit here. I was wondering if it's possible to change the submit button for my log in form?Here's the code.

echo "<a href=\"signup.html\">Register</a><form action=\"login.php\" method=\"post\">name: <input type=\"text\" name=\"username\" size=\"8\"> password: <input type=\"password\" name=\"password\" size=\"8\"><input type=\"submit\" value=\"submit\" name=\"submit\"></form>";

I was hoping to change the button to a clickable .gif. Or atleast a text link. The button looks way out of place.Would I change it to this??

echo "<a href=\"signup.html\">Register</a><form action=\"login.php\" method=\"post\">name: <input type=\"text\" name=\"username\" size=\"8\"> password: <input type=\"password\" name=\"password\" size=\"8\"><input type=\"image\" SRC=\"image/mypic.gif\" name=\"submit\"></form>";

Thank you

Link to comment
Share on other sites

You can style it if you want. You can use a lot of CSS properties to change the border style, background color, etc. You can also use CSS to make it look like an image, or you can just use an image without CSS. <input type="image" src="http://www.....jpg">You can also get a little tricky, and use one image for both the normal and hover states. You can make a button like this with css:

.input_button {  background-image: url(path/to/image);  background-repeat: no-repeat;  background-position: top left;  height: 16px;  width: 80px;}.input_button:hover {  background-position: bottom left;}

That way you make an image twice as tall as the button itself, and instead of having to load a new image on hover, it just moves the existing one.

Link to comment
Share on other sites

hmm.. the image is not working. But the CSS is. Here's my code for the submit...mind having a boo?

<input type=\"image\" class=\"submit\" name=\"submit\">

Here's my CSS code

/*  =======Submit button=========  */.submit { background-image: url(images/submit.jpg); background-repeat: no-repeat; background-position: top left; height: 16px; width: 16px;}.submit:hover { background-position: bottom left;}

Again, I cannot thank you enough. I wouldn't be able to learn this stuff any other way.Cheers P.S. I just got the msgbox working...yay!!

Link to comment
Share on other sites

I did that 1st actually..but the image never moved. So I thought the CSS covered that part. I'll give it a try again..maybe something was missing before. I just added the src. and still no movement. It just keeps the original pic. I even tried changing the bg pic for the hover, nothing changes.

Link to comment
Share on other sites

Change the button to a normal submit button:<input type="submit" class="submit">I checked the code I have that does this and here is what I'm using:

.standard_button {  font-family: "Verdana", sans-serif;  font-size: 10px;  font-weight: bold;  border: none;  height: 16px;  width: 100px;  background-image: url(../images/standard_button.gif);  background-position: 0% 0%;  color: #FFFFFF;  cursor: pointer;}.standard_button:hover {  background-image: url(../images/standard_button.gif);  background-position: 0% 100%;  color: #000000;}

Maybe try changing the background-position to the percentages.Also, here's an example button. The normal state and hover states are part of the same image. Since I specify above that the button is 16px high, I made the image 32px so that it can move the image and show the other part.http://www.outpostmultimedia.com/projects/...dard_button.gif

Link to comment
Share on other sites

No problem. I was pretty pumped when I realized I could do that too, I've never liked mousing over something and seeing the status bar pop up and load an image, and javascript preloading always seemed like a hack (which it is). This way seems to work pretty well.

Link to comment
Share on other sites

I really need to buy someone a drink now. I have a new request.When a user successfully registers I have them automatically redirected to the index.php page. Thing is, they are not logged in when they get there. Is this easy to show how to impliment? Many many thanks..HoochP.S. here is my 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=iso-8859-1" /><title>my test site</title></head><body><?php include 'header.php'; ?><table width="700" border="2" align="center" cellpadding="0" cellspacing="0" bordercolor="#BE8647">  <tr>    <td width="161" rowspan="2">   <div align="center">     <?php    // Connect to the database 	 include "includes/db.php";$query = "SELECT COUNT(ip) AS numrows FROM stats WHERE ip='".$_SERVER["REMOTE_ADDR"]."'";$result = mysql_query($query) or die('Error, query failed');$row = mysql_fetch_array($result);$numrows = $row['numrows'];if ($numrows == 0) {mysql_query("INSERT INTO stats(ip,hits,activity,user_agent)VALUES ('".$_SERVER["REMOTE_ADDR"]."','1',now(),'{$_SERVER['HTTP_USER_AGENT']}')");}else{mysql_query("UPDATE stats SET hits=hits+1 WHERE ip='".$_SERVER['REMOTE_ADDR']."'");}$result = mysql_query("SELECT COUNT(ip) AS numrows FROM stats");$row = mysql_fetch_array($result);$unique = $row['numrows'];$result = mysql_query("SELECT hits FROM stats");while ($row = mysql_fetch_array($result)) {$hits += $row['hits'];} 	 $msgbox = "";    if (!$_COOKIE['id']){ 	 echo"member info block<br>"; 	 echo "<form action=\"login.php\" method=\"post\">name: <input type=\"text\" name=\"username\" size=\"8\"><br> 	 password: <input type=\"password\" name=\"password\" size=\"8\"> <input type=\"image\" class=\"submit\" name=\"submit\"></form>";     } 	 else 	 { 	 echo"member info block<br>";    $msgbox .= "Welcome - ";    // Get users information    $result = mysql_query("SELECT * FROM users WHERE id='".mysql_escape_string($_COOKIE['id'])."'");    $r=mysql_fetch_assoc($result);    $msgbox .= $r["username"]; 	 } 	 echo $msgbox; 	 ?>     <form method="GET" action="search.php">    <b>Search:</b> <input type="text" name="search" size="10" />    <input type="image" class="submit" value="Search!" />    </form>	<a href="signup.html">Register</a><br />	<a href="includes/logout.php">Logout</a><br /><br />	<strong>SITE STATS</strong><br />    Unique Hits: <? echo $unique; ?><br />    Hits: <? echo $hits; ?>       </div>	</td>    <td width="296"> </td>    <td width="233"> </td>  </tr>  <tr>    <td>Test middle </td>    <td>Test right </td>  </tr></table></body></html>

Link to comment
Share on other sites

I really need to buy someone a drink now.
I'll take a Hangar One on the rocks, please.I'm betting your problem is how you are setting the cookie. I ran into this with my own apps, and the symptoms sound similar.First, a little primer on cookies. I'm sure you know that a cookie is a little text chunk hanging out on your local computer, and they contain information that basically the site tells the browser to save, whatever information that is. Could be a user id, a shopping cart, whatever.The way that happens, is that the server includes a header when it sends the response to the browser. The header tells the browser everything it needs to know about the cookie, the name of it, the value, expiration, all that junk. So since the cookie is essentially a header attached to some other page, you can't set a cookie and retrieve it on the same page. By the time the browser has created the cookie, the server is already done executing the code. That is the reason when you log in or log out on a lot of places, you go to some page that says "thank you, we are redirecting you". That page you see is the page that actually sets (or deletes) the cookie, and by the time you get redirected, the cookie has already been created or deleted, and the page you get redirected to now has access to the updated info.The second thing this means (that the cookie is a header) is that you actually need some page content to set the cookie. You can't juse call the setcookie() function at the end of a page and have a cookie created (actually, it produces an error if you do that anyway). You have to make the call to setcookie before any other page output, since the cookie is a header, and whenever you start output on the PHP script all the headers get sent first.So, in conclusion, consider inserting a middle page between login (or logout) and index that is totally responsible for cookie manipulation, creating and deleting. You can use the same login code you already use, the difference is that a cookie is also set. Once you actually spit output out from that page, and get the cookie set, you can redirect them to the appropriate page and have access to the cookie.I can't tell you how long it took me to figure that out.btw: the code actually looks pretty decent, you got stats and everything going on. you go!
Link to comment
Share on other sites

Thank guys. I am a little confused with your very detailed answer guy. But it's late and I have been sitting at the computer for a few hours now. Maybe a fresh brain will prevail tomorrow. Have a good one....Hooch

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...