Javascript form validation based on PHP session variables - php

I have a login area of my site, and on login I set a session variable $_SESSION['logged_in'] = true.
Now I also have lots of forms and things where users can input comments. Obviously in my PHP validation I check the user is logged in simply using the session variable, but I want javascript validation too because I can make the user experience slicker that way.
$("body").on("click", ".submit", function(e){
e.preventDefault();
if (user == logged in){
...AJAX call to php file....
}
})
So how do people generally do the bit where I check the user is logged in using javascript?
ie
if user == logged in

You can of course check user permissions by AJAX (with JSON for example), but this will provide some additional latency.
You can just write a value to global JS scope like this:
if ( userIsLogged() ) {
echo "<script>document.mysite.userlogged = true;</script>";
}
then you can check document.mysite.userlogged variable.
You can also set a cookie in PHP, wich can be obtained in JavaScript. To get cookies properly in JS see that: Javascript getCookie functions
If you don't want to inject JS code, you can set some attribute like:
<div id="comments" data-logged="<?php echo $isLogged; ?>">
...
</div>
And get it by jQuery:
if ( $("#comments").attr('data-logged') == 1 ) {
you can provide logged/notlogged specific functionality for the whole page by generating JS file, like: <script type="text/javascript" src="http://yoursite.com/somefile.php"> and generate it in php dynamically, but be aware of caching !
Personally i would go to data-XXX attribute if tou want to personalize single block, and global JS variable if you check logged condition many times in JS.

Related

Show different content before and after logged in

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

Show login JS popup for auth required actions

I want to show a login popup, kind of overlay handled by JS when user clicks on any button/link which requires user to be logged in.
For Eg: If user tries to comment without signing in, on click of post I have to show this popup.
This is not ajax call where I can just reveal the popup based on the server response.
Is there a way to do this? Maybe by checking the status code or something like that?
The challenge is, when user is logged in the specific action takes user to another page, but when user is not logged in I want to suppress this and instead show login popup in same page.
Careful, even in chrome you can directly edit the javascript just by right clicking on the page > inspect element > resources > javascript, and typing your changes in, bypassing your check. Just to keep in mind that you use it only to increase the user experience, but make sure your php or whichever server side script checks for a valid session.
So assuming you are taking care of that, if you add a class to your buttons/links like so:
Post Comment
<form><input type="submit" class="requires_login" value="Post Comment" /></form>
you could for instance use javascript or jquery:
$(document).ready(function(){
var valid_session='<?php echo (isset($_SESSION['id']) ? 'true':'false'); ?>';
$('.requires_login').on('click',function(event){
if (valid_session=='false'){
event.preventDefault();
alert('open popup instead');
//for instancce, $('#my_popup').show(); if you have:
//<div id="my_popup">You must be logged in first!</div>
}
});
});
Hope that helps!
The easiest way would be to redirect on the page that requires a login, you can do that with $this->response->redirect('auth/login');
If you really insist on a js popup you either have to use AJAX or you could write the following in your view:
<script language="javascript">
var loggedIn = <?= Auth::instance()->logged_in() ? "true" : "false" ?>
</script>
You would have to check on each action if the user is logged in before redirecting.
Also a problem with this approach is that it does not handle session timeouts.

How to show actual values of javascript variables in a test div?

I have a 2-player boardgame with a lot of (changing) variables.
For testing purposes, I want to show all these javascripts variables inside a testdiv, like:
<div id="testdiv" style="margin-top:800px;background-color:yellow">
/** here the listing of js vars and arrays */
</div>
This boardgame uses a backend-file for updating the game, but i get lost when trying to follow what happens exactly with the javascript vars.
I do know the names of the vars and arrays.
After change of turn, i refresh the page, but I want to update the page via ajax (jQuery).
For checking the playersturn, i already use jQuery and the taconite plugin form http://www.malsup.com/jquery/taconite/
This plugin returns xml, like this:
### Taconite output
?><taconite>
<?php
echo $content_refresh; // refresh pagina indien nodig
echo $content_redirect;
echo $content_melding; // melding over verlaten tafel of afgewezen!
echo $content_inpartij; // tegenstander in partij??
echo $content_chataangevraagd; // chat door tegenstander aangevraagd?
echo $content_wachtopaanschuiven; // div leegmaken zodra 2e speler in partij is
echo $content_starttijd;
?>
</taconite>
Al content vars are generated xml, for example
## Taconite: refresh nodig??
if($refresh_needed == 'ja')
{
$content_refresh = '<eval><![CDATA[
window.location="http://www.xxxxxxxx.nl/v45/partij.php?gameID='.$_GET['gameid'].'";
]]>
</eval>';
//$meta_refresh = '<replaceContent select="#refresh"><META HTTP-EQUIV="refresh" CONTENT="0"></META></replaceContent>';
}
So, instead of refreshing I just want to update the boardgame, but just have not an overview of al (known) present javascript values.
Thanks in advance for any help!
I'm not familiar with your plugin nor is your serverside technology listed (guessing php) so I would say take a look at the json serialization abilities of php at http://php.net/manual/en/book.json.php
Then what you should be doing here is in the javascript on the client side, make an ajax request like you are, but have the server side code written using json to send down just the data that represents either the necessary changes or the whole board state. On the client side the JSON object will be recieved and usable as a direct javascript object which you can then have a method that processes it to manually update the board state based on the data the server sent down.
edit:
Sorry, forgot the scope was to get debug information here, for that the method which renders an update to the board, should also render said debug info into a separate div on the screen somewhere. I would use jquery for the ajax if you aren't already, and with jquery you can use the selectors to do:
$("#debugDiv").text("Var a: " + boardState.VarA);
$("#debugDiv").append("Var b: " + boardState.VarB);
Take a look at:
http://api.jquery.com/append/
http://api.jquery.com/id-selector/
http://api.jquery.com/element-selector/
http://api.jquery.com/category/selectors/
In javascript the variables that you declare globally are usually attached to the window object. So if your variables are in global Scope you can check them in DOM tab of firebug, and click on window.
The problem is that you will see a lot of other variables also there.
If your variables are in some other scope you can just check what is inside the particular scope.
If you want to print them in a div, you will need some way to distinguish your variables from other variables and then use a for in loop along with hasOwnProperty and typeof.
That being said, the best way is to restructure your application so that its atleast transparent to you.

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.

How to use Post method without a Form

I am that kind that spends more time looking for bugs in web projects and correct them, but I still have one question about the use of the GET and POST method
To summarize , I often use the GET method for queries that may be coming from links or simple buttons example :
Click me
and for forms (signup,login, or comment) I use the post method. but the question is:
sometimes (Multi-steps signup for e.g), I may need to pass the info collected from the form in page 1 to a page 2 (where the user can find a captcha for e.g). in order to send them to the database if the captcha test is Okey. But the question is , how to pass those info to a next page via a POST method without using a hidden form?
Do I need to recreate a POST method from scratch with a socket?
thank you
You can use JavaScript (jQuery):
First u need to load jQuery ( using google as host or you download it):
<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.js"></script>
Then...
<script type="text/javascript">
$(document).ready(function() {
$('#Link').click(function() {
$.post("example.php", { n: "203000"} );
});
});
</script>
<a id="Link" href="#">Click me</a>
Edit:
after that save it in the SESSION in example.php
$ _SESSION['N'] = (int) $_POST['n'];
When this value will be stored on the server side. And tied to the client session, until he closes browser or that it set the time for that session on the server side runs out.
Edit2:
There is also another possibility to post requst, yes ..
But I do not like this method myself ...
And here is the form used, something the OP did not want.
<form name="myform" action="example.php" method="POST">
<input type="hidden" name="n" value="203000">
<a id="Link" onclick="document.myform.submit()" href="#">Click me</a>
</form>
Use sessions to store the data until you submit them:
http://de.php.net/manual/en/intro.session.php.
Using sessions has a big advantage,
once you have verified the data you can store it.
Always keep in mind that users may manipulate POST requests!
If the problem is to pass info between pages like in a multi-step form you should use session (if you are using PHP).
By the way for send a POST request without form you need to use CURL like in this example
The statement is a HTML language statement used by a browser to initiate a POST/GET data relation. The Browser is the execution environment.
You can use other languages (and their execution environment) like Java, Java Script, C#, etc. to initiate HTTP POST/GET data relations.
Sorry if I'm not understanding you correctly, but from what I'm reading, you want to access form data entered on page 1 (using a form with a post method) on page 2? If so, use the $_POST autoglobal array. For example, $nameOnPage2 = $_POST['nameFromPage1']. You don't have to create a form on the second page for this.

Categories