Hey everyone,

So I've looked and tried to figure out how to get the user to "log in" before accessing a page. However I've seen where you send the user to the log in page if he or she has not log in but what about if the person has logged in already?..

for ex

if {

///enter code to redirect to login page///
}
exit()

or how ever it's coded but how do you make the "else" part of the function redirect to the current page so the log in viewer can "view" or access the page?

Recommended Answers

All 18 Replies

Using SESSION will make it easier,
Once the user logged in set SESSION for that user, For ex: SESSION.

And use this condition to check whether they have logged in

if(!isset($_SESSION['username'])) 
{
///enter code to redirect to login page///
exit();
}

If SESSION is not set it will redirect,
Hope this solves your question.
Don't forget to destroy your SESSION during logout.

@Samueal: when I put that code in to a page I want a login first before viewing, it does redirect to the login page but it still redirects there even when I am logged in..

Member Avatar for diafol
session_start();
if(!isset($_SESSION['user_id']) || empty($_SESSION['user_id'])){
  header('Location: login.php');
  exit;
}

@ardav: That code still redirects me to the login page after I have logged in.

Member Avatar for diafol
session_start();
if(!isset($_SESSION['user_id']) || empty($_SESSION['user_id'])){
  echo "user_id: {$_SESSION['user_id']}"; 
  exit;
}

@ardav: Yeah, it shows no user name when I echo out the username variable, which obviously means no username has been logged in but when I log in, it redirects me to the "successfully logged in page" which it wouldn't go to that page if I was not logged in..so there's got to be something wrong with my script for user log in..but I'm not sure what..here's my script below of the "checkuser.php" that goes along with the login page:
the connection is correct, so I starred out that part for my clients protection..

<?php
$host="********************"; // Host name 
$username="************"; // Mysql username 
$password="********"; // Mysql password 
$db_name="*********"; // Database name 
$tbl_name="users"; // Table name

// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect"); 
mysql_select_db("$db_name")or die("cannot select DB");

// username and password sent from form 
$myusername=$_POST['myusername']; 
$mypassword=$_POST['mypassword'];

// To protect MySQL injection 
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);

$sql="SELECT * FROM users WHERE username='$username' AND password='$password' AND activated='0'";
$result=mysql_query($sql);

// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row

if($count==0){
// Register $myusername, $mypassword and redirect to file "login_success.php"
session_register("myusername");
session_register("mypassword"); 
header("location:login_success.php");
}
else {
echo "Wrong Username or Password";
}
?>
Member Avatar for diafol
session_register("myusername");
session_register("mypassword");

Don't do this.

Place session_start(); at the top of the page.

Then where your session_register stuff goes, do

$_SESSION['myusername'] = $myusername;

instead.

Then if you have session_start() at the top of EVERY page, the session variable $_SESSION will be available throughout. If you do not place session_start() in a page, you may find that you kill off the variable(s).

@ardav: So do I just take out the part that says

session_register("myusername");
session_register("mypassword");

or do I take out that whole function as follows:

if($count==0){
// Register $myusername, $mypassword and redirect to file "login_success.php"
session_register("myusername");
session_register("mypassword"); 
header("location:login_success.php");
}
else {
echo "Wrong Username or Password";
}

sorry for sounding dumb..

Member Avatar for diafol

get rid of all register stuff - it's not good. but rem the session_start(); at top of every page.

@ardav: Ok I added the session() to every page and placed the "if" statement at the top of one of the pages to do a test run and this error showed up which makes no sense because the linking that it says it's in doesn't exist and it says there is a parse syntax error which I don't seem to see..Here is the error "Parse error: syntax error, unexpected $end in C:\Program Files (x86)\EasyPHP-5.3.8.1\www\Test\Blog.php on line 147" and here is the blog page:

<?php
session_start();
if(!isset($_SESSION['username']) || empty($_SESSION['username'])){
  header('Location: logIn.php');
  exit;
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>
</title>
<link rel="stylesheet" type="text/css" href="CSS/style.css" />
<meta name="description" content="This book will give women, men, and teenagers a different perspective on pregnancy and your life immediately following having kids. This story describes my overall experience being pregnant. This book will prepare all women to make sure that they are ready to get pregnant! I hope you enjoy!!!" />
<meta name="keywords" content="Tahirih Pellegrino,teen,teen mother,TEEN MOTHER,struggle,life,Baby,babysitting,childbirth,pregnancy,giving birth,hospital,health,mom,being a mom,parent,being a parent,Ready or Not,books,story,blog,blogs,email,family," />
<script type="text/javascript">
function preload(arrayOfImages) {
    $(arrayOfImages).each(function(){
        $('<Images/>')[0].src = this;
        // Alternatively you could use:
        // (new Images()).src = this;
    });
}

// Usage:

preload([
    'Images/butterfly-background.jpg',
    'Images/book cover2 another version1.jpg',
    'Images/facebook-logo-pink.png'
	'Images/Email-icon.jpg'
	'Images/header-background.jpg'
	'menu-background.jpg'
]);
</script>
</head>
<body>
<div class="container">
<div id="main-pic">
<a href="AboutMe.html"><div id="main-pic-background"><img src="Images/Tahirih.jpeg" width="240px" height="327px" /></div><!-- end of #main-pic-background --></a>
</div><!-- end of #main-pic -->
<div id="side-pic1"><a href="#"><table style="margin-left: 4px; margin-top: 4px;" border="0" width="204px" height="54" cellpadding="0" cellspacing="0">
       <tr>
	<td style="border-top: 1px solid purple; border-left: 1px solid purple; border-bottom: 1px solid purple; padding-left: 5px; padding-right: 15px;"><img src="Images/facebook-logo-pink.png" width="38px" height="38px" /></td>
	<td style="border-top: 1px solid purple; border-right: 1px solid purple; border-bottom: 1px solid purple; color: #000;">Become A Fan of Tahirih on Facebook</td>
       </tr>
</table></a>
</div><!-- end of #sid-pic1 -->
<div id="side-pic2"><a href="EmailForm.html" target="_blank"><div class="inner-side-pic2"><img src="Images/Email-icon.jpg" width="50px" height="40px" /><div class="inner-side-pic2-text">Shoot Tahirih an Email!!<!-- end of .inner-side-pic-text --></div></div><!-- end of .inner-side-pic2 --></a></div><!-- end of #side-pic2 -->
<div id="side-pic3">
<a href="Buy.php"><img src="Images/book cover2 another version1.jpg" width="210px" height="300px" /></a></div><!-- end of #side-pic3 -->
<div id="Archives"><p class="archives">Archives</p></div><!-- end of #Archives -->
<div id="Archives-content">
<p class="Archives-content-text"><i>Check Out My Recent Posts!</i></p>
<ul>
	<li><a href="#">November</a></li>
</ul>
</div><!-- end of #Archives-content -->
<div id="side-pic5">
<div class="inner-side-pic5">
<div class="inner-side-pic5-text">
<h3 style="font-size: 20px; font-weight: bold; margin-left: 10px;"><u>Recent Blog Posts</u></h3>
<ul>
	<li><span class="headline"><b>No blogs Have been posted at this time.<b></span></li><br />
	<li><span class="headline">Please check back later for more updates!</b></span></li>
</ul>
</div><!-- end of inner-side-pic4-text -->
</div><!-- end of .inner-side-pic5 -->
</div><!-- end of #side-pic5 -->
<div id="header">
<div id="nav-header">
<a href="index.php"><h1><i>Tahirih Pellegrino</i></h1><h2><i><u>Ready or Not!!</u></i></h2></a>
</div><!-- end of nav-header -->
</div><!-- end of #header -->
<div id="menu">
<ul>
<li><a href="Register1.php">Register</a></li>
<li><a href="logout.php">Sign Out</a></li>
<li><a href="index.php">Home</a></li>
<li><a href="AboutMe.html">About Me</a></li>
<li><a href="Blog.php">Blog</a></li>
<li><a href="Buy.php">Buy Now</a></li>
<li><a href="ContactMe.html">Contact Me</a></li>
</ul>
</div><!-- end of #menu -->
<div id="content">
<div id="login-content">
<form action="checkuser.php" method="post" name="" id="">
  <table width="40%" border="0" align="center" cellpadding="4" cellspacing="0">
    <tr> 
      <td width="22%">Username</td>
      <td width="75%"><input name="username" type="text" id="username"></td>
    </tr>
    <tr> 
      <td>Password</td>
      <td><input name="password" type="password" id="password"></td>
    </tr>
    <tr> 
      <td>&nbsp;</td>
      <td><input type="submit" name="Submit" value="Submit"></td>
    </tr>
  </table>
  <div style="margin-left: 30px; margin-top: 5px;">
	Not a member? Click <a href="Register1.php">here</a>.
	</div>
</form>
</div><!--end of #login-content-->
<div id="inner-content">
<div class="subnav">
<p class="title1">~My Blog~</p><p>
<p style="width: 480px; font-size: 19px; text-align: left;">No Blogs have been posted at this time. Please come back later to check back to see if there are any updates!</p>
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<div style="clear: both;"></div>
</div><!-- end of .subnav -->
</div><!-- end of #inner-content -->
<div id="footer">
<div class="left">
&copy; 2011 Tahirih Pellegrino, All Rights Reserved
</div><!-- end of .left -->
<div class="right">
Web Design by <a href="http://www.facebook.com/pages/Gene-Howell/166880296733102?sk=info" target="_blank">Gene Howell</a>. Hosting by <a href="http://www.godaddy.com/default.aspx" target="_blank">Godaddy.com</a>
</div><!-- end of .right -->
</div><!-- end of #footer -->
</div><!-- end of #content -->
</div><!-- end of .container -->
</body>
</html>

Close the if statement
Add } after exit(); (line no:5)

And make sure you have given the correct file name for redirection and add exit statement next to it

header('Location: logIn.php');
exit;

@Samueal: ok I did that however, I must not have coded the sessions as suggested by ardav in the checkuser.php because it says there is an error: "Parse error: syntax error, unexpected T_STRING in /home/content/98/8447998/html/checkuser.php on line 32"

here is the code for check user:

<?php
$host="*********************"; // Host name 
$username="****************"; // Mysql username 
$password="************"; // Mysql password 
$db_name="**********"; // Database name 
$tbl_name="users"; // Table name

// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect"); 
mysql_select_db("$db_name")or die("cannot select DB");

// username and password sent from form 
$username=$_POST['username']; 
$password=$_POST['password'];

// To protect MySQL injection 
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);

$sql="SELECT * FROM users WHERE username='$username' AND password='$password' AND activated='0'";
$result=mysql_query($sql);

// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row

if($count==0){
// Register $myusername, $mypassword and redirect to file "login_success.php"
$_SESSION['username'] = $username
header("location:login_success.php");
}
else {
echo "Wrong Username or Password";
}
?>

Also, do I need to do the same thing to the password with the session or just the username?

Member Avatar for diafol
$_SESSION['username'] = $username

needs a ; at the end on line 31.

wow...I can't believe I missed that..

anyways..it logs me in but once I log in and go to that page that requires a log in...it still directs me to the log in page for some reason..

Member Avatar for diafol

I don't understand what you mean. Show the relevant code that causes this behaviour.

@ardav: Well there isn't an error message that pops up, but when I echo out the username on the page that is supposed to be log in protected, it shows the words "username:" ..and then nothing which tells me there's got to be something wrong with the checkuser.php that I use to check if the user has logged in on the log in page..

also I would go through the process of logging in because obviously the blog page (the page I have login protected) needs to have actual members view that particular page, but it still redirects me to the login page, after I logged in..Here are the codes for the checkuser.php:

<?php
session_start();

$host="****************************"; // Host name 
$username="*************"; // Mysql username 
$password="********"; // Mysql password 
$db_name="**************"; // Database name 
$tbl_name="users"; // Table name

// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect"); 
mysql_select_db("$db_name")or die("cannot select DB");

// username and password sent from form 
$username=$_POST['username']; 
$password=$_POST['password'];

// To protect MySQL injection 
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);

$sql="SELECT * FROM users WHERE username='$username' AND password='$password' AND activated='0'";
$result=mysql_query($sql);

// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row

if($count==0){
// Register $myusername, $mypassword and redirect to file "login_success.php"
$_SESSION['username'] = $username;
header("location:login_success.php");
}
else {
echo "Wrong Username or Password";
}
?>

and here is the blog page(the page that gets redirected to the login page even when logged in)
blog.php

<?php

session_start();

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>
</title>
<link rel="stylesheet" type="text/css" href="CSS/style.css" />
<meta name="description" content="This book will give women, men, and teenagers a different perspective on pregnancy and your life immediately following having kids. This story describes my overall experience being pregnant. This book will prepare all women to make sure that they are ready to get pregnant! I hope you enjoy!!!" />
<meta name="keywords" content="Tahirih Pellegrino,teen,teen mother,TEEN MOTHER,struggle,life,Baby,babysitting,childbirth,pregnancy,giving birth,hospital,health,mom,being a mom,parent,being a parent,Ready or Not,books,story,blog,blogs,email,family," />
<script type="text/javascript">
function preload(arrayOfImages) {
    $(arrayOfImages).each(function(){
        $('<Images/>')[0].src = this;
        // Alternatively you could use:
        // (new Images()).src = this;
    });
}

// Usage:

preload([
    'Images/butterfly-background.jpg',
    'Images/book cover2 another version1.jpg',
    'Images/facebook-logo-pink.png'
	'Images/Email-icon.jpg'
	'Images/header-background.jpg'
	'menu-background.jpg'
]);
</script>
</head>
<body>
<div class="container">
<div id="main-pic">
<a href="AboutMe.html"><div id="main-pic-background"><img src="Images/Tahirih.jpeg" width="240px" height="327px" /></div><!-- end of #main-pic-background --></a>
</div><!-- end of #main-pic -->
<div id="side-pic1"><a href="#"><table style="margin-left: 4px; margin-top: 4px;" border="0" width="204px" height="54" cellpadding="0" cellspacing="0">
       <tr>
	<td style="border-top: 1px solid purple; border-left: 1px solid purple; border-bottom: 1px solid purple; padding-left: 5px; padding-right: 15px;"><img src="Images/facebook-logo-pink.png" width="38px" height="38px" /></td>
	<td style="border-top: 1px solid purple; border-right: 1px solid purple; border-bottom: 1px solid purple; color: #000;">Become A Fan of Tahirih on Facebook</td>
       </tr>
</table></a>
</div><!-- end of #sid-pic1 -->
<div id="side-pic2"><a href="EmailForm.html" target="_blank"><div class="inner-side-pic2"><img src="Images/Email-icon.jpg" width="50px" height="40px" /><div class="inner-side-pic2-text">Shoot Tahirih an Email!!<!-- end of .inner-side-pic-text --></div></div><!-- end of .inner-side-pic2 --></a></div><!-- end of #side-pic2 -->
<div id="side-pic3">
<a href="Buy.php"><img src="Images/book cover2 another version1.jpg" width="210px" height="300px" /></a></div><!-- end of #side-pic3 -->
<div id="Archives"><p class="archives">Archives</p></div><!-- end of #Archives -->
<div id="Archives-content">
<p class="Archives-content-text"><i>Check Out My Recent Posts!</i></p>
<ul>
	<li><a href="#">November</a></li>
</ul>
</div><!-- end of #Archives-content -->
<div id="side-pic5">
<div class="inner-side-pic5">
<div class="inner-side-pic5-text">
<h3 style="font-size: 20px; font-weight: bold; margin-left: 10px;"><u>Recent Blog Posts</u></h3>
<ul>
	<li><span class="headline"><b>No blogs Have been posted at this time.<b></span></li><br />
	<li><span class="headline">Please check back later for more updates!</b></span></li>
</ul>
</div><!-- end of inner-side-pic4-text -->
</div><!-- end of .inner-side-pic5 -->
</div><!-- end of #side-pic5 -->
<div id="header">
<div id="nav-header">
<a href="index.php"><h1><i>Tahirih Pellegrino</i></h1><h2><i><u>Ready or Not!!</u></i></h2></a>
</div><!-- end of nav-header -->
</div><!-- end of #header -->
<div id="menu">
<ul>
<li><a href="Register1.php">Register</a></li>
<li><a href="logout.php">Sign Out</a></li>
<li><a href="index.php">Home</a></li>
<li><a href="AboutMe.html">About Me</a></li>
<li><a href="Blog.php">Blog</a></li>
<li><a href="Buy.php">Buy Now</a></li>
<li><a href="ContactMe.html">Contact Me</a></li>
</ul>
</div><!-- end of #menu -->
<div id="content">
<div id="login-content">
<form action="checkuser.php" method="post" name="" id="">
  <table width="40%" border="0" align="center" cellpadding="4" cellspacing="0">
    <tr> 
      <td width="22%">Username</td>
      <td width="75%"><input name="username" type="text" id="username"></td>
    </tr>
    <tr> 
      <td>Password</td>
      <td><input name="password" type="password" id="password"></td>
    </tr>
    <tr> 
      <td>&nbsp;</td>
      <td><input type="submit" name="Submit" value="Submit"></td>
    </tr>
  </table>
  <div style="margin-left: 30px; margin-top: 5px;">
	Not a member? Click <a href="Register1.php">here</a>.
	</div>
</form>
</div><!--end of #login-content-->
<div id="inner-content">
<div class="subnav">
<p class="title1">~My Blog~</p><p>
<p style="width: 480px; font-size: 19px; text-align: left;">No Blogs have been posted at this time. Please come back later to check back to see if there are any updates!</p>
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<div style="clear: both;"></div>
</div><!-- end of .subnav -->
</div><!-- end of #inner-content -->
<div id="footer">
<div class="left">
&copy; 2011 Tahirih Pellegrino, All Rights Reserved
</div><!-- end of .left -->
<div class="right">
Web Design by <a href="http://www.facebook.com/pages/Gene-Howell/166880296733102?sk=info" target="_blank">Gene Howell</a>. Hosting by <a href="http://www.godaddy.com/default.aspx" target="_blank">Godaddy.com</a>
</div><!-- end of .right -->
</div><!-- end of #footer -->
</div><!-- end of #content -->
</div><!-- end of .container -->
</body>
</html>

Hey everyone, I fixed my issue..turns out I forgot a session destroy function along with declaring the password variable in the login check..it's all fixed now! Thanks for everyone's help and patience with my fairly new experience with php!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.