JavaScript code to check if a session is active - javascript

I am wanting to write a simple and straightforward client side JavaScript which will check if the users session is still active and then enable some action to take place, and if not for some other action to be coded for.
I have searched for a simple piece of JavaScript to achieve this, but not been successful to date.

Use this code below
PHP
var session = '<?= session["username"] != null ?>';
.Net
var session = '<%=Session["username"] != null%>';
Java
var session = '<%= session.getAttribute("username") != null %>';
then follow it with this code
if(session){
alert("Your sesssion is active ");
}

maybe i dont follow your question good enough.
but what the issue with doing something like that (it can be much more mature ):
if (sessionStorage.user) {
console.log(1)
} else {
console.log('user not exist in the session storage')
}

Related

How can I redirect with extra information in jquery?

I'd like to perform a redirect, but I also wish to send additional information along with it.
I've tried to change the value of window.location.href but that doesn't seem to pass along the extra information.
I also get how I can do
$.get(
new_url,
{data : "mydata"},
function(data) {
alert('page content: ' + data);
}
);
and that will display the html content of the new page, but that doesn't help with actually getting there.
How can I achieve this?
Edit: I feel as if I must be phrasing this terribly because I'm pretty sure this is an easy/common task. This shouldn't be something that would require cookies - it should basically be like a post request (I think).
You have a few different options for this:
URI Variables - You can append extra data to the URL by appending a question mark (?) followed by a set of key-value separated by an ampersand (=) with each variable being separated by an ampersand (&). For instance, http://www.google.com/search?q=javascript+url+variables&ie=UTF-8 gives you a link to a Google search for "javascript url variables" using UTF-8 encoding. Your PHP code or JavaScript would need to handle passing along and processing these variables. If using JavaScript a nice library for processing URLs is URI.js or using PHP you can use the parse_url and http_build_query functions. You can use this with window.location.href; for instance: window.location.href = "http://www.google.com/search?q=javascript+url+variables&ie=UTF-8" (replace the Google URL with the one you created or set in a variable).
Storage API - You can use the localStorage or sessionStorage properties to store and retrieve information using JavaScript (information is stored in the user's browser - supported by IE 8 and newer and all other major browsers). Note that this is JavaScript only unless you grab the data with JavaScript and pass it to your PHP server through URL variables, form, AJAX request, etc.
Cookie - You can store additional information inside a cookie - however this is more difficult since you have to setup your variables as a parsable string (possibly JSON) and remember to encode/decode the string when setting/getting the cookie. I don't recommend this method.
IndexedDB API - This is a more advanced client-side/browser storage mechanism and currently only supported in IE 10 and newer (and nearly all other browsers). There are also still changes being made to the standard which means newer versions of browsers could break current implementations or be buggy. If all you need is simple key-value storage (not an SQL-like database) then you should stick with one of the above options.
You can use the window open method to redirect your user,and remember to use "_self"
window.open('url','_self');
Preferably you'd store the data in localStorage and fall back to a cookie (I really like js-cookie).
Here are the two helper functions you need to store and retrieve data:
function setMultiPageData(itemName, data) {
var dataStr = JSON.stringify(data);
var hasLocalStorage = typeof localStorage !== 'undefined';
if (hasLocalStorage) {
localStorage.setItem(itemName, dataStr);
}
else {
Cookies.set(itemName, dataStr, { path: '/' }); // path set to root to make cookie available on any page
}
}
function getMultiPageData(itemName) {
var data = null;
var hasLocalStorage = typeof localStorage !== 'undefined';
if (hasLocalStorage) {
data = localStorage.getItem(itemName);
}
if (!hasLocalStorage || data === null) {
data = Cookies.get(itemName);
}
var parsedObject = null;
try {
parsedObject = JSON.parse(data);
}
catch (ex) {
console.log(ex); // remove in production
}
return parsedObject;
}
usage:
var data = { first: 'this is the first thing', second: 'this is the second thing' };
setMultiPageData('stackoverflow-test', data);
// go to a new page
var retrievedData = getMultiPageData('stackoverflow-test');
if (retrievedData === null) {
console.log('something went wrong')
}
else {
console.log(retrievedData); // { first: 'this is the first thing', second: 'this is the second thing' }
}

Password protected redirect with php

I cannot seem to find the answer to this anywhere. The closest I have managed to do is to password protect a page with php, but every solution I've found in that regard I haven't been able to get to work properly. Basically I am making a web-based puzzle game. I have the current version set up with javascript to forces you to enter a password to get to the next level. I would like something similar in php because you can easily view the password if you look at the page source. I really like what this js code does, unfortunately I can't find any resources how to do that with php. Any help would be appreciated.
<SCRIPT>
function passWord() {
var testV = 1;
var pass1 = prompt('Enter the Code',' ');
while (testV < 3) {
if (!pass1)
history.go(-1);
if (pass1.toLowerCase() == "1234") {
alert('It came unlocked!');
window.open('sample-level.htm');
break;
}
testV+=1;
var pass1 =
prompt('That is not the correct answer.','Password');
}
if (pass1.toLowerCase()!="password" & testV ==3)
history.go(-1);
return " ";
}
</SCRIPT>
I just need to be able to protect the next destination page, not the current one.
You need to use PHP sessions. You'll need to create a Database, create a table in that database to store the username, password and perhaps email. Then you'll want to create a file to connect to the database. Include that file in your login/password form. All the code and information is a bit much to put here but the link below is very strait forward tutorial and should get you started.
http://code.tutsplus.com/tutorials/user-membership-with-php--net-1523

Disable the url in browser

I want to disable the URL so that no one can edit the data by changing the URL
I am posting the data in URL through get method in php.
How can I disable the URL?
You can't "disable the URL", you've stumbled upon one of the most fundamental issues of web programming: don't trust the client!
That is why web programmers have to check data to ensure it meets certain criteria before moving on...
<?php
if (!isset($_GET['example']) || ($_GET['example']!='foo' || $_GET['example']!='bar'))
{
//error
}
else
{
//proceed
}
?>

How Can I Insert A Value With Javascript (or PHP) Into a Form Depending On Visitor Referral

I'm not sure if the way to do this is check Google Analytics cookies or otherwise track where a user came to my site from. Basically I have a form with a hidden field code="XY1" Now I need to be able to insert a different preset code for say people who came from Facebook, so the script would have to check where the visitor came from and then assign a code XF1 to any from FB, and a code XT1 to any from Twitter, etc.
Would something like this PHP work for the capture?:
$referringPage = parse_url( $_SERVER['HTTP_REFERER'] );
if ( stristr( $referringPage['host'], 'facebook.com' ) )
Or this JS
var ref = document.referrer;
if (!ref.indexOf("facebook.com") != -1) {
document.write(...)
}
I'm not sure what is the best way to do it and what kind of methods can reliably check the source of a visitor, so any help would be greatly appreciated.
You can use $_SERVER['HTTP_REFERER'], but it's not guaranteed to be accurate, or even present. Not all browsers will necessarily set it, and some allow you to set it yourself. Google cookies won't contain any site history, and you can't examine the browser history, so there's no guaranteed way to do what you're asking.
You can try this option using jquery $.test() method.
$(function(){
var referer=document.referrer, //option 1
//referer="<?php echo $_SERVER['HTTP_REFERER'];?>",//optional 2
XFB=/facebook.com/g,
XFT=/twitter.com/g,
checkF1=XFB.test(referer),
checkF2=XFT.test(referer);
if(checkF1){
var code= "XF1";
$('#hiddenInput').attr('value','ref: '+referer)
}
else if(checkF2){
var code= "XT1";
$('#hiddenInput').attr('value','ref: '+referer)
}
});

javascript form checking and encrypted passwords

I have a simple form where users can change their passwords, and I am using an onsubmit event to check the form which generally works fine, except when I try to stop them using a password already in use.
The passwords are stored in a database and are encrypted. What I need to do is compare the encrypted password with the new password, which is not yet encrypted. The encryption I am using is:
<%
Function encrypt(x1, x2)
s = ""
t = 0
For i = 1 to len(x1)
t = t + asc(mid(x1,i,1))
Next
For i = 1 to len(x2)
y = (t + asc(mid(x2,i,1)) * asc(mid(x2,((i+1) mod len(x2)+1),1))) mod 255
s = s & chr(y)
Next
For i = (len(x2) + 1) to 10
If t>598.8 Then t = 598.8
y = t^3*i mod 255
s = s & chr(y)
Next
encrypt = s
End Function
%>
and I run encrypt(Username,Password) which gives me a output like ¬{±ÝÆÝl
The onsubmit code I am using is
function checkData (){
if (document.signup.password1.value != document.signup.password2.value) {
alert("Your passwords do not match.")
document.signup.password1.focus()
return false
}
if (document.signup.password1.value == "") {
alert("Please enter a password.")
document.signup.password1.focus()
return false
}
}
This all works fine and I am just stuck on the last bit which is the old password check.
I have tried various things like
if (encrypt(document.signup.password1.value,emailaddress) == "value from database"){
alert("The password chosen is already in use.")
document.signup.password1.focus()
return false
}
My main question is: can I call the ASP function encrypt into my javascript checkData? As I am beginning to think this is where the problem is, I am wondering if I am wasting my time and feel that there is no way of doing this. I know I can submit the form to the next page and do the check there but I really wanted to do it this way if I can.
You can not directly invoke ASP (or any other server side language's) functions from JavaScript. That being said, there is a widely used technology called AJAX, which allows you to execute asynchronous JavaScript requests to your server side application. They're called asynchronous, because you do not submit/reload the entire page, but you execute a piece of JavaScript which invokes a server side functionality and returns the result, thus letting you update your page without having to reload it.
In your case, you'd want to implement an AJAX request which asks your if a certain password entered by a user is already in use, and the server will simply return a boolean, which you'd evaluate on the JavaScript side and update your page accordingly.
I'm very certain that there are tons of tutorials and explanations on how to use AJAX requests with ASP (which I am unfamiliar with), and providing such an explanation would certainly be out of what can be provided here. Please consult Google :)

Categories