PHP sessions

Home » Tutorials » PHP » PHP sessions
Today we will discuss sessions in php. It helps browser to identify user in different pages.
We will apply session in our web application. First of all we call session_start function, which starts session. It is very important, that this function must be called before any output in browser. We’ll create authorization form and new table in our database to store data about users.

Next we’ll write function, which will check user with input data from html form. If it is check, we’ll record login into global array $_SESSION, announcing the key, which we can identify login.

$_SESSION
<?php
$_SESSION['user'] = $login;
?>
That’s all. We only need to call session_start() function in other pages.

What’s happening, when you logout from account in any web site? Session destroys. We created logout.php file, where after starting session we call session_destroy() function, which delete session.

Code lesson (index.php)
<?php

	session_start();
	include 'db.php';
	include 'api.php';

	if(!empty($_POST)) {

		if($_POST['login'] != '' && $_POST['password'] != '') {
			$login = trim(strip_tags($_POST['login']));
			$password = trim(strip_tags($_POST['password']));
			if(isUser($db, $login, $password)) {
				$_SESSION['user'] = $login;
			} else {
				echo "<h1>Пользатель не найден</h1>";	
			}
		} else {
			echo "<h1>Заполните все поля</h1>";
		}

	}

?>

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Главная</title>
	<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
	<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
	<header>
		<nav class="navbar navbar-default" role="navigation">
			<div class="container-fluid">
				<div class="navbar-header">
					<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
						<span class="sr-only">Toggle navigation</span>
						<span class="icon-bar"></span>
						<span class="icon-bar"></span>
						<span class="icon-bar"></span>
					</button>
					<a class="navbar-brand" href="#">Sport CRM</a>
				</div>
		
				<div class="collapse navbar-collapse navbar-ex1-collapse">
					<ul class="nav navbar-nav">
						<li><a href="index.php">Главная</a></li>
						<li><a href="players.php">Игроки</a></li>
						<li><a href="teams.php">Команды</a></li>
						<li><a href="countries.php">Страны</a></li>
					</ul>
					<div class="pull-right">
						<?php if(isset($_SESSION['user'])) { ?>
							<p>Пользователь: <?php echo $_SESSION['user'];  ?></p>
							<p><a href="logout.php">Выйти</a></p>
						<?php } ?>
					</div>
				</div>
			</div>
		</nav>
	</header>

	<div id="content">
		<div class="container-fluid">
		<?php if(!isset($_SESSION['user'])) { ?>
			<form action="" method="POST" role="form">
			
				<div class="form-group">
					<label for="">Логин</label>
					<input type="text" class="form-control" id="login" name="login">
				</div>

				<div class="form-group">
					<label for="">Пароль</label>
					<input type="password" class="form-control" id="password" name="password">
				</div>
			
				<button type="submit" class="btn btn-primary">Войти</button>
			</form>
		<?php } ?>	
		</div>
	</div>

	<footer>
		
	</footer>
</body>
</html>
Code lesson (players.php)
<?php
	session_start();
?>
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Игроки</title>
	<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
	<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
	<header>
		<nav class="navbar navbar-default" role="navigation">
			<div class="container-fluid">
				<div class="navbar-header">
					<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
						<span class="sr-only">Toggle navigation</span>
						<span class="icon-bar"></span>
						<span class="icon-bar"></span>
						<span class="icon-bar"></span>
					</button>
					<a class="navbar-brand" href="#">Sport CRM</a>
				</div>
		
				<div class="collapse navbar-collapse navbar-ex1-collapse">
					<ul class="nav navbar-nav">
						<li><a href="index.php">Главная</a></li>
						<li><a href="players.php">Игроки</a></li>
						<li><a href="teams.php">Команды</a></li>
						<li><a href="countries.php">Страны</a></li>
					</ul>
					<div class="pull-right">
						<?php if(isset($_SESSION['user'])) { ?>
							<p>Пользователь: <?php echo $_SESSION['user'];  ?></p>
							<p><a href="logout.php">Выйти</a></p>
						<?php } ?>
					</div>
				</div>
			</div>
		</nav>
	</header>

	<div id="content">
		<div class="container-fluid">
			<?php include 'db.php'; ?>
			<?php include 'api.php'; ?>
			<?php
				$players = getAllPlayers($db);
			?>
			<table class="table table-bordered">
				<tr>
					<th>Игрок</th>
					<th>Команда</th>
					<th>Страна</th>
					<th>Удалить</th>
				</tr>
				<?php foreach ($players as $player) { ?>
					<tr>
						<td><a href="edit.php?player_id=<?php echo $player['player_id'];?>"><?php echo $player['player_name']; ?></a></td>
						<td><?php echo $player['team_name']; ?></td>
						<td><?php echo $player['country_name']; ?></td>
						<td><a class="btn btn-danger" href="delete.php?player_id=<?php echo $player['player_id'];?>">Удалить</a></td>
					</tr>
				<?php } ?>
			</table>

			<?php if(isset($_SESSION['user'])) { ?>
				<button id="addButton" class="btn btn-default">Добавить игрока</button>
			<?php } ?>
			
			<form action="" method="POST" role="form" style="display: none; margin-top: 20px;">
		
			<div class="form-group">
				<label for="">Введите имя</label>
				<input type="text" class="form-control" id="name" name="name" placeholder="Введите имя">
			</div>

			<div class="form-group">
				<select name="country" class="form-control" id="country">
				<?php
					$countries = getAllCountries($db);
					foreach ($countries as $key => $value) {
						echo "<option value=".$value['country_id'].">".$value['country_name']."</option>";	
					}	
				?>
				</select>
			</div>
			
			
			<button type="submit" class="btn btn-default">Добавить</button>
			
		</form>
		</div>

		<?php
			if(isset($_POST['name']) && $_POST['name'] != '') {
				$name = $_POST['name'];
				$countryId = $_POST['country'];	
				addPlayer($db, $name, $countryId);
			}
			
		?>

	</div>

	<footer>
		
	</footer>

	<script>
		$("#addButton").click(function(){
			$("form").slideDown();
		});
	</script>
</body>
</html>
Code lesson (logout.php)
<?php

	session_start();
	session_destroy();

?>
Code lesson
CREATE table users(
	user_id int(10) unsigned primary_key auto_increment not null,
	user_login varchar(20) not null,
	user_password varhar(20) not null
);

INSERT INTO users (user_login, user_passord) VALUES ('admin', '12345');

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

Подписаться на рассылку

Будьте в курсе - получайте последние статьи на свой email

Ваша подписка успешно оформлена

Pin It on Pinterest

Share This