How to redirect after login in PHP?

by tressie.damore , in category: PHP General , 9 months ago

How to redirect after login in PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by adan , 3 months ago

@tressie.damore 

To redirect the user to a different page after a successful login, you can use the header function in PHP.


Here is an example of how you can use it:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
<?php
// check if the login was successful
if ($loginSuccessful) {
    // redirect to the dashboard page
    header('Location: dashboard.php');
    exit;
} else {
    // login was not successful, display an error message
    echo '<p>Login failed. Please try again.</p>';
}


This will redirect the user to the dashboard.php page after a successful login.


Keep in mind that the header function must be called before any output is sent to the browser. If you have already sent output to the browser (e.g. by echoing a string or printing a variable), you will not be able to use the header function.