Используйте перенаправление header()
в условном успешном обновлении if / else stmt.
if($query->rowCount() > 0)
{
foreach ($results as $result) {
$status = $result->Status;
$_SESSION['eid'] = $result->id;
$_SESSION['name'] = $result->FirstName . " " . $result->LastName;
$_SESSION['emplogin'] = $result->emp_username;
}
if($status == 0)
{
$target_page = 'myprofile.php'; // I assume this is the page you are redirecting to
// on success, change this to your desired link if not.
//Build your entire http path URL.
$url = 'http://' . $_SERVER['HTTP_HOST']; // Get the server
$url .= rtrim(dirname($_SERVER['PHP_SELF']), '/\\'); // Get the current directory
$url .= $target_page.'?success'; // <-- Your relative path with a success post through url
header('Location: ' . $url, true, 302);
exit;
} else {
echo "<script type='text/javascript'> document.location = 'myprofile.php'; </script>";
}
} else {
//else $query->rowCount() !> 0 ***no results...***
$target_page = 'myprofile.php';
$url = 'http://' . $_SERVER['HTTP_HOST']; // Get the server
$url .= rtrim(dirname($_SERVER['PHP_SELF']), '/\\'); // Get the current directory
$url .= $target_page.'?log_error'; // <-- Your relative path with an error post through url, handle $_GET['log_error'] on another page or this page and redirect.
header('Location: ' . $url, true, 302);
exit;
}
Не забудьте добавить if(isset($_GET['success'])){ $success = "Your success message here" }
на целевой странице и if(isset($_GET['log_error'])){ $log_error = "Your login error message here" }
. Затем опубликуйте эту переменную, где вы будете sh, чтобы опубликовать ваши сообщения об успехе / ошибке.
Вы можете использовать тот же редирект и добавлять разные пары ключ / значение POST в URL и просеивать результат POST. , Таким образом, вместо ?success
вы можете поместить что-то вроде ?error=login
, а затем обработать эту ошибку с помощью условия, которое проверяет, установлено ли значение $ _GET ['error'] и = = 'login' if(isset($_GET['login') && $_GET['login' ) === "error"){ //handle error code here and display issue }
.
СЕССИИ Создайте сеанс и сохраните в нем соответствующую информацию, такую как 'userLoggedIn', которая будет указана на страницах успешного входа пользователя в систему.
session_start();// Start the session
// $_SESSION['sessData'] is an array that carries pertinent SESSION info that can be
// logged through $_SESSIONS within your user login pages
$sessData = !empty($_SESSION['sessData'])?$_SESSION['sessData']:'';
// check to see if the user is logged in, if so send them to the restricted
// home page for logged in users
if( isset($_SESSION['userLoggedIn'])!="" ){
header("Location: home.php"); // home.php is the users logged in page.
}
//handle code if session is not set
РЕДАКТИРОВАТЬ 19 МАРТА 2020 ГОДА:
Если у вас есть БД, в которой сохраняются пользовательские данные, создайте таблицу для страницы, на которой они находятся, когда они выходят из системы, назовите ее logout_page
или как-то
В вашем html убедитесь, что каждая страница имеет уникальный идентификатор, установленный в теге body, чтобы вы могли вызывать его при установке переменной посещенных страниц, которая будет отправлена в БД при выходе из системы. Установите это значение в php и позвоните в html.
// Declare a variable in your php on each restricted login page the user can access and set it to the following.
// You can use `basename()` and `$_SERVER['PHP_SELF']` to get current page file name.
$pageName = basename($_SERVER['PHP_SELF']);
// conditional to see if user is logging out
if(isset($_GET['logout'])){// $_GET value coming from your logout button that directs to this code
//query DB and ad $pageName to your DB entry
//handle logout
}
Когда пользователь входит в систему, измените сценарий входа и включите last_page
в свой запрос результатов.
// not sure how you connect but it would look similar to this
$sql = "SELECT id, first_name, last_name, email, last_page FROM user_table";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
//assign values to variables
$id = $row['id'];
$target_page = $row['logout_page'];
// Set sessions here
$_SESSION['last_page'] = $target_page;
$_SESSION['msg'] = "Something you wish to say about logging back and setting to users last page visited";
// handle unset
// Build your entire http path URL.
$optional = '?key=value';// use `?id=` maybe '?id=."$id;
$url = 'http://' . $_SERVER['HTTP_HOST']; // Get the server
$url .= rtrim(dirname($_SERVER['PHP_SELF']), '/\\'); // Get the current directory
$url .= $target_page.$optional; // <-- Your relative path with a success post through url
header('Location: ' . $url, true, 302);
exit;
}
}