Site with login

I keep running into problems with this… Very different problems… Here’s what I’m currently doing:

I’ve got an index.php, which I’m ofcourse planning to render different content, depending on who is logged in. The login link points back to the index.php, with mode=login. I can get the php to display what is in $_POST[‘mode’], so that’s no problem. But how do I put up different links when mode is login, and when mode is register, for example? How is the best way to output HTML from PHP in this way?

This sounds like a job for heredoc. Heredoc is a syntax used for long strings with your php variables interspersed. You start your variable declaration like normal but put three open carets after the equal sign as well as a string that will terminate:

$ifNotLoggedIn =<<< HEREDOC
This is my content, $user is a php variable that will render as the value stored within it, and <strong>oh look!</strong> here is some html stuff as well.
HEREDOC;

echo $ifNotLoggedIn;

You have to put the terminating string on its own line with no whitespace before it to end it or you will get errors.

So with that info, put your logged in content as a heredoc variable like above, as well as your not logged in content in its own variable. Then it’s just as simple as placing this in your body:

<?php
if($_SESSION['mode'] == "whatever")
{
   echo $loggedInContent;
}else{
   echo $notLoggedInContent;
}?>

Ok I’ll try this out today, thanks for the help!

I’m finally getting somewhere now :slight_smile: Thanks for the help everyone, I’ve learned a whole lot!

Using HEREDOC is one way of doing it - I prefer to use templates

Bear in mind that it may only be useful in certain situations - i.e. if you have a template which is only ever used once in one area of the site it might not be worth it

Basically you write your code in a seperate PHP file and then include this file in your PHP page based on conditional statements. This means that if you make a change to the ‘login’ area you only have to modify it in one place.

You can also view the actual page layout in your favourite HTML editor so the visual design element is easier.

If you include all your page content within strings in the PHP tags you won’t be able to see it in the editor. You could always use the <? if something ?>html stuff<? end if ?> method - but I prefer to seperate dynamic content into templates and classes.

It’s up to your preferences though - loads of ways to skin a cat!

I’m currently not using templates or HEREDOC yet. I made a header.php and footer.php which I include in every page, and then the content is always in the same space.
However it’s not working properly! It worked the first time, when I wasn’t logged in it said I needed to log in. Then when I logged in it said Welcome, Maqrkk. And now it acts as if I’m logged in, but it doesn’t know the username. And this is the same on a different computer, with a different IP etc.
This is in my header.php:

<?php
session_start();
if($_SESSION['logged_in'] == true);
{
$login = true;
}
?>

And this is the code I have in my login.php:

<?php
$mode = $_POST['mode'];
if($mode = 'login')
{
	if ($_POST['uname'] == "" || $_POST['pword'] == "")
	{
		header("location:index.php?err=1");
	}
	else
	{
		$con = mysql_connect("xxx","xxx","xxx");
		mysql_select_db("Maq_polls",$con);
		$username = $_POST['uname'];
		$username = mysql_real_escape_string($username);
		$password = $_POST['pword'];
		$password = sha1(mysql_real_escape_string($password));
		$user = mysql_query("SELECT * FROM users WHERE user_name = '$username' and user_pw = '$password'");
		$count = mysql_num_rows($user);
		if($count != 1)
		{
			header("location:index.php?err=1");
		}
		else
		{
			$_SESSION['logged_in'] = true;
			$_SESSION['username'] = $username;
			header("location:index.php");
		}
	}
}
else if($mode = 'logout')
{
	$_SESSION['logged_in'] = false;
	header("location:index.php");
}
?>

Currently, mode is logout every time, because it thinks I’m logged in somehow. What am I doing wrong?

The infamous power of posting struck me. Right after posting I noticed the typo in header.php

It’s now:

<?php
session_start();
if($_SESSION['logged_in'] == true)
{
$login = true;
}
else
{
$login = false;
}
?>

You have also used a single = instead of a double == in your if comparison for mode


if($mode = 'logout') 

= is the assignment operator
== is equality operator

Change it or strange things will still happen! :stuck_out_tongue:

[quote=Charleh;2337156]You have also used a single = instead of a double == in your if comparison for mode


if($mode = 'logout') 

= is the assignment operator
== is equality operator

Change it or strange things will still happen! :P[/quote]

Thanks, I also missed that one! After some more bugs (in parts I didn’t link) it now looks like it works! Now to get the registering to work again…

Registering works. And the login system seems to work aswell. Now all I need to do is write some error messages for certain situations, for example password with not enough characters etc.

However, I found another error. When I log in, close the browser and go to the site again I’m logged out. Im guessing this has to do with cookies. What’s a safe way to store cookies with login information?

You don’t - storing cookies with login information is usually bad practice

Have a look at this post, it’s got a link to a discussion on the matter

http://forum.java.sun.com/thread.jspa?threadID=529689&messageID=2547879

Most of the time, if you close the browser you lose your session - and that’s the way it should be.

True unless you have a remember me check box, in which case you will need to store a cookie.

Use:
setcookie(“name”, value, expires)

I would keep the expires value relatively low, just to be safe. But you can insert their session id, their username md5 and still be somewhat secure.

//This sets a cookie called session with the users session id which expires in one day
setcookie(“session”, md5($username),time()+(606024*1),"/");

Thanks for all the responses guys, really appreciated!!

Ok one question, is md5() for the same purpose as sha1(), encrypting? And why do you encrypt the username?

It was an arbitrary choice, it doesn’t matter what you put as the name or value really, it’s just something that you are going to check when the user visits again. Yes, md5 is an encryption algorithm, just like sha1. I would choose to encrypt whatever you set as the value though because reading cookies is easy (and spoofing them is equally easy), if something is sitting in plain text, it’s going to be that much easier to hack your site. Just something to keep in mind…

Allright I get it :slight_smile: I basically put up a cookie with the md5(username), pretty much like you showed me.

This is what is now in my header.php:

if(isset($_COOKIE['session']))
{
	if($_COOKIE['session'] != "")
	{
		// connecting to database.

		$user = mysql_query("SELECT * FROM users WHERE md5(user_name) = '$_COOKIE[session]'");
		
		$_SESSION['logged_in'] = true;
	}
}

It’s not really working, am I doing it wrong, or isn’t this possible and should I work around. By that I mean getting all user_name’s and testing each md5(user_name) to the cookie’s?

I decided to stay on the safe side and just not allow cookies… and I figured how to ‘easily’ pass post data, instead of putting it in the URL. Say I send the user to error.php, I don’t want to let the user easily look at all the errors by just changing error.php?err=1 to err=2, for example. Not that it’s risky, I just don’t want them to. Instead, before I put the header(“error.php”) statement, I set $_SESSION[‘error’] to the errorvalue, is that a good way to solve the problem?

Well good or not, it works :slight_smile:

And once again I got a question :wink:
This one is with opening and closing the connection to the database.
My index.php first opens header.php, which connects to the database and gets user’s session and compares to password in the database. Then whatever comes in the middle position opens the database, and finally the footer.php (which doesn’t use the database (yet)).

I was wondering, is it safe to open the database in the header, and close it in the footer? They will always be included both, but is it safe to leave it open in the meanwhile? Is it even necessary to close the database? I find myself using lots of lines for database connecting and closing, is this necessary?

Nope, I’d stick to opening a connection and getting your data then closing the connection. You are not always guaranteed that the footer code will be parsed if there is an error or something similar.

To be safe I’d close it in the header.

If you are getting tired of opening and closing the connection all the time why not just write a function or a class which you pass the connection information (or contains connection information already) which does the query/open/close of the data/conn and passes back an array with the results in it?

Thanks for the suggestion, actually never thought about it…