I am new to php, and I am trying to create a website with a login-function. I have searched around, and I found a video where i got this code (see below). I want to create a website where you are logged in at all time, at the moment when i change webpage, i can't call "echo "Logged in as $user
";".
Why and how can I do this? Is there any other better way to do this?
I am going to make a website where you can create an user with username, password, first name, last name, address and so on. If I for example create an user in the database with the name user123, with the info first name = User, last name = Userson, address = Userstreet 2. Later, when you are logged in, you can book a hotel.
<?php
if(isset($_GET['logout']))
{
$expire = time() - 60*60*24*10; //ti dager
setcookie("idkunde","", $expire);
}
if(isset($_POST['user'])){
$user = $_POST['user'];
$pass = $_POST['pass'];
//connect to server
$con = mysql_connect("localhost", "root", "");
if(!$con){die('Could not connect: '. mysql_error());}
mysql_select_db("hotellformidling", $con);
if(mysql_num_rows(mysql_query("SELECT * FROM kunde WHERE brukernavn = '$user' AND passord = '$pass'")))
{ //riktig info
$result = mysql_query("SELECT * FROM kunde WHERE brukernavn ='$user' AND passord = '$pass'");
while($row = mysql_fetch_array($result))
{
$expire = time() + 60*60*24*10; //ti dager
setcookie("idkunde", $row['idkunde'], $expire);
echo "Logged in as <b>$user<b> <br>";
//$userID = $row['idkunde'];
}
}
else//feil info
{
echo "<b>Feil brukernavn eller passord</b><br><br>";
}
mysql_close($con);
}
if(isset($_COOKIE['idkunde'])){
$userID = $_COOKIE['idkunde'];
}
if(isset($userID))
{
echo "Logged in as <b>$user<b> <br>";
echo "(<a href='?logout'>Logg ut?</a>)";
}else{
echo "<form method='post'>
Brukernavn: <Input type='text' name='user'><br>
Passord: <Input type='password' name='pass'><br>
<input type='submit' value='Logg inn'>
</form>";
}
?>
"? – carmel Mar 18 '15 at 10:01