开发者

pass value from page to another in PHP

开发者 https://www.devze.com 2022-12-30 02:07 出处:网络
I am sending login status = fail, b开发者_如何学Cack to my login page.Here is my code- header(\"location:index.php?login=fail\");

I am sending login status = fail, b开发者_如何学Cack 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?


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.


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.......
}


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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号