I'm trying to create a simple members only section. With the following code, I'm able to log in and get redirected to a page (that simply says: "hello") if the login is correct. If I then copy the URL from the page to which I was redirected, open up IE, and then paste the copied URL into the browser window, I'm told to log in. I would like to add a full web page of HTML (so that I can take advantage of CSS functionality and because I'm not that adept at PHP) to the redirected page, keeping it as a .php file, of course. Can someone help?


The current code is:


EXAMPLE_SESSION_FUNCTIONS.php

<?php
ini_set( 'session.name', 's' );
/* the URL to the login page*/
define( 'URL_LOGIN_PAGE', 'EXAMPLE_LOGIN.php' );

// start the session...
session_start();

/* check for valid user */
if( !defined('LOGGING_IN') )
{
  verify_if_valid_user();
}


function match_user_in_db( $user, $pass )
{
$host="localhost"; // Host name 
$username="a"; // Mysql username 
$password="b"; // Mysql password 
$db_name="c"; // Database name 
$tbl_name="d"; // Table name 

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

// Define $myusername and $mypassword 
$myusername=$_POST['username']; 
$mypassword=$_POST['password']; 

// To protect MySQL injection 
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
$sql="SELECT username FROM $tbl_name WHERE username='$myusername' and password='$mypassword'";
$result=mysql_query($sql);

  if( mysql_num_rows($result)==1 )
  {
    $_SESSION['valid_user'] = mysql_result( $result, 0, 0 );

Echo "<a href=http://www.myURL.com/EXAMPLE_TEST_PAGE.php</a>" ;

  }
  else
  {
Echo "Invalid login";
Echo "<a href=http://www.myURL.com/EXAMPLE_LOGIN.php>Login again!</a>" ;
  }
}


function process_login()
{
  $username = mysql_escape_string( trim($_POST['username']) );
  $password =  ($_POST['password']);



  match_user_in_db( $username, $password );  
}


function process_logout()
{
  /* used ONLY in the LOGOUT page.  */
  session_destroy();
  unset( $_SESSION );

Echo "You are logged out.";

}

function verify_if_valid_user()
{
  if( !isset($_SESSION['valid_user']) )
  {
    // user not logged in yet!
    // re-direct them to the login page

Echo "You are not logged in.";
Echo "<a href=http://www.myURL.com/EXAMPLE_LOGIN.php>Login now!</a>" ;

  }
}
?>

EXAMPLE_LOGOUT.php

<?php
// FILENAME: EXAMPLE_LOGOUT.PHP
// ---------------------------------------

include_once( 'EXAMPLE_SESSION_FUNCTIONS.php' );
process_logout();
?>

EXAMPLE_LOGIN.php

<?php
if( isset($_POST['user_login']) )
{
  define( 'LOGGING_IN', true );
  // include the 'session functions' file
  include_once( 'EXAMPLE_SESSION_FUNCTIONS.php' );
  process_login();
}
else
{
?>
<html>
<head>
<title>Login Page</title>
</head>
<body>
<h1>Login Here</h1>
<form name="loginform" id="loginform" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
  <p>
    <input name="username" type="text" id="username" size="30" maxlength="30" />
    Username</p>
  <p> 
    <input name="password" type="password" id="password" size="30" maxlength="30" />
    Password</p>
  <p>
    <input type="submit" name="user_login" value="Submit" />
  </p>
</form>
</body>
</html>
<?php
}
?>

EXAMPLE_TEST_PAGE.php
THIS IS WHERE I WANT TO ADD A FULL HTML PAGE, REPLACING THE "echo "Hello";" with a full page of HTML code so that the only way to access that HTML page is to log in.

<?php
include_once( 'EXAMPLE_SESSION_FUNCTIONS.php' );
?>

<html>
<head>
<title>TEST PAGE</title>
</head>
<body>

<?php
if ($_SESSION['valid_user'])

{
echo "Hello";//WANT TO REPLACE WITH A FULL HTML PAGE TO ACHIEVE RESULTS SPECIFIED ABOVE 
}


session_destroy();
?>

</body>
</html>

Dani AI

Generated

A few focused points that tie the thread together and make the example safe and reliable years later.

The clean, recommended pattern is: start the session at the very top, check the session flag before any output, redirect and exit if the user is not logged in, and then emit the page HTML normally. That is the idea demonstrated; was right that a .php can contain plain HTML, but that alone does not provide access control. Two bugs to watch for in the posted code: calling session_destroy() inside the protected page (that will log users out immediately), and using echo-only checks that emit messages instead of redirecting and exiting (so code after the message may still run).

Example top-of-protected-page pattern:

<?php
require_once 'EXAMPLE_SESSION_FUNCTIONS.php'; // should call session_start()
if (empty($_SESSION['valid_user'])) {
    header('Location: EXAMPLE_LOGIN.php');
    exit;
}
// protected HTML may follow here (no need to echo it)
?>
<!doctype html>
<html>
<head><title>Members area</title></head>
<body>
  <!-- members-only content -->
</body>
</html>

Practical security and debugging tips:

  • Remove any accidental session_destroy() from the protected page; use it only in the logout script.
  • Make verify_if_valid_user() perform a header('Location: ...') + exit instead of just echoing text.
  • Remember cookies: copying the URL into the same browser (with the session cookie present) will show the page; opening a fresh browser profile or private window will not. That explains the browser-to-browser differences reported.
  • Upgrade the login flow: stop using deprecated mysql_* calls, store password hashes (password_hash/password_verify), use prepared statements (PDO or mysqli), call session_regenerate_id(true) on successful login, and set cookie flags (HttpOnly, Secure) when serving over HTTPS.

Those changes preserve the simple HTML/CSS workflow while making the members-only protection robust and secure.

Recommended Answers

All 11 Replies

I'm trying to create a simple members only section. With the following code, I'm able to log in and get redirected to a page (that simply says: "hello") if the login is correct. If I then copy the URL from the page to which I was redirected, open up IE, and then paste the copied URL into the browser window, I'm told to log in. I would like to add a full web page of HTML (so that I can take advantage of CSS functionality and because I'm not that adept at PHP) to the redirected page, keeping it as a .php file, of course. Can someone help?


The current code is:


EXAMPLE_SESSION_FUNCTIONS.php

<?php
ini_set( 'session.name', 's' );
/* the URL to the login page*/
define( 'URL_LOGIN_PAGE', 'EXAMPLE_LOGIN.php' );

// start the session...
session_start();

/* check for valid user */
if( !defined('LOGGING_IN') )
{
  verify_if_valid_user();
}


function match_user_in_db( $user, $pass )
{
$host="localhost"; // Host name 
$username="a"; // Mysql username 
$password="b"; // Mysql password 
$db_name="c"; // Database name 
$tbl_name="d"; // Table name 

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

// Define $myusername and $mypassword 
$myusername=$_POST['username']; 
$mypassword=$_POST['password']; 

// To protect MySQL injection 
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
$sql="SELECT username FROM $tbl_name WHERE username='$myusername' and password='$mypassword'";
$result=mysql_query($sql);

  if( mysql_num_rows($result)==1 )
  {
    $_SESSION['valid_user'] = mysql_result( $result, 0, 0 );

Echo "<a href=http://www.myURL.com/EXAMPLE_TEST_PAGE.php</a>" ;

  }
  else
  {
Echo "Invalid login";
Echo "<a href=http://www.myURL.com/EXAMPLE_LOGIN.php>Login again!</a>" ;
  }
}


function process_login()
{
  $username = mysql_escape_string( trim($_POST['username']) );
  $password =  ($_POST['password']);



  match_user_in_db( $username, $password );  
}


function process_logout()
{
  /* used ONLY in the LOGOUT page.  */
  session_destroy();
  unset( $_SESSION );

Echo "You are logged out.";

}

function verify_if_valid_user()
{
  if( !isset($_SESSION['valid_user']) )
  {
    // user not logged in yet!
    // re-direct them to the login page

Echo "You are not logged in.";
Echo "<a href=http://www.myURL.com/EXAMPLE_LOGIN.php>Login now!</a>" ;

  }
}
?>

EXAMPLE_LOGOUT.php

<?php
// FILENAME: EXAMPLE_LOGOUT.PHP
// ---------------------------------------

include_once( 'EXAMPLE_SESSION_FUNCTIONS.php' );
process_logout();
?>

EXAMPLE_LOGIN.php

<?php
if( isset($_POST['user_login']) )
{
  define( 'LOGGING_IN', true );
  // include the 'session functions' file
  include_once( 'EXAMPLE_SESSION_FUNCTIONS.php' );
  process_login();
}
else
{
?>
<html>
<head>
<title>Login Page</title>
</head>
<body>
<h1>Login Here</h1>
<form name="loginform" id="loginform" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
  <p>
    <input name="username" type="text" id="username" size="30" maxlength="30" />
    Username</p>
  <p> 
    <input name="password" type="password" id="password" size="30" maxlength="30" />
    Password</p>
  <p>
    <input type="submit" name="user_login" value="Submit" />
  </p>
</form>
</body>
</html>
<?php
}
?>

EXAMPLE_TEST_PAGE.php
THIS IS WHERE I WANT TO ADD A FULL HTML PAGE, REPLACING THE "echo "Hello";" with a full page of HTML code so that the only way to access that HTML page is to log in.

<?php
include_once( 'EXAMPLE_SESSION_FUNCTIONS.php' );
?>

<html>
<head>
<title>TEST PAGE</title>
</head>
<body>

<?php
if ($_SESSION['valid_user'])

{
echo "Hello";//WANT TO REPLACE WITH A FULL HTML PAGE TO ACHIEVE RESULTS SPECIFIED ABOVE 
}


session_destroy();
?>

</body>
</html>

If I underatand what your asking (which is more of how to implement the HTML page instead of the proper PHP syntax, I would use something like the following. This code prevents you from having to echo HTML (meaning it will parse as is) while keeping it within the confines of the if statement

<?PHP if (whatever = whatever) { ?>

[B][Insert HTML Code Here][/B]

<?PHP } ?>

Is that what you were looking for?

No, I already tried that. The result is that when I login, using EXAMPLE_LOGIN.php, I am directed to the page (which is fine). However, when I then copy the URL, and open IE again and paste the URL into the browser window, I am sent directly to the page, without having to log in again. In the current setup, above, I am asked to log in (by the verify_if_valid(user) function).

If you replace lines 14-16, with a simple:

<p>hello</p>

and close off the php, before and after that html code, you'll see what I mean...

Any other thoughts?

Member Avatar for Member #120589

php files do not have to include any php. they can be plain old html. just don't include any php or php tags.

php files do not have to include any php. they can be plain old html. just don't include any php or php tags.

Ok. But that doesn't solve my problem. I need an "if" statement to check the database to see if there's an ID and password. I'm using PHP to do this. Then I want to embed some HTML in between the PHP. Only users with a valid ID and password should be able to see the HTML.

Thoughts?

Member Avatar for Member #120589

Sorry mgt - I misread - probably the Guinness!

jrotunda has the solution I believe.

JRotunda,

My bad - that worked....I must have left out a "{" or put something in the wrong place...., the first time I tried it

If I underatand what your asking (which is more of how to implement the HTML page instead of the proper PHP syntax, I would use something like the following. This code prevents you from having to echo HTML (meaning it will parse as is) while keeping it within the confines of the if statement

<?PHP if (whatever = whatever) { ?>

[B][Insert HTML Code Here][/B]

<?PHP } ?>

Is that what you were looking for?

Thanks for your help, JRotunda!!!!!

Member Avatar for Member #120589

if solved, mark it so.

if solved, mark it so.

This is my first post in over 2 years. I'm not sure how to mark it "solved".

This is my first post in over 2 years. I'm not sure how to mark it "solved".

Link at the bottom

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.