php - URL opening in all browsers even when user not logged in?

873

My url is opening in all browsers even when I am using sessions. Ex abc.com/123.php without users logged in. This opens up in all browsers. I am using this code.All codes are in < php open/close tags ok codes which ia m using are

         <?php
       session_start();

         if (isset($_SESSION['LAST_REQUEST_TIME'])) {
     if (time() - $_SESSION['LAST_REQUEST_TIME'] > 600) {
    // session timed out, last request is longer than 10 minutes ago
    unset($_SESSION);
    session_destroy();
    header("location:userlogin.php");
}
  } else {
$_SESSION['LAST_REQUEST_TIME'] = time();
   }

        if($_SESSION['username']=="");
        ?>
779

Answer

Solution:

I am not sure that this compiles well. Because there are a couple of problems.

Be careful with this line of code:

if($_SESSION['username']=="");

This means thattrue part of thisif statement finishes at semicolon.

Second thing is that yourelse part is never executed but printed as regular HTML.

I would write it like this:

<?php
session_start();

if (isset($_SESSION['LAST_REQUEST_TIME'])) {
  if (time() - $_SESSION['LAST_REQUEST_TIME'] > 600) {
    // session timed out, last request is longer than 10 minutes ago
    unset($_SESSION);
    session_destroy();
    header("location:userlogin.php");
  }
} else {
  $_SESSION['LAST_REQUEST_TIME'] = time();
}

if(isset($_SESSION['username'])) {
?>
 ///////SOME HTML CODE/////

<?php
} else {
  header("location:to_some_login_page.php");
}
?>

And I believe that is what you intended to to with closing<?php tag.

Also for readability I suggest you to do just this:

if ($_SESSION['username']!="") {
  header("location:to_some_login_page.php");
}

So you don't even need else part, because as soon as header is set, he will be redirected.

287

Answer

Solution:

Because your

else {
header("location:to_some_login_page.php");
   }

is outside of<?php ?>

Try This:

<?php
session_start();

if (isset($_SESSION['LAST_REQUEST_TIME'])) {
if (time() - $_SESSION['LAST_REQUEST_TIME'] > 600) {
    // session timed out, last request is longer than 10 minutes ago
    unset($_SESSION);
    session_destroy();
    header("location:userlogin.php");
}
else {
$_SESSION['LAST_REQUEST_TIME'] = time();
 }

 if($_SESSION['username']=="");

 ///////your code/////

}
else {
header("location:to_some_login_page.php");
   }
?>

People are also looking for solutions to the problem: php - Template Parse Error SMF

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.