I am having problems with this, when i login with valid data, the page just refreshes (i am assuming that the if statement in protectedstuff.php failed). When i used the deprecated method to register the session and check if it exists, it worked if(!session_is_registered(myusername))
.
Oh and also I am able to see a cookie was created "PHPSESSID".
what am I doing wrong?
login.php ->
<?php
if($_POST){
$errorLogin="Wrong Username or Password";
$link = mysqli_connect('localhost', 'root', '', 'mydb')
or die('Could not connect: ' . mysqli_error($link));
// username and password sent from form
$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword'];
$sql_query="SELECT * FROM users WHERE username='$myusername' and password='$mypassword';";
$result = mysqli_query($link, $sql_query) or die('query failed'. mysqli_error($link));
$row = mysqli_fetch_assoc($result);
$dbUserName= $row['username'];
$dbPassword= $row['password'];
// Mysql_num_row is counting table row
// If result matched $myusername and $mypassword,
if($myusername==$dbUserName && $mypassword==$dbPassword){
// Register $myusername, and redirect to file "login_success.php"
//session_register("myusername"); <- deprecated
$_SESSION['myusername']=$myusername;
header("location:protectedstuff.php");
}else {
echo $errorLogin;
}
}
?>
<table width="300" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<form name="form1" method="post">
<td>
<table width="100%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF">
<tr>
<td colspan="3"><strong>Login </strong></td>
</tr>
<tr>
<td width="78">Username</td>
<td width="6">:</td>
<td width="294"><input name="myusername" type="text" id="myusername"></td>
</tr>
<tr>
<td>Password</td>
<td>:</td>
<td><input name="mypassword" type="text" id="mypassword"></td>
</tr>
<tr>
<td> </td>
<td> </td>
<td><input type="submit" name="Submit" value="Login"></td>
</tr>
</table>
</td>
</form>
</tr>
</table>
the usernames and passwords are already in the database.
This is my protectedstuff.php
<?php
session_start();
if(!isset($_SESSION['myusername']))
{
header("location:login.php");
}
else{
?>
<html>
<body>
Login Successful
</body>
</html>
<?php
}
?>
Thank you!
I don't see a session_start()
above your $_POST
block. You must call that on every page BEFORE any output is sent
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.