Moja propozycja jest następująca:
ten "kawałek" kodu, przenieś do osobnego pliku, o nazwie np.: connection.php
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
reszta kodu, np.: index.php [ How can you check if a PHP session exists? ]
<?php
session_start();
$html = "";
if (isset($_COOKIE["PHPSESSID"])) {
include_once('connection.php');
$sql = "SELECT id AS 'id_user', username, email FROM users WHERE username = '".$_SESSION['username']."'";
$result = $conn->query($sql);
if ($result->num_rows == 0) {
$html .= "Podana nazwa użytkownika jest nieprawidłowa lub"
." użytkownik o pdanej nazwie nie jest zapisany";
} else {
$row = $result->fetch_assoc();
$_SESSION['id_user'] = $row['id_user'];
$_SESSION['username'] = $row['username'];
$_SESSION['email'] = $row['email'];
// Można też jak poniżej
//foreach ($row as $name => $value) {
// $_SESSION[$name] = $value;
//}
unset($row);
}
$result->free_result();
$conn->close();
}
$html .= "id: ".$_SESSION['id_user']." - Name: ".$_SESSION['username']." ".$_SESSION['email']."<br>";
?>
<!DOCTYPE html>
<html lang="pl">
<head>
<meta charset="utf-8">
</head>
<body>
<pre>
<?php echo $html; ?>
</pre>
</body>
</html>
do usuwania sesji, np.: logout.php [ link ]
<?php
... jakiś kod php
session_unset();
session_destroy();
session_write_close();
setcookie(session_name(),'',0,'/');
?>
<!DOCTYPE html>
<html lang="pl">
<head>
<meta charset="utf-8">
</head>
<body>
<pre>
Zostałe(a)ś wylogowan(a)y.
</pre>
</body>
</html>