Answer the question
In order to leave comments, you need to log in
How to properly structure a document to avoid "Cannot modify header information - headers already sent by"?
Hello everyone,
I'm sorry for so many childish questions, but I'm just starting to learn programming and I ran into authorization, namely header(). I know that headers should precede all outputs, but would it be better to structure the structure to avoid them then?
I will give the sources below:
index.php
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Blog</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div class="container">
<div class="top"><?php (isset($_POST['session_id'])) ? include_once "logout.php" : include_once "lgn.php"; ?></div>
<div class="center">
<div class="left">left</div>
<div class="content"><?php include_once "blog.php"; ?></div>
</div>
</div>
</body>
</html>
<?php
$login = htmlentities(trim($_POST['login']));
$password = md5(trim($_POST['password']));
if (isset($_POST['submit'])) {
include_once "db_connect.php";
include_once "config.php";
if (isset($login,$password)) {
$query = "SELECT * FROM users WHERE login="."'".$login."'";
$result = mysqli_query($con,$query);
$user = array();
while ($row = mysqli_fetch_array($result)) {
foreach ($row as $key => $value) {
if (!is_numeric($key)) {
$user[$key] = $value;
}
}
}
if (($login === $user['login']) && ($password === $user['password'])) {
setcookie('session_id', $user['id']);
setcookie('login', $user['login']);
}else{
echo "Such user doen't exist or login/password dosn't match. Please, check them twice and try again!";
}
}
}
?>
<div class="login">
<form action="" method="POST">
<table>
<tr>
<td><input type="text" name="login" placeholder="Login" value="<?php echo $_POST['login'] ?>"></td>
<td><input type="password" name="password" placeholder="Password"></td>
<td><input type="submit" name="submit"></td>
</tr>
</table>
</form>
</div>
<table>
<tr>
<td><?php echo "Welcome back, ".$_COOKIE['login']; ?></td>
<td><a href="<?php setcookie('session_id', ""); ?>">Log out</a></td>
</tr>
</table>
Answer the question
In order to leave comments, you need to log in
index.php you actually have an html template. organize it like this:
<?php
if (проверка данных выводить шаблон или заглолвки отправлять) {
что-то можно сделать тут еще. но только не echo,print или вывод какой либо
тут можете посылать ваши хидеры (session, cookie И так далее)
else {
тут выводите ваш html типа echo '<html>........</html>';
}
?>
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question