Login to Interupt and access the page using PHP / MySQL

I am currently using PHP / MySQL and I would like to know the best way to do a login without user authentication and then automatically redirect them to the page they are logged in to.

For example:

1) The user tries to open a protected page.
2) They are redirected and asked to login.
3) After a successful login, they go back to the url they were trying to access.

I currently have the following PHP code installed on my "secure" pages: (Not even sure if this is the correct way to "secure" it):

<?php
session_start();

 if ($_SESSION['first'] == "" && $_SESSION['usrID'] == "") {

    print" <script>
   window.location=\"../login/index.php\"
   </script> ";

    }

   ?>

      

Any suggestions on how to provide this functionality (and maybe better make my code "safe") I would really appreciate.

Thank!

+2


source to share


2 answers


You can store the requesting url in the var session.

$_SESSION['destination'] = $_SERVER['REQUEST_URI'];

      

Then, after logging in, you can do something like this:

if (isset($_SESSION['destination'])) {

    header('Location: ' . $_SESSION['destination']);
    exit;
}

      



Also, it's not such a good idea

  print" <script>
   window.location=\"../login/index.php\"
   </script> ";

      

Using JavaScript for redirection has problems. First, nothing happens with JavaScript disabled. Try sending location headers

header('Location: ../login/index.php');
exit; // Call exit to make sure the rest of your code never executes

      

+2


source


You can get the referrer URI in the /login/index.php file and pass it to the login form in the hidden field. And after the user logs in, you simply redirect them to the page they previously tried to access.

Something like that:



/login/index.php:

<?php

// if user submitted login form
if(isset($_POST['login'])) {

// do your login actions here
// and after...
header("Location: " . $_POST['returnto']);

}


//

$user_came_from = htmlspecialchars( $_SERVER['HTTP_REFERER'] );

?>
<form name="my_login_form" action="" method="post">
user: <input type="text" name="user" value="" />
pass: <input type="password" name="pass" value="" />
<input type="hidden" name="returnto" value="<?php echo $user_came_from ?>" />
<input type="submit" name="login" value="login" />
</form>

      

+1


source







All Articles