4

How would you redirect from a PHP page to another?

</head>

<body>
    <!-- Home -->
    <div data-role="page" id="page1">
        <div data-theme="a" data-role="header">
            <a data-role="button" data-theme="d" href="login.html" data-icon="arrow-l" data-iconpos="left" class="ui-btn-left">
                        Back
                    </a>
            <a data-role="button" href="index.html" data-icon="home" data-iconpos="right" data-theme="d" class="ui-btn-right">
                     Home  
                    </a>
            <h3>
                Login Process
            </h3>
        </div>
        <div data-role="content">

            <?php
    // takes the variables from action script and assigns them php variables names
    $user = $_POST ['username'];
    $pass = $_POST ['password'];

    // if there is a user name and password
    if ($user && $pass)
    {
        // connect to server
        mysql_connect("localhost", "", "") or die(mysql_error());
        //select database
        mysql_select_db("") or die(mysql_error());

        //Create a query that selects all data from the PATIENT table where the username and password match
        $query = "SELECT * FROM Patient WHERE Username = '$user' AND Password = '$pass'";

        //executes query on the database
        $result = mysql_query ($query) or die ("didn't query");
        //this selects the results as rows

        $num = mysql_num_rows ($result);
        //if there is only 1 result returned than the data is ok 
        if ($num == 1)
        {
            //sends back a data of "Success"
            echo "Successful Login";
            $row=mysql_fetch_array($result);
            $_SESSION['Name'] = $row['Name'];
            $_SESSION['Address'] = $row['Address'];
        }
        else
        {
            //sends back a message of "failed"
            echo "Unsuccessful Login";
        }
    }

    ?>
        </div>
    </div>
</body>

</html>

So when the user logs in, it takes them to the page shown above. What I need it to do is, if login is successful, I need it to go to redirect to another PHP page.


login.php

<?php
    // takes the variables from action script and assigns them php variables names
    $user = $_POST ['username'];
    $pass = $_POST ['password'];
    $error = '';

    // if there is a user name and password
    if ($user && $pass)
    {
        // connect to server
        mysql_connect("localhost", "", "") or die(mysql_error());
        //select database
        mysql_select_db("") or die(mysql_error());

        //Create a query that selects all data from the PATIENT table where the username and password match
        $query = "SELECT * FROM Patient WHERE Username = '$user' AND Password = '$pass'";

        //executes query on the database
        $result = mysql_query ($query) or die ("didn't query");
        //this selects the results as rows

        $num = mysql_num_rows ($result);
        //if there is only 1 result returned than the data is ok 
       if ($num == 1)
    {
    header("Location: http://helios.hud.ac.uk/u101010/PHP/details1.php");
    }
            //sends back a data of "Success"
            $return_message =  "Successful Login";
            $row=mysql_fetch_array($result);
            $_SESSION['Name'] = $row['Name'];
            $_SESSION['Address'] = $row['Address'];
        }
        else
        {
            //sends back a message of "failed"
            $return_message = echo "Unsuccessful Login";
        }
    }
    <html>
        <head>
            <meta charset="utf-8" />
            <meta name="viewport" content="width=device-width, initial-scale=1" />
            <meta name="apple-mobile-web-app-capable" content="yes" />
            <meta name="apple-mobile-web-app-status-bar-style" content="black" />
            <title>
            </title>
            <link rel="stylesheet" href="https://ajax.aspnetcdn.com/ajax/jquery.mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
            <link rel="stylesheet" href="my.css" />
            <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
            </script>
            <script src="https://ajax.aspnetcdn.com/ajax/jquery.mobile/1.2.0/jquery.mobile-1.2.0.min.js">
            </script>
            <script src="my.js">
            </script>
            <!-- User-generated css -->
            <style>
            </style>
            <!-- User-generated js -->
            <script>
                try {

        $(function() {

        });

      } catch (error) {
        console.error("Your javascript has an error: " + error);
      }
            </script>

    ?>
    </head>

    <body>
        <!-- Home -->
        <div data-role="page" id="page1">
            <div data-theme="a" data-role="header">
                <a data-role="button" data-theme="d" href="login.html" data-icon="arrow-l" data-iconpos="left" class="ui-btn-left">
                        Back
                    </a>
                <a data-role="button" href="index.html" data-icon="home" data-iconpos="right" data-theme="d" class="ui-btn-right">
                     Home  
                    </a>
                <h3>
                    Login Process
                </h3>
            </div>
            <div data-role="content">

                <?php echo $return_message; ?>

            </div>
        </div>
    </body>

    </html>

Details1.php

<!DOCTYPE html>
<?php
    session_start();
    ?>
    <html>

    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <meta name="apple-mobile-web-app-capable" content="yes" />
        <meta name="apple-mobile-web-app-status-bar-style" content="black" />
        <title>
        </title>
        <link rel="stylesheet" href="https://ajax.aspnetcdn.com/ajax/jquery.mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
        <link rel="stylesheet" href="my.css" />
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
        </script>
        <script src="https://ajax.aspnetcdn.com/ajax/jquery.mobile/1.2.0/jquery.mobile-1.2.0.min.js">
        </script>
        <script src="my.js">
        </script>
        <!-- User-generated css -->
        <style>
        </style>
        <!-- User-generated js -->
        <script>
            try {

                $(function() {

                });

            } catch (error) {
                console.error("Your javascript has an error: " + error);
            }
        </script>
    </head>

    <body>
        <!-- Home -->
        <div data-role="page" id="page1">
            <div data-theme="a" data-role="header">
                <a data-role="button" data-theme="c" href="menu.html" data-icon="arrow-l" data-iconpos="left" class="ui-btn-left">
                        Main Menu
                        </a>
                <h3>
                    Your details
                </h3>


            </div>
            <div data-role="content">
                Name:
                <?php echo $_SESSION['Name'];?>
                <br /> Address:
                <?php echo $_SESSION['Address'];?>



            </div>
    </body>

    </html>

details.html

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="apple-mobile-web-app-capable" content="yes" />
    <meta name="apple-mobile-web-app-status-bar-style" content="black" />
    <title>
    </title>
    <link rel="stylesheet" href="https://ajax.aspnetcdn.com/ajax/jquery.mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
    <link rel="stylesheet" href="my.css" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
    </script>
    <script src="https://ajax.aspnetcdn.com/ajax/jquery.mobile/1.2.0/jquery.mobile-1.2.0.min.js">
    </script>
    <script src="my.js">
    </script>
    <!-- User-generated css -->
    <style>
    </style>
    <!-- User-generated js -->
    <script>
        try {

            $(function() {

            });

        } catch (error) {
            console.error("Your javascript has an error: " + error);
        }
    </script>
</head>

<body>
    <!-- Home -->
    <div data-role="page" id="page1">
        <div data-theme="a" data-role="header">
            <a data-role="button" data-theme="c" href="menu.html" data-icon="arrow-l" data-iconpos="left" class="ui-btn-left">
                        Main Menu
                        </a>
            <h3>
                Your details
            </h3>
        </div>
        <form name="form1" method="post" action="details1.php">
            <strong>Details</strong>
            <br />
            <br /> Name: <input type="text" name "Name" />
            <br /> Address: <input type="text" name="Address" />
            <br />
            <input type="submit" name="Submit" value="Book appointment" />
            <br />
            <input type="submit" name="Submit" value="Cancel appointment" />
        </form>

    </div>
</body>

</html>

login.html

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="apple-mobile-web-app-capable" content="yes" />
    <meta name="apple-mobile-web-app-status-bar-style" content="black" />
    <title>
    </title>
    <link rel="stylesheet" href="https://ajax.aspnetcdn.com/ajax/jquery.mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
    <link rel="stylesheet" href="my.css" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
    </script>
    <script src="https://ajax.aspnetcdn.com/ajax/jquery.mobile/1.2.0/jquery.mobile-1.2.0.min.js">
    </script>
    <script src="my.js">
    </script>
    <!-- User-generated css -->
    <style>
    </style>
    <!-- User-generated js -->
    <script>
        try {

            $(function() {

            });

        } catch (error) {
            console.error("Your javascript has an error: " + error);
        }
    </script>
</head>

<body>
    <!-- Home -->
    <div data-role="page" id="page1">
        <div data-theme="a" data-role="header">
            <a data-role="button" data-theme="d" href="login.html" data-icon="arrow-l" data-iconpos="left" class="ui-btn-left">
                        Back
                    </a>
            <a data-role="button" href="index.html" data-icon="home" data-iconpos="right" data-theme="d" class="ui-btn-right">
                     Home  
                    </a>
            <h3>
                Login
            </h3>
        </div>
        <div data-role="content">
            <h4>
                Enter login details below:
            </h4>

            <form name="form1" method="post" action="login.php">
                <strong>Patient Login </strong>
                <br />
                <br /> Username: <input name="username" type="text" id="username" />
                <br /> Password: <input name="password" type="password" id="password" />
                <br />
                <br />
                <br />
                <input type="submit" name="Submit" value="Login" />
            </form>
            <br />
            <div data-role="content">
                <h4>
                    Please ensure your username and password are kept secure.
                </h4>

                <br />
            </div>
        </div>
</body>

</html>
Narendra Jadhav
  • 10,052
  • 15
  • 33
  • 44
user2216325
  • 61
  • 2
  • 11

4 Answers4

3

Try using the header() function as so:

if ($num == 1)

{

header("Location: http://www.example.com");

}

Obviously change http://www.example.com to your location of choice and place it above any HTML in your page otherwise you will get a headers already set error.

With the above in mind you would need to re-arrange your code as follows:

    <?php

// takes the variables from action script and assigns them php variables names
$user = $_POST ['username'];
$pass = $_POST ['password'];
$error = '';

// if there is a user name and password
if ($user && $pass)
{
    // connect to server
    mysql_connect("localhost", "", "") or die(mysql_error());
    //select database
    mysql_select_db("") or die(mysql_error());

    //Create a query that selects all data from the PATIENT table where the username and password match
    $query = "SELECT * FROM Patient WHERE Username = '$user' AND Password = '$pass'";

    //executes query on the database
    $result = mysql_query ($query) or die ("didn't query");
    //this selects the results as rows

    $num = mysql_num_rows ($result);
    //if there is only 1 result returned than the data is ok 
    if ($num == 1)
    {
        //sends back a data of "Success"
header("Location: success.php");

    }
    else
    {
        //sends back a message of "failed"
        $error = "Unsuccessful Login";
    }
}

?>

<html>
<head>
</head>
    <body>
        <!-- Home -->
        <div data-role="page" id="page1">
            <div data-theme="a" data-role="header">
            <a data-role="button" data-theme="d" href="login.html" data-icon="arrow-l" data-iconpos="left" class="ui-btn-left">
                    Back
                </a>
                <a data-role="button" href="index.html" data-icon="home" data-iconpos="right" data-theme="d"class="ui-btn-right">
                 Home  
                </a>
                <h3>
                    Login Process
                </h3>
            </div>
            <div data-role="content">


<?php  echo $error; ?>

            </div>
        </div>
    </body>
</html>`

In addition I would urge you to look at PDO or mysqli and prepared statements with bound values before proceeding with this type of thing as you are opening yourself up to SQL injection attacks.

Peter Featherstone
  • 7,835
  • 4
  • 32
  • 64
  • Won't work in the OP's situation; the PHP code is buried inside HTML tags, to content is already sent to the browser – thaJeztah Mar 27 '13 at 22:41
  • Keep in mind that you can only use this before you write Amy html or echo'ed data to the page – Edo Post Mar 27 '13 at 22:42
  • True, just move all the code above the HTML, have edited the answer to reflect. – Peter Featherstone Mar 27 '13 at 22:43
  • This will work, but make sure you don't output ANY html before the PHP code executes - not even one bit of white space, otherwise you will get a 'headers already sent' error. – greg Mar 27 '13 at 22:43
  • @PeterFeatherstone from the kind of question, I assume the OP is not an experienced PHP programmer. I suggest to extend your question with a proper explanation and example on 'how to' do this, **while still being able to show the `unsuccesful login` message** – thaJeztah Mar 27 '13 at 22:45
  • updated including whole code' @thaJeztah – Peter Featherstone Mar 27 '13 at 22:50
  • 1
    Great! StackOverflow is not only about 'fast' answers, but to provide usable answers *for the person that asks the question* depending on the experience of that person, more explanation may be required in some cases :) – thaJeztah Mar 27 '13 at 22:56
  • You're absolutely correct @thaJeztah, I couldn't agree more! – Peter Featherstone Mar 27 '13 at 22:57
  • @PeterFeatherstone, yes i am still very inexperienced with PHP and very new to this. I just put your code in and it said "undefined". Where am i going wrong? – user2216325 Mar 27 '13 at 23:10
  • I made a little mistake I put $err=or instead of $error in my answer above which I have corrected now, could that be it? Where was it saying undefined exactly? – Peter Featherstone Mar 27 '13 at 23:11
  • I put in the username and password, clicked login and it displayed undefined. So the above is the login.html, it displayed error on login.php – user2216325 Mar 27 '13 at 23:15
  • do you have a page link that I can look at? I'd like to see your actual form code to see how that is all setup and where it goes next etc. – Peter Featherstone Mar 27 '13 at 23:22
  • Its all through a database so the link probably wouldn't work :s – user2216325 Mar 27 '13 at 23:30
  • But what about your form html? It might be useful to look at this. Are you using a html form with its action that points to the page with the code on your posted above? Are the inputs named correctly (username and password) etc. – Peter Featherstone Mar 27 '13 at 23:34
  • ok, i've added login.php with your changes and detail.php which is where i want the page directed to. Sorry if it looks bad. I'm new and confused about this – user2216325 Mar 27 '13 at 23:56
  • A couple of things... on the login.php page you need to close the php tag using `?>` before the `` tag, secondly I am finding it hard to find where your form is actually submitted from? I don't see any `` or `
    ` tags anywhere for example? Where are you getting the `$_POST['username']` and `$_POST['password']` values from?
    – Peter Featherstone Mar 27 '13 at 23:59
  • I have a detail.html page setup which has the form but because the user can only view the information and not edit it, I cannot see the use of that HTML page. – user2216325 Mar 28 '13 at 00:08
  • Could i show you somehow where its going wrong?? – user2216325 Mar 28 '13 at 00:09
  • ok can you just at the top of your login.php page type `echo $_POST['username'] . $_POST['password'];` and tell me if these show your correct entered values at the top of the page once submitted? – Peter Featherstone Mar 28 '13 at 00:10
  • If you could show me where this form that the user cant change so i can see it myself that would be helpful... – Peter Featherstone Mar 28 '13 at 00:10
  • no it says undefined. When the user logs in, it should display there name and address – user2216325 Mar 28 '13 at 00:13
  • ok its added as details.html – user2216325 Mar 28 '13 at 00:16
  • Im confused, you have details.html which then goes to details1.php but you want to do a redirect on login.php? How does the information ever get to login.php? In addition you have `` however it has no value and is not called username, there is also no password input field so where are you getting the information for `$_POST['username']` and `$_POST['password']` from? – Peter Featherstone Mar 28 '13 at 00:18
  • Sorry the page i sent you was details1.html. The username and passsword is stored on the database setup. So in Login.html the user would type in their name and password, if this matches with the info in the database they would login into the login.php page. When they login, it would display there Name and Address which is information stored in the database. I want, when it logs in to go from login.html to go to login.php displaying success login or failure. If successful it directs to the details page where it shows their name and address. Hope this makes more sense – user2216325 Mar 28 '13 at 00:26
  • Ok, can we take a look at the login.html code? At the least the part about the form they fill out. Where does the login.html form information get sent to? Also note that unless you've setup your server to allow it you can't process php code inside an html file, it would have to be renamed with the php extension. – Peter Featherstone Mar 28 '13 at 00:29
  • I am using a server. I have posted the login.html page. The information links with the login.php where it either allow the user to login or it fails. – user2216325 Mar 28 '13 at 00:36
  • The login was working until I used the code you gave. It allowed users to login if their username and password matched. – user2216325 Mar 28 '13 at 00:37
  • In your real example are you filling out all the `mysql_connect()` and `mysql_select_db()` info? As a test, remove everything from login.php (make sure you back it up first!) and just put `echo $_POST['username'];` and see if it displays your inputted username. Undefined means that nothing has been set to that array which looking at your form doesn't make sense. – Peter Featherstone Mar 28 '13 at 00:43
  • It still said undefined. But then i deleted all your code and brought it back to how it was and it said successful. – user2216325 Mar 28 '13 at 01:04
  • Also, the details in the details1.php does display. Its just getting it from login.php to the details page automatically if login is successful – user2216325 Mar 28 '13 at 01:09
3

All you have to do is change the header and exit the script:

header("Location: http://www.example.com");
die();
  • where does this header go on the php page?? – user2216325 Mar 27 '13 at 23:33
  • It can go everywhere you want. It stops the the rest of the page (using die() in this case) and redirects the user to the location specified inside the function. Be sure there is no HTML output before the function is called. You can put an `ob_start()` function at top of your page to work around any error messages saying "headers already sent" – Joshua - Pendo Mar 28 '13 at 00:18
2

Just use

header("Location: http://www.test.com");

Please note, that you can only set a header-redirect, if there is no output sent before. No single word, no html syntax and not even a simple whitespace.

More details: header function

So you have to put the PHP-part on the top of your script and store the success/error-messages in a variable instead of a direct "echo".

Example: Please note the variable "$return_message" in your if-clauses. There is no "echo" anymore, but in the HTML-context you will find the echo for the output.

<?php
// takes the variables from action script and assigns them php variables names
$user = $_POST ['username'];
$pass = $_POST ['password'];

// if there is a user name and password
if ($user && $pass)
{
    // connect to server
    mysql_connect("localhost", "", "") or die(mysql_error());
    //select database
    mysql_select_db("") or die(mysql_error());

    //Create a query that selects all data from the PATIENT table where the username and password match
    $query = "SELECT * FROM Patient WHERE Username = '$user' AND Password = '$pass'";

    //executes query on the database
    $result = mysql_query ($query) or die ("didn't query");
    //this selects the results as rows

    $num = mysql_num_rows ($result);
    //if there is only 1 result returned than the data is ok 
    if ($num == 1)
    {
        //sends back a data of "Success"
        $return_message =  "Successful Login";
        $row=mysql_fetch_array($result);
        $_SESSION['Name'] = $row['Name'];
        $_SESSION['Address'] = $row['Address'];
    }
    else
    {
        //sends back a message of "failed"
        $return_message = echo "Unsuccessful Login";
    }
}

?></head>
    <body>
        <!-- Home -->
        <div data-role="page" id="page1">
            <div data-theme="a" data-role="header">
            <a data-role="button" data-theme="d" href="login.html" data-icon="arrow-l" data-iconpos="left" class="ui-btn-left">
                    Back
                </a>
                <a data-role="button" href="index.html" data-icon="home" data-iconpos="right" data-theme="d"class="ui-btn-right">
                 Home  
                </a>
                <h3>
                    Login Process
                </h3>
            </div>
            <div data-role="content">

<?php echo $return_message; ?>

            </div>
        </div>
    </body>
</html>
Stefan Brendle
  • 1,545
  • 6
  • 20
  • 39
  • If you do NOT include an `exit;` after a redirect `header()` the rest of the code on the page will still be executed. – Tigger Mar 27 '13 at 23:19
  • i'm going wrong somewhere. Do i start the session right up the top after the php? It also says undefined. Does the header go at the top aswell. Sorry i'm new to php. – user2216325 Mar 27 '13 at 23:25
2

You coud use JavaScript

   <script type="text/javascript">window.location = 'PathToYourPage.extension'</script>
Edo Post
  • 727
  • 7
  • 18