Show different content before and after logged in - php

I want to show different div with different contents in different condition.
If customer is logged in, then show content A,
If customer is not logged in, then show content B,
This is the script I have, not sure it is correct or not.
<?php if (!$logged) {
$disp_div=1;
} else {
$disp_div=0;
} ?>
This is the jQuery
<script type="text/javascript" >
$(document).ready(function(){
var show=<?php echo $disp_div; ?>
if(show==1)
{
$('#div_logged_in').show();
$('#div_not_logged_in').hide();
}
else if(show==0)
{
$('#div_logged_in').hide();
$('#div_not_logged_in').show();
}
});
This is the HTML
<div id="div_logged_in">
Content A
</div>
<div id="div_not_logged_in">
Content B
</div>

A: Why !$logged is wrong:
You use a local variable. Next time your user refreshes the page he won't be logged in anymore. For that you can store variables in a array called $_SESSION . This array is saved for a client session on you webserver. As longs as the user stays there it will always remain the same (until YOU change it). For that you need a session_start(); in the first line of you main PHP script.
B: Why the javascript part is a security leak:
Your website is designed not to filter the content that is sended to the user. Every user gets the whole content, just the visibility is changed. In this way every advanced user can just look into your code and see all the secrets you want to hide.
C: What is the right way?
It just some PHP that echos HTML without Javascript and uses $_SESSION:
<?php
if($_SESSION["loggedIn"] == "yes") { //You have to set that somewhere else just like $logged
?>
<p> You ARE logged in. </p>
<?php } else { ?>
<p> You ARE NOT logged in. </p>
<?php
}
?>

I don't know what is $logged. If it is the variable to find whether the user is logged in, then your condition is just opposite of your requirement. You are showing div_logged_in when the user is not logged in from this condition.
if(show==1)
{
$('#div_logged_in').show();
$('#div_not_logged_in').hide();
}
The value of show will be 1 when $logged is false. So change the condition and you will get it. In this scenario, i would suggest you to go with SESSIONS. You can use anywhere to check whether the user is logged in or not.

First off, you need to start reading about sessions and the $_SESSION superglobal.
After that, throw that script away, and look for a proper tutorial, I found a very nice one here: http://net.tutsplus.com/tutorials/php/a-better-login-system/ - though it may be a bit advanced since it talks about ACL, which you probably won't need.
But if you can try and understand the rest of the tutorial, you should be fine. Good luck!

Please do not depend on client-side validation because its a security flow within your application, what if the customer viewed the source code for your page? then they see hidden contents.
Your approach is correct but you have to use $_SESSION or $_COOKIE not if (!$logged) and as I said, do not out put the content totally.

use
if($_SESSION["username"])
you can set it in the login.php file
and destroy it by using session_destroy() on the logout.php

Related

Redirect user to another page if not logged in?

This may seem pretty confusing at first but I have a log in system on my website. I also have a forum on my website. What I want to do is make it so if people click on the forum button and they aren't logged in, it takes them to the login page, but if they are, it will take them to the forums. I have that in place but I am trying to do one more thing. I also want to make it so if people go in the url and type www.example.com/forums.php, it will check if they are logged in and if they aren't, take them back to the login page and if they are, proceed to take them there. I tried with this but it only works for the first part like I stated, not the rest.
<!-- Main Content -->
<p class="japanese">プレーンズ</p>
<p class="dev" contenteditable>currently under development</p>
<p class="clock"></p>
<p class="login">login</p>
<p class="register">register</p>
<?php
if (isset($_SESSION['u_username'])) {
echo '<p class="forums">forums</p>';
} else {
echo '<p class="forums">forums</p>';
}
?>
On top of your forums.php, check if the session is active, and if not, issue an HTTP redirect.
<?php
if (!isset($_SESSION['u_username'])) {
header('Location: login.php');
exit();
}
The exit is important to avoid running any more code on the page if the user is being redirected.
And the redirect should be placed before any output takes place, which means that it should go at the top of the file being executed.

How to remain on page after login & log out

how do i create the below php that the user stays on the index page after logging in ? It seems it will direct the user to the logonprocess.php after clicking the submit button.
I'm also trying to find out how will the logout button appear after the user login successfully. The logout will also need to work the same as login which will stay on the same page.
I have read that ajax was one way but i have not yet read or understand ajax. I'm still trying to learn on the php portion first.
Index.php
<?php
ini_set("session.save_path", "sessionData");
session_start();
?>
<?php if (!isset($_SESSION['uName'])) { ?>
<form method="post" action="logonProcess.php">
<div>Username <input type="text" name="userName" placeholder="Username"></div>
<div>Password <input type="password" name="pwd" placeholder="Password"></div>
<div><input type="submit" value="Logon"></div>
</form>
<?php } else { }?>
<?php if (isset($_SESSION['uName'])) {
$username = $_SESSION['uName'];
echo "<p>Welcome $username</p>\n";
?>
Logout
<?php } else { }?>
Logout.php
<?php
session_start();
if(session_destroy()) // Destroying All Sessions
{
header("Location: index.php"); // Redirecting To Home Page
}
?>
At the end of your logonProcess.php file:
header('Location: index.php');
If you login from different pages use the $_SERVER['HTTP_REFERER'] variable.
header('Location: ' . $_SERVER['HTTP_REFERER']);
If you want to redirect somewhere after a certain script has been executed you could ofcourse always use PHP's header() function which allows you to specify a Location which would look like this
header('Location: index.php');
After that your part two of the question is "How do I remove the logout button when the user login successfully?" I think with login you must mean logout since you'll want to be able to actually logout once logged in.
To do this you check wether or not a $_SESSION
A $_SESSION in PHP is simply an array containing values that are remembered across page reloads so as you can imagine - it is a very good place to store your user ID.
The reason that usually just an ID is saved is so that while a hacker might still be able to compromise your users' cookie he / she will not be able to see any data he / she shouldn't have like a password, email address, phone number etcetera so all damage done will be on the website itself, not the users personal life ^.^
When you create a $_SESSION in PHP you simply set it in your logonProces.php file after all the authentication checks for the user passed.
This would look something like this (semi-psuedo code)
if ($user_verified_in_db) {
$_SESSION['user'] = $user['ID']; //note - non of this will probably exist yet in your script, DONT use it its an EXAMPLE.
header('Location: index.php');
}
The above snippet should be placed somewhere appropiate in the procesLogon.php file so that the session will be set.
Now in HTML you'll have a link somehwere right?
Logout
Imagine that is your link being displayed somewhere on the page, now what you want to do is check if the $_SESSION['user'] is set using isset().
Your code would look something like this:
<?php if (isset($_SESSION['user'])) { ?>
Logout
<?php } ?>
this will check if the session is set or not, if it isn't set it won't display the link, if it is it will since you'll need an option to logout.
NOTE this is psuedo code - you still have to build this construction using your variables and your login script, my tiny piece of code doesn't do anything for you at that except show you an example of how this is commonly handled.
Good luck!
EDIT (5-11-2015)
As per the comment of the OP,
If you want to hide items in general, like the logout link example above, all you have to do is wrap the divs you want to hide in the if statement.
e.g.
<?php if (isset($_SESSION['user'])) { ?>
<!-- this can be any HTML element showing stuff for logged in users. -->
<?php } ?>
when you wrap elements within this if statement - if you check the expression: isset($_SESSION['user']) - it will evaluate to true if $_SESSION['user'] is set which you are in your login script.
You can keep reusing this check whenever and wherever you need to show / hide elements from the user.
if you would put a ! (exclamation mark) in front of the expression so that it turns out like this: !isset($_SESSION['user']) you reverse the process so if you have the following statement
<?php if (isset($_SESSION['user'])) { ?>
<!-- everything here is shown when user is logged in -->
<?php } else { ?>
<!-- everything here is shown when user is logged out -->
} ?>
this is the positive if check checking if your user is logged in or not, you can decide to put in the else for what to do when the user isn't logged in but you can also modify the expression slightly to reverse or invert the situation e.g.
<?php if (!isset($_SESSION['user'])) { ?>
<!-- everything here is shown when user is logged out -->
<?php } else { ?>
<!-- everything here is shown when user is logged in -->
} ?>
for instance. This will allow you to gain control over what users see on your webpages, use them whenever you need to show or hide something.
Also note that the else clause is ofcourse, optional and doesn't have to be included, you can use the ! example without the else as well as the one without the exclamation mark.
You can put this code end of php file logonprocess.php too.
echo "<script>window.location='index.php'</script>"
You will have to add the echo "<script>window.location=\'index.php\'</script>" to an if/else statement within your logonProcess.php so that once they "submit" the information it processes and redirects to index.php.

Echo two different page view on the same page

In this case, I am going to echo/print two different page view in the same page, which it depends on whether the user has logged-in or not.
If the users are logged in, they can find all the menus in the page. However, if the user are not logged in, there would be some views I want to hide from them.
The method that I am going to use is:
First: check if the user has login or not (with session),
Then: show the page based on the result of the check of session.
And I will use this code:
<?php
session_start();
if(isset($_SESSION['login_id']) && !empty($_SESSION['login_id'])){
?>
YOUR HTML CODE
<?
} else {
?>
YOUR HTML CODE
<?}
?>
My question actually is very simple, I just want to make sure, if I use this method, won't it make the page to load slow?
If this will make the page to load to slow, is there a good method for I to achieve this?
Thanks
It won't make your page slow (any code in the if-else block that isn't processed won't make any difference to the load time).
You might, however, wish to include a separate PHP file with the information you want to display, rather than code it directly into the if-else block. For example;
session_start();
if(isset($_SESSION['login_id']) && !empty($_SESSION['login_id'])){
include 'loggedin.php';
}
else {
include 'notloggedin.php';
}
Hope this helps.
Your page load is really going to depend more on the html then this php switch. I have dealt with pages with 30 switches like this on one page load. While not the best practice anymore you likely wont even notice.

Retrieve a php value and use it in javascript

In my website I set some values to session object like "user_status", "user_name" and like so. The php file looks like this:
<script type="text/javascript">
var logged = <? echo $this->session->getValueOf("user_status"); ?>;
</script>
<a class="show_message" href="#">SHow my status</a>
Well, I have a js script that pretends do an action according to user status in the website, so, I have this:
$('.show_status').click(function(event){
//ask for user status
if (logged){
//do something
}
else{
//do another action for visitors
}
});
Walking around I thought if it is the best way flow data between session -> javascript, because if you inspect the page source at browser the value of user_status will be visible and could be riskable for website security.
Thanks in advance
EDIT:
logged var only takes a boolean value.
The js action must be executed each time the element #(".show_status") is clicked.
If the JavaScript is just being used for interface stuff, and doesn't have any back end effects, I probably wouldn't worry too much about the insecurity of handling that logic client-side.
If security is an important thing though, I would recommend you use PHP to write the appropriate JavaScript function. For example:
On the page being viewed, perhaps in the header, you have:
<script type="text/javascript">
<?php
if ($this->session->getValueOf("user_status")) {
require_once('logged_in_user_functions.js');
} else {
require_once('visitor_functions.js');
}
?>
</script>
In the file `logged_in_user_functions.js' you have:
function showComment(id) {
//logic that shows the comment here
}
function showCommentSubmissionForm() {
//logic that adds this form to the page goes here
}
Meanwhile, in the file `visitor_functions.js' you have:
function showComment(id) {
//logic that shows the comment in a different way goes here
}
function showCommentSubmissionForm() {
//logic to display a message saying the user needs to log in to post a comment goes here
}
Then you can add your logic into your page without having to check the user status. The proper behaviour is provided by virtue of which .js file was included:
<button id='add_comment_button' onclick='showCommentSubmissionForm()'>Add Comment</button>
This gives PHP (and thus the server, not the client) final say in what gets displayed to the user.
Assuming that user_status will be something like Active, then this isn't really a security risk.
If you want to hide everything from casualy prying eyes, you could try using an encrypted cookie, using something like How to save encrypted data in cookie (using php)? to encrypt your values.

Display Admin Link On Every Page

My question is about how do I place a link on the side of every page that leads to the admin page once someone has logged on to my application successfully? I have a sample site I just built, and I would like a link to the admin page available in the navigation column to the right of the page which is displayed site-wide. But if the person is not logged in, they don't see the link, but will continue to see the usual links.
My background is totally different from web development, so forgive my stupid question.
I'm using PHP and MySQL for the application.
Without seeing how you display your menu or what key is used for the session, Ill assume some things:
<?php
session_start();
// do your login stuff and set session as logged in
$_SESSION['logged_in'] = true;
?>
Then in your menu or how ever you display it:
<?php
//navigation column
if(isset($_SESSION['logged_in']) && $_SESSION['logged_in']===true){echo 'Admin';}
//navigation column continue with rest of links
?>
Or the ternary operator assign link to a variable
<?php
$adminLink = (isset($_SESSION['logged_in']) && $_SESSION['logged_in']===true)?'Admin':'';
echo $adminLink;
?>
You should use a session variable to track the user's session and see if they are logged in.
if(isset($_SESSION['id'])) echo 'Admin Area';

Categories