Okay, I haved been maked a register system, but when I tried to make the login system it didn't work. When the user log in with the correct username and password its post "You are now logged in", but when I refresh the site, It says I need to login. And I has to ask how I could check the user is logged in exempel If the user logged in so echo this and if not so echo this..
Here is my code:
session_start();
require 'inc/connect.php';
if(isset($_POST['name'], $_POST['password'])){
if(!empty($_POST['name'])){
if(!empty($_POST['password'])){
$username = $_POST['name'];
$password = $_POST['password'];
$user = $_SESSION['name'];
// KRYPTERING
$md5 = md5($password);
$sha1 = sha1($md5);
$crypt = crypt($sha1, 'st');
$md51 = md5($crypt);
$sha12 = sha1($md51);
$crypt1 = crypt($sha12, 'st');
$kode = base64_encode($crypt1);
$check = $mysqli->prepare("SELECT username, password FROM user WHERE username=? && password=?");
$check->bind_param("ss", $username, $kode);
$check->execute();
$check->bind_result($username, $kode);
$print = $check->fetch();
$check->close();
if ($print)
echo "You are now logged in!";
else
echo "Username / Password was incorrect!";
} else
echo "You need something!";
} else
echo "You need something!";
}
You need to put the username in the session on successful login, to check for it at the top of the page, and redirect to a different when its already set.
session_start();
require 'inc/connect.php';
if(isset($_SESSION['username']))
{
//already logged in, redirect
header('Location: otherpage.php');
exit;
}
if(isset($_POST['name'], $_POST['password'])){
if(!empty($_POST['name'])){
if(!empty($_POST['password'])){
$username = $_POST['name'];
$password = $_POST['password'];
$user = $_SESSION['name'];
// KRYPTERING
$md5 = md5($password);
$sha1 = sha1($md5);
$crypt = crypt($sha1, 'st');
$md51 = md5($crypt);
$sha12 = sha1($md51);
$crypt1 = crypt($sha12, 'st');
$kode = base64_encode($crypt1);
$check = $mysqli->prepare("SELECT username, password FROM user WHERE username=? && password=?");
$check->bind_param("ss", $username, $kode);
$check->execute();
$check->bind_result($username, $kode);
$print = $check->fetch();
$check->close();
if ($print)
{
//redirect to different page for the message
//echo "You are now logged in!";
$_SESSION['username'] = $username;
header('Location: otherpage.php');
exit;
}
else
echo "Username / Password was incorrect!";
} else
echo "You need something!";
} else
echo "You need something!";
}
Then in the other pages, you'll want something like:
session_start();
if(!isset($_SESSION['username']))
{
//not logged in, redirect to login form
header('Location: login_form.php');
exit;
}