I set session variable for login of user but it doesn't work on another pages than login.php.
login.php:
<?php
session_start();
if(isset($_POST['submit'])) {
$conn = mysqli_connect('localhost', 'cp72722_lucky', '3AIp!9f4', 'cp72722_lucky');
$user_username = mysqli_real_escape_string($conn, trim($_POST['username']));
$user_password = mysqli_real_escape_string($conn, trim($_POST['password']));
if(!empty($user_username) && !empty($user_password)) {
$query = "SELECT user_id , username FROM users WHERE username = '$user_username' AND pwd = SHA('$user_password')";
$data = mysqli_query($conn,$query);
if(mysqli_num_rows($data) == 1) {
$row = mysqli_fetch_assoc($data);
$user_value = $row['username'];
$user_id_value = $row['user_id'];
$_SESSION['username'] = $user_value;
$_SESSION['user_id'] = $user_id_value;
echo "Hello," . $_SESSION['username'];
$home_url = 'http://' . $_SERVER['SERVER_NAME'];
header('Location: ' . $home_url);
print_r($home_url);
exit();
}
else {
echo 'Извините, вы должны ввести правильные имя пользователя и пароль';
}
}
else {
echo 'Извините, вы должны заполнить поля правильно';
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link href="style/style.css" rel="stylesheet">
</head>
<body>
<header>
<ul>
<li><a href="/">Главная</a></li>
</ul>
</header>
<h2>Вход</h2>
<div class="container">
<form action="http://<?php echo $_SERVER['SERVER_NAME']; ?>" method="POST">
<label for="username">Логин:</label>
<input type="text" name="username">
<label for="password">Пароль:</label>
<input type="password" name="password">
<button type="submit" name="submit">Вход</button>
<a href="auth/signup.php">Регистрация</a>
</form>
</div>
<footer>
<p>Все права защищены</p>
</footer>
</body>
</html>
My header.php shows almost on all pages and I want to welcome the users after login. If the session is not set, then should display the form to login. Problem is, if the user is logged in and the profile links, it always displays second choice because session is not set. How do I resolve this issue?
header.php:
<?php
session_start();
print_r($_SESSION);
?>
...
<header id="header">
<?php
echo 'Glad to see you,'. htmlspecialchars($_SESSION['username']);
?>
...
<div>
<?php
if(!isset($_SESSION['username'])) {
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<label for="username">Login:</label>
<input type="text" name="username">
<label for="password">Password:</label>
<input type="password" name="password">
<button type="submit" name="submit">Enter</button>
<a href="auth/signup.php">Registration</a>
</form>
<?php
}
else {
?>
<p><a href="myprofile.php">Profile</a></p>
<p><a href="exit.php">Exit(<?php echo $_SESSION['username']; ?>)</a></p>
<?php
}
?>
</div>