Reputation: 151
I am new to using php, html, and building websites and am getting caught up on how Sessions work etc. I am simply trying to setup login/logout
on a website using sessions, mysql, and slim to provide some background.
I am getting confused on how to use sessions correctly if you are not allowed to run php on the client side. To my understanding what you would do is when you make the post api call to login, if it was successful you would set the $_SESSION['userLogin']
value to some value to show a user is logged in. Then on the home page file (index.php
), you would have php testing if $_SESSION['userLogin']
is set. If it is, then a "log out" button would be displayed. If it was not set, a "login" button would be displayed. Ii have typed out what I am talking about below. This doesnt work though because when my browser loads the page, the php is commented out.
Can someone explain this to me? If you cannot use php client side, how are you supposed to know if $_SESSION['userLogin'] is set and what html to load?
code:
<!DOCTYPE html>
<html>
<head>
<div id="content_area">
<div id="features">
<table>
<tr>
<td><img class="feature-icon" src="../_images/_icons/marshall-to-hunters.png"/></td>
<td class="feature-text">Connect to a large base of bug hunters.</td>
</tr>
<tr>
<td><img class="feature-icon" src="../_images/_icons/get-paid.png"></td>
<td class="feature-text">Get paid for finding bugs.</td>
</tr>
</table>
</div>
<?php
if(!isset($_SESSION['userLogin'])
{
echo '
<form id="login" name="loginForm" method="post">
<input class="loginForm" type="submit" value="Log In" id="submitLogin">
<input class="loginForm" type="password" name="password" placeholder="Password" id="passLogin">
<input class="loginForm" type="text" name="username" placeholder="Username" id="usernameLogin">
</form>';
}
else
{
//Sometype of logout button
}
?>
</div>
Upvotes: 1
Views: 65
Reputation: 455
In your code your saying is the $_SESSIOn['userLogin'] is set show the user a login form:
<?php
if(isset($_SESSION['userLogin'])
{
echo '
<form id="login" name="loginForm" method="post">
<input class="loginForm" type="submit" value="Log In" id="submitLogin">
<input class="loginForm" type="password" name="password" placeholder="Password" id="passLogin">
<input class="loginForm" type="text" name="username" placeholder="Username" id="usernameLogin">
</form>';
}
else
{
//Sometype of logout button
}
?>
if the $_SESSION['userLogin'] is set this means the user is logged in, so where your echoing out the form, you need to echo the logout button and kill the session.
To keep the code you have you could use if(!isset(.....
Also, as mentioned above in a comment, you need to include session_start() on all pages, you might be better off creating one file and including it in all the pages where you need to use the session code.
Upvotes: 1