开发者

How to redirect to another page using PHP [duplicate]

开发者 https://www.devze.com 2023-02-08 05:34 出处:网络
This question already has answers here: 开发者_Go百科 How do I make a redirect in PHP? (34 answers)
This question already has answers here: 开发者_Go百科 How do I make a redirect in PHP? (34 answers) Closed 5 months ago.

I'm building a website which includes a login page. I need to redirect the user to their profile page once they've logged in successfully, but I don't know how to do that in PHP (It's my first site).

I've searched the internet and have been told that the header() function should do the trick, but it will only work if I haven't outputted any information before using it.

That's the problem. I've outputted a bunch of information (Including the HTML to build the login page itself).

So how do I redirect the user from one page to the next?

What options do I have? Also, what is the best practice in these instances?


EDIT: Here's my entire login.php page:

<?php 

session_start(); 

echo "<!DOCTYPE html> 
  <html> 
     <head> 
        <meta charset='utf-8'> 
        <title>Sprout</title>
    <link rel='stylesheet' href='stylesheet.css' type='text/css'>
     </head>
 <body>
    <div class='box'>
    <form action='login.php' method='post'>
       Name<br /> <input type='text' name='username' class='form'/><br />
       Password<br /> <input type='password' name='password' class='form'/>
       <input type='submit' value='Login' class='button' />
    </form>
    </div>
 </body>
  </html>";

if ($_SERVER['REQUEST_METHOD'] == 'POST') 
{
    $username = $_POST["username"];
    $password = $_POST["password"];

    $dbhost = "localhost";
    $dbuser = "root";
    $dbpass = "root";

    $conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ("Error connecting to database");

    $dbname = "database";

    mysql_select_db($dbname);

    $query = "SELECT username FROM users WHERE username = '$username' AND password = '$password'";

    $result = mysql_query($query) or die ("Failed Query of " . $query);


    while($row = mysql_fetch_assoc($result))
    {
            $_SESSION["user"] = $username;
    }
}
?>


You could use a function similar to:

function redirect($url) {
    header('Location: '.$url);
    die();
}

Worth noting, you should them with a die() or exit() function to prevent further code execution.

Note that it just makes no sense to output large chunks of HTML if you are going to redirect. Therefore you have to move the form handling code above all HTML. As a side effect it will mitigate the notorious "Headers already sent" error.

Here's a more detailed guide than any of the other answers have mentioned: http://www.exchangecore.com/blog/how-redirect-using-php/

This guide includes reasons for using die() / exit() functions in your redirects, as well as when to use ob_flush() vs ob_start(), and some potential errors that the others answers have left out at this point.


You can conditionally redirect to some page within a php file....

if (ConditionToRedirect){
  //You need to redirect
  header("Location: http://www.yourwebsite.com/user.php");
  exit();
 }
else{
  // do something
}


That's the problem. I've outputted a bunch of information (including the HTML to build the login page itself). So how do I redirect the user from one page to the next?

This means your application design is pretty broken. You shouldn't be doing output while your business logic is running. Go an use a template engine (like Smarty) or quickfix it by using output buffering).

Another option (not a good one though!) would be outputting JavaScript to redirect:

<script type="text/javascript">location.href = 'newurl';</script>


header won't work for all

Use below simple code

<?php
        echo "<script> location.href='new_url'; </script>";
        exit;
?>


Assuming you're using cookies for login, just call it after your setcookie call -- after all, you must be calling that one before any output too.

Anyway in general you could check for the presence of your form's submit button name at the beginning of the script, do your logic, and then output stuff:

if(isset($_POST['mySubmit'])) {
    // the form was submitted

    // ...
    // perform your logic

    // redirect if login was successful
    header('Location: /somewhere');
}

// output your stuff here


You could use ob_start(); before you send any output. This will tell to PHP to keep all the output in a buffer until the script execution ends, so you still can change the header.

Usually I don't use output buffering, for simple projects I keep all the logic on the first part of my script, then I output all HTML.


The simplest approach is that your script validates the form-posted login data "on top" of the script before any output.

If the login is valid you'll redirect using the "header" function.

Even if you use "ob_start()" it sometimes happens that you miss a single whitespace which results in output. But you will see a statement in your error logs then.

<?php
ob_start();
if (FORMPOST) {
    if (POSTED_DATA_VALID) {
        header("Location: https://www.yoursite.com/profile/");
        ob_end_flush();
        exit;
    }
}
/** YOUR LOGINBOX OUTPUT, ERROR MESSAGES ... **/
ob_end_flush();
?>


firstly create index.php page and just copy paste below code :-

<form name="frmUser" class="well login-form" id="form" method="post" action="login_check.php" onSubmit="return FormValidation()">
    <legend>
        <icon class="icon-circles"></icon>Restricted Area<icon class="icon-circles-reverse"></icon>
    </legend>
    <div class="control-group">
        <label class="control-label" for="inputPassword">Username</label>
        <div class="controls">
            <div class="input-prepend">
                <span class="add-on"><icon class="icon-user icon-cream"></icon> </span>
                <input class="input" type="text" name="username" id="username" placeholder="Username" />
            </div>
        </div>
    </div>
    <div class="control-group">
        <label class="control-label" for="inputPassword">Password</label>
        <div class="controls">
            <div class="input-prepend">
                <span class="add-on"><icon class="icon-password icon-cream"></icon>
                </span> <input class="input" type="password" name="password" id="password" value="" placeholder="Password" />
            </div>
        </div>
    </div>
    <div class="control-group signin">
        <div class="controls ">
            <input type="submit" class="btn btn-block" value="Submit" />
            <div class="clearfix">
                <span class="icon-forgot"></span><a href="#">forgot password</a>
            </div>
        </div>
    </div>
</form>



/*------------------after that ----------------------*/

create a login_check.php and just copy paste this below code :-

<?php
session_start();
include('conn.php');

<?php
/* Redirect browser */
header("location:index.php");

/* Make sure that code below does not get executed when we redirect. */
exit;
?>


<?php

if(count($_POST)>0)
{   

    $result = mysql_query("SELECT * FROM admin WHERE username='".$_POST["username"]."' and password = '".$_POST["password"]."'");
    $row  = mysql_fetch_array($result);

if(is_array($row)) 
{
    $_SESSION["user_id"] = $row[user_id];
    $_SESSION["username"] = $row[username];

    $session_register["user_id"] = $row[user_id];
    $session_register["username"] = $row[username];
} 
else 
{
   $_SESSION['msg']="Invalid Username or Password";
   header("location:index.php");
}
}

if(isset($_SESSION["user_id"]))
{
    header("Location:dashboard.php");
}

?>




/*-----------------------after that ----------------------*/


create a dashboard.php and copy paste this code in starting of dashboard.php



<?php
session_start();
include('conn.php');
include('check_session.php');
?>




/*-----------------------after that-----------------*/ 



create a check_session.php which check your session and copy paste this code :- 


<?php
    if($_SESSION["user_name"]) 
    {
?>
    Welcome <?php echo $_SESSION["user_name"]; ?>. Click here to <a href="logout.php" tite="Logout">Logout.</a>
<?php
    }
    else
    {
     header("location:index.php");
    }
?>





if you have any query so let me know on my mail id farjicompany@gmail.com


Although not secure, (no offense or anything), just stick the header function after you set the session variable

 while($row = mysql_fetch_assoc($result))
    {
            $_SESSION["user"] = $username;
    }
header('Location: /profile.php');


On click BUTTON action

   if(isset($_POST['save_btn']))
    {
        //write some of your code here, if necessary
        echo'<script> window.location="B.php"; </script> ';
     }


----------


<?php
echo '<div style="text-align:center;padding-top:200px;">Go New Page</div>'; 
		$gourl='http://stackoverflow.com';
		echo '<META HTTP-EQUIV="Refresh" Content="2; URL='.$gourl.'">';    
		exit;

?>


----------


Just like you used echo to print a webpage. You could use also do the same with redirecting.

print("<script type=\"text/javascript\">location.href=\"urlHere\"</script>")


<?php 
include("config.php");
 
 
$id=$_GET['id'];

include("config.php");
if($insert = mysqli_query($con,"update  consumer_closeconnection set close_status='Pending' where id="$id"  "))
            {
?>
<script>
    window.location.href='ConsumerCloseConnection.php';

</script>
<?php
            }
            else
            {
?>
<script>
     window.location.href='ConsumerCloseConnection.php';
</script>
<?php            
    }
?>      
0

精彩评论

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