Jump to content

Redirecting a user that is not logged in?


phreak3r

Recommended Posts

Hi there PHPFreaks! Phreak3r back again! I would like to restrict users/visitors to the site that are not logged in from access certain pages, I would also like to redirect them to the 'splash/landing page' which would consist of index.php. I already have something similar to what I am describing, except it only works with displaying register/login and logout in/on the navigation bar. I have tried many attempts which have all resulted in some sort of failure. Thank you for your answers and your time!

 

Here's the code for the header page that display the navbar and checks if the user is logged in or not:

<?php
// Session is automatically incorporated into each page on the site.
// Start new session.
    session_start();
?>

<html>
  <head>
    <meta content="text/html;charset=utf-8" http-equiv="Content-Type">
    <meta content="utf-8" http-equiv="encoding">
    <!-- <link rel="stylesheet" type="text/css" href="/css/header.css"> -->
  </head>

  <nav>
    <a class="logo">soapbox</a>
	
	<?php if (!(isset($_SESSION['logged_in_user']))) {
      //header('Location: /');
			echo '<ul><li><a class="header" href="signup.php">Register | </a><a class="header" href="login.php">Login</a></li></ul>';
		} elseif ($_SESSION['logged_in_user'] == TRUE) {
			echo '<ul><li><a class="header" href="logout.php">Logout</a> <a class="header" href="">'. $_SESSION['username'] . '</a></li></ul>';
		}
	?>
  </nav>

Here's the code for the login.php script

<?php
include('header.php');
require('dbcon/dbcon.php');
?>

<?php

	// if fields in form are set and submitted, check if user exists and is logged in or not
	if (isset($_POST['submit'])) {
		$username = mysqli_real_escape_string($conn, $_POST['username']);
		$password = mysqli_real_escape_string($conn, $_POST['password']);
		$user_query = "SELECT * FROM profile0 WHERE username = '$username'";
		$result = mysqli_query($conn, $user_query);
		$row = mysqli_fetch_assoc($result);

		// if username and password match, init session and redirect to another page.
		if (mysqli_num_rows($result) == 1 && password_verify($password, $row['password'])) {
			$_SESSION['logged_in_user'] = $username; // set to IDnum later on...
			$_SESSION['username'] = $username;		
			// check if the user is logged in
			if (isset($_SESSION['logged_in_user'])) {
				$_SESSION['logged_in_user'] = TRUE;
				header('Location: main.php');
			} else {
				// not logged in, keep on same page...
				session_destroy();
				exit();
			}
		} // HERE: else incorrect username or password error sent out.
	}
?>

P.S. If there are any errors or if something seems off, please excuse that, I am very tired at the moment and do not sleep with any problems being unsolved.

Link to comment
Share on other sites

<a class="logo">soapbox</a>
	
	<?php if (!(isset($_SESSION['logged_in_user']))) {
      //header('Location: /');
You cannot redirect if there has been any output. Move that bit of logic to the "top" of your script.

 

 

Thank you, but it still does not seem to work correctly.

Link to comment
Share on other sites

We talked about a couple things in this thread  that you still have not implemented. You are still checking for the name of a button to be submitted instead of checking the Server Request Method. I gave you the exact one line copy/paste code. You are still putting variables in your query instead of using prepared statements.

 

It is still bothering you, eh? Gee... I am still checking for the name of a button to be submitted? Well, it works apparently, no errors. Is it necessary to change it? Fine, I will use those prepared statements.

Link to comment
Share on other sites

I'm sorry, I thought you were actually wanting to learn and do things correctly. If your OK with "it works" then perhaps someone else is better suited to help you.

 

When the form doesn't work, you wont even know it didn't. There are certain cases where it will completely fail and you will not get any errors. You don't know what you don't know.

Link to comment
Share on other sites

I'm sorry, I thought you were actually wanting to learn and do things correctly. If your OK with "it works" then perhaps someone else is better suited to help you.

 

When the form doesn't work, you wont even know it didn't. There are certain cases where it will completely fail and you will not get any errors. You don't know what you don't know.

 

I do, however, there are multiple ways to accomplish something. But, I will stop being hard-headed and add it in.

Link to comment
Share on other sites

In this instance, there is only ONE way that will ALWAYS work in all cases. It is not an opinion, it just is. You would do well to learn how and why your current approach could fail instead of just doing it because someone told you to.

 

Sounds conservative in thought, but I will take it. Do you think I am re-inventing the wheel here? I have gotten that from many who have suggested the utilization of a framework.

 

EDIT: I put 'submit' as a name in the input name field. I thought that would work, well at least it seemed to. But, I am still not understanding if it works with buttons, how you described it.

Link to comment
Share on other sites

How about try it and see what happens?

 

Here is what the manual says about Request Method

'REQUEST_METHOD' Which request method was used to access the page; i.e. 'GET', 'HEAD', 'POST', 'PUT'.

 

 

So when your form method is POST

<form action="confirmation.php" method="POST">

 

And you you check the Request Method as so, the script knows the form has been submitted using the POST method then the code in that block runs.

if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
//Process form
}
Link to comment
Share on other sites

 

How about try it and see what happens?

 

Here is what the manual says about Request Method

 

 

So when your form method is POST

<form action="confirmation.php" method="POST">

 

And you you check the Request Method as so, the script knows the form has been submitted using the POST method then the code in that block runs.

if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
//Process form
}

 

Okay. Well, if this way works best and is the most efficient method, then why are all other methods not deprecated/why is one still allowed to use them? Just does not make any sense to me. Now, from what I understand prepared statements and PDO are two different things, yes? Is there anything I need to setup or reconfigure to get going with the prepared statements? There are not too many good resources on both prepared statements and PDO, at least the ones I have come across are not so good. Would you in any case use the method I was using before but if it were applied in a correct manner? For the record, I have re-added the line of code above back in. I didn't have it in, then I added it in the first time you gave an answer in a previous thread, then I found a way to make it work, so I removed your suggest code. But, now it is back in the script.

 

EDIT: It was suggested that PDO is better than the mysqli_extension, so if you have any advice on how to start with PDO, that would be great. I took a look at what you linked me to on PDO in a previous thread, but the information did not seem to offer anything on how to actually 'add' the extension in. From what I understand PDO is something that you have to add in before you can use it with the code? :grimacing:

Link to comment
Share on other sites

You may already have PDO enabled. Run a phpinfo script and you can see if it is there.

 

Yes, PDO and Prepared Statements are two different things. You need to use both. The tutorial I gave you has it covered.

 

Indeed, it is enabled. Ahem, so I do need both? I thought the opposite, well...interesting... If you say so.

 

post-206807-0-24827900-1516646970_thumb.png

Link to comment
Share on other sites

You may already have PDO enabled. Run a phpinfo script and you can see if it is there.

 

Yes, PDO and Prepared Statements are two different things. You need to use both. The tutorial I gave you has it covered.

 

I hate to double post, but I'm doing it anyway. So, I have tried to set up a connection using PDO according to the hashphp wiki, I have ran into an error.

 

Here's the code in dbcon/dbcon.php:

<?php
/*$host   = "localhost";
$database = "soapbox";
$username = "root";
$password = "1234";

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

// Create connection
$conn = mysqli_connect($host, $username, $password, $database);
mysqli_select_db($conn, $database); */

$db = new PDO('mysqli: host = localhost; dbname = soapbox; charset = utf8mb4', 'root', '1234');
$db -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db -> setAttribute(PDO::ATTR_EMULATES_PREPARES, false);

/*if (!$conn) {
	die("Connection failed: " . mysqli_connect_error());
} else {
	echo "Connection successful!";
}

if (!mysqli_select_db($conn, $database)) {
	echo " Database not selected!";
} else {
	echo " Database selected!";
}*/
?>

And here's the error received:

 

Fatal error: Uncaught PDOException: could not find driver in /var/www/html/soapbox/dbcon/dbcon.php:13 Stack trace: #0 /var/www/html/soapbox/dbcon/dbcon.php(13): PDO->__construct('mysqli: host = ...', 'root', '1234') #1 /var/www/html/soapbox/login.php(3): require('/var/www/html/s...') #2 {main} thrown in /var/www/html/soapbox/dbcon/dbcon.php on line 13

Link to comment
Share on other sites

Do you see a problem here?

 

$db = new PDO('mysqli: host

 

I sure do 'Master Coder', however even without the 'i' there's still an error with the 'undefined constants'

 

Fatal error: Uncaught Error: Undefined class constant 'ATTR_EMULATES_PREPARES' in /var/www/html/soapbox/dbcon/dbcon.php:18 Stack trace: #0 /var/www/html/soapbox/login.php(3): require() #1 {main} thrown in /var/www/html/soapbox/dbcon/dbcon.php on line 18

Link to comment
Share on other sites

emulates?

 

Whoops. my little silly mistake. Anyways, thank you for recommending me to use PDO and prepared statements, I have been reading up on them. I now understand their exact/intended purpose. Hmm, they even seem to be a bit more understandable and readable compared to the MySQLi statements offered. From what I understand any SQL injection attacks are futile with a combination of prepared statements and PDO? Seems like PDO and prepared statements can only be used in PHP when it comes to handling data. Also, the core issue of this forum has yet to be solved. I am still getting an error with the redirect. I place the beginning portion of the if statement at the very top of the header.php script.

Link to comment
Share on other sites

You need to call session_start() in a script before you access $_SESSION variables. This also needs to go at the top of the script before any output has occured.

 

I do so in the header.php script, it is present on every page on/in the site.

<?php
// Session is automatically incorporated into each page on the site.
// Start new session.
    session_start();
    if (!(isset($_SESSION['logged_in_user']))) {
      //header('Location: soapbox/');
?>

<html>
  <head>
    <meta content="text/html;charset=utf-8" http-equiv="Content-Type">
    <meta content="utf-8" http-equiv="encoding">
    <!-- <link rel="stylesheet" type="text/css" href="/css/header.css"> -->
  </head>

  <nav>
    <a class="logo">soapbox</a>
	
	<?php
			echo '<ul><li><a class="header" href="signup.php">Register | </a><a class="header" href="login.php">Login</a></li></ul>';
		} elseif ($_SESSION['logged_in_user'] == TRUE) {
			echo '<ul><li><a class="header" href="logout.php">Logout</a> <a class="header" href="">'. $_SESSION['username'] . '</a></li></ul>';
		}
	?>
Link to comment
Share on other sites

Since you have not turned on error_reporting in the script does that mean you have enabled it in the php.ini?

 

 

If I have to keep asking the same thing this is going to go very slow.

 

So impatient, I am still trying to convert the code. Maybe I should have kept it in mysqli instead of PDO. I have errors from trying to convert to PDO, I am going to ahead and try to fix those first. ::)

Link to comment
Share on other sites

Have you looked at the PHP Manual to see how one uses pdo functions? It isn't much different from mysqli. You write a query. You prepare the query to produce the 'query statement' variable. You build an array with the parameters for the query. You execute the query statement variable using this array. Then you loop thru the results in the query statement variable using a fetch. Done.

 

There are some very good examples of this in the Manual. I could easily give you a link (and some helpful soul here probably will) but I do think that the exercise of going to the manual and searching for at least one of the pdo functions alone would be a good learning experience for you. :)

 

When trying to learn something new in PHP it's always a good idea to RTFM.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.