Jump to content

Only Showing A Page To Logged In Users


Ricky55

Recommended Posts

Hi very new to PHP.

 

I am wanting to create a very basic client login area. I have some code that I am using in a modal window provided via jQuery which looks nice. I'm wanting the same kind of experience that you get when you log into this website. Security is not an issue for me on this one.

 

So I have my code which works as I want but I now need to protect the secret page its self. I want users to be redirected to my home page if they try to open the URL without going through my login system.

 

How would I achieve this? Would I need to use sessions?

 

Heres my very basic login code.

 

 

Thanks

 

Richard

 


<?php
$username = 'ddd';
$password = 'xxx';
$after = 'http://www.domain/secret-content';
?>

<!DOCTYPE html>
<html lang=en>
<head>
<meta charset="utf-8">

<title>My Login Page</title>

</head>

<body>

<form method="post" action="#">

<label for="loginUsername">Username:</label>
<input type="text" name="username" size="20" id="loginUsername">

<label for="password">Password:</label>
<input type="password" name="password" size="20" id="loginPassword">

<button type="submit" name="submit" value="submit" id="submit">Submit</button>


</form>

<?php
if (
( isset($_POST["username"]) && ($_POST["username"] == $username) ) &&
( isset($_POST["password"]) && ($_POST["password"] == $password) )
)

{

echo "<meta HTTP-EQUIV=\"REFRESH\" content=\"0; url=$after\">";

}
?>



<?php
if (
( isset($_POST['username']) || ($username == '') ) ||
( isset($_POST['password']) || ($password == '') )
)

{
print '<p class="login-error">Sorry your username or password was entered incorrectly.</p>';
}

?>

</body>
</html>

Link to comment
Share on other sites

Yes it does. Your server will have to keep information about a user until the session expires, which consumes resources on the server. If you have a lot of users with session data, this can become a problem. Entirely avoiding sessions is difficult, so what you should try to do is to put as little information into sessions as you can. It would also be good to keep the number of users who have session data associated with them as low as possible; for instance, setting session data for every user would not be a very good idea. Sessions also make the task of scaling architectures more complicated.

Link to comment
Share on other sites

Performance hits by using sessions isn't normally something you have to worry about. Only after a profiling of the site shows you that the session handler is a major bottleneck is when you should be worry about it.

Just be mindful of what you store in the session, as they need to be read from disk at every page load. So I recommend saving the bare minimum of stuff, that you need on (just about) every page load.

Link to comment
Share on other sites

If you want to recognize users across multiple page views, such as having users log in, restricting access and stuff like that, then using sessions is the proper way. You may be able to do without, but it would be a highly complex and time consuming affair. Most definitely it'd give you more of a performance impact than sessions, at least.

Link to comment
Share on other sites

It's not really across multiple pages, it's just a simple client login I'm creating.

 

Users can login from any page of the site but when they have logged in they are just taken to one very simple page that allows them to download marketing assets, images etc.

 

It's doesn't have to secure really I just want users to be redirected to the home page if they try to visit the protected page without logging in first.

 

So is what I have the best way of achieving this?

Link to comment
Share on other sites

It's not really across multiple pages, it's just a simple client login I'm creating.

 

Users can login from any page of the site but when they have logged in they are just taken to one very simple page that allows them to download marketing assets, images etc.

 

It's doesn't have to secure really I just want users to be redirected to the home page if they try to visit the protected page without logging in first.

 

To do this, you need to save some state on the users, and in your case, you should use sessions for this. The state needs to be persistent across page changes. If you don't have a state on your user, you have no way of knowing whether or not you should redirect the visitor to the home page - because is the user logged in or not? By saving this state in a session, you can check this session variable on your login page to see if they are allowed to see the page. If so, show it - otherwise redirect to the home page. Information on how to do this can be found in the first replies to this thread.

Link to comment
Share on other sites

Ok thanks guys sorry if I was over complicating the issue.

 

This really is my final question how would l log a user out of the session.

 

My logout button was just going to be a link back to the home page but how would I end the session?

Link to comment
Share on other sites

You'll have to unset the global $_SESSION array as well, or at least the session ID. From the PHP manual:

session_destroy() destroys all of the data associated with the current session. It does not unset any of the global variables associated with the session, or unset the session cookie. To use the session variables again, session_start() has to be called.

 

In order to kill the session altogether, like to log the user out, the session id must also be unset. If a cookie is used to propagate the session id (default behavior), then the session cookie must be deleted. setcookie() may be used for that.

Link to comment
Share on other sites

Why isn't this working guys, all seems fine but when I visit my secret page without logging in the content still shows.

 

This is my login code

 


<?php
session_start();
$username = 'ddd';
$password = 'xxx';
$after = 'index.php';
?>

<!DOCTYPE html>
<html lang=en>
<head>
<meta charset="utf-8">

<title>My Login Page</title>

</head>

<body>

<form method="post" action="">

<label for="loginUsername">Username:</label>
<input type="text" name="username" size="20" id="loginUsername">

<label for="password">Password:</label>
<input type="password" name="password" size="20" id="loginPassword">

<button type="submit" name="submit" value="submit" id="submit">Submit</button>


</form>

<?php
if (
( isset($_POST["username"]) && ($_POST["username"] == $username) ) &&
( isset($_POST["password"]) && ($_POST["password"] == $password) )
) 

{

echo "<meta HTTP-EQUIV=\"REFRESH\" content=\"0; url=$after\">"; 
$_SESSION['isLoggedIn'] = true;

}
?>



<?php
if (
( isset($_POST['username']) || ($username == '') ) ||
( isset($_POST['password']) || ($password == '') )
) 

{
print '<p class="login-error">Sorry your username or password was entered incorrectly.</p>';
}

?>

</body>
</html>

 

This is my secret page code

 


<?php
session_start();

if (!isset($_SESSION['isLoggedIn'])) {
header("Location: ../index.php");
die;
}
?>

<a href="logout.php">Logout</a>

 

This is my logout code

 


<?php
session_start();
unset($_session['isLoggedIn']);
header ("Location: ../index.php");
?>

 

 

 

 

This is the code I'm using to log users out.

Link to comment
Share on other sites

I recommend reading the page I linked to, as it'll show you an example of how to properly destroy your session.

 

That noted, I'd also recommend you to all of the PHP processing to the top of the file. That way you can use the header () function to properly redirect your users, without having to write out the login form again.

Doing it that way will give you a lot more freedom and flexibility in what you can do with your code as well, since you're not constrained to whatever HTML you may or may not have sent to the browser. Not to mention that you can actually manipulate the HTTP headers, something which is impossible once you've sent something to the client.

Link to comment
Share on other sites

I'm back guys, I know sorry...

 

I've got this working as I want now apart from one tiny aspect.

 

If you go here you can see what I have so far

 

http://www.qwerty-demos.co.uk

 

Login using

 

User: ricky

Pass: hello

 

Problem starts when you enter in the incorrect info.

 

in my code I have

 


if(credentials_valid($_POST['username'], $_POST['password'])) {
log_in($_POST['username']);
header ("Location: ../client-login/");
}else{
header ("Location: login.php?error=1");
exit("You are being redirected");
}

 

The jQuery modal window is just showing login.php

 

which looks like this

 


<div id="login">

<a class="modal_close" href="#">Close Me</a>

<form action="_includes/authenticate.php" method="POST">

<label for="username">Username:</label>
<input type="text" name="username" size="20" id="username">

<label for="password">Password:</label>
<input type="password" name="password" size="20" id="password">

<button type="submit">Submit</button>

</form>

<?php if($_GET['error'] == '1'): ?>
<p>Username and/or password incorrect</p>
<?php endif ?>

</div>

 

My question is, how do I get the error message "Username and/or password incorrect" to display in my jQuery window and not load login.php as a separate page.

 

Any help will be much appreciated.

 

Cheers guys!

Link to comment
Share on other sites

I'm getting a bit confused with all this now mate.

 

I think I may be coming at this from the wrong angle.

 

You've seen my page

 

http://www.qwerty-demos.co.uk

 

I need any errors to just show up within my light box rather than opening a new page.

 

From my limited knowledge it seems that I either need to build the PHP logic into the code that I'm showing within the jQuery lightbox so I can just echo out the error or use Ajax so I can detect the error from PHP and just display it in the lightbox but I'm not sure how to do either.

 

I think I might have to get my dev mate to give me a hand. I've spent ages on this and it is working perfectly the page is being protected just as I want I just can't get this damn error to show without loading a new page and breaking my lightbox.

Link to comment
Share on other sites

I have exhausted my time on here for the day.. for now, anyway.  I understand what you are looking for and will leave you with some basic logic.

 

(You're looking for the modal to remain open and display any errors within the modal without a full page reload, correct?  Without that, the modal is completely pointless.)

 

Add an id to your form and a couple lines of JS:

 

http://api.jquery.com/jQuery.ajax/

 

<form id="check" action="_includes/authenticate.php" method="POST">
...

<script>
$(document).ready(function(){
...
   $('#check').submit(function() {
       // add an AJAX call to your db here and send back any errors if login is not successful; then, within the 'Success' key (within the jQuery ajax function), you can close the modal and send the user to the "logged in" page.
       return false;
   });
});

 

Sorry, like I said, I can't help you further at this time.  This will point you in the right direction and hopefully somebody else can add on, or at least you can give your developer some direction.  There's obviously more to it than I described within my few lines of javascript, but it's actually quite a simple process in the end.

Edited by mrMarcus
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.