pass value from page to another in PHP

I am sending login status = fail, back to my login page.Here is my code-

header("location:index.php?login=fail");

but that is sending through URL like-

http://localhost/303/index.php?login=fail

is there any way to pass value without showing in URL? And how to get this value on the second page?

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

You are passing that value via a GET request, which is why it appears in the URL. In order to pass a value without showing it in the URL, you want to pass it via a POST request.

In order to do this you aren’t going to want to “return” the value to your login page. Instead, whatever php form is handling the process of logging in the user after they click the “login” button, will decide what to show the user.

In PHP post variables can be accessed by the global $_POST object –

$_POST['username'];

Would get the value with the name “username” that you passed via POST:

<form method="post" action="checkLogin.php">
Username:
<input type="text" name="username" maxlength="25" />
Password: 
</td><td><input type="password" name="password" />
<input type="submit" name="submit" value="Login">
</form>

In order to dynamically save and show errors to the user, you can store them in the session, for example have a file called “errors.php”

<?php
if (isset($_SESSION['errors']))
{
    echo $_SESSION['errors'];
}

unset($_SESSION['errors'])
?>

And in your php that checks the login, do:

session_start();
$_SESSION['errors'] = "Invalid username or password.";

Then redirect to your login page (don’t pass any variables) and on your form always have this field:

<?php include("errors.php"); ?>

If you didn’t have any errors, it won’t show anything and the login page will look normal.

Note: In any php form that you use a session_start(), it HAS TO BE THE FIRST THING in the form.

Solution 2

Other ways are to use session or hidden fields but you what you are doing is fine for the purpose. You can later retrieve the value like this:

if ($_GET['login'] === 'fail')
{
  // failed.......
}

Solution 3

there are several ways to accomplish your task

  • Modern AJAX way. Form being sent using AJAX. No page reload until password is correct. Errors shown in place. Requres javascript.
  • Post/Redirect/Get pattern. Form being sent using regular POST. No redirect on errors, shown in place.
  • sessions, when we store an error in the session

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply