PHP Session Variable In JavaScript - php

How could I input php in this so when it has a correct password it stores the information as a cookie and then allow the deletion to it too.
<SCRIPT language="JavaScript">
<!--hide
var password;
var pass1="password";
password=prompt('Please enter your password to view this page!',' ');
if (password==pass1){
alert('Password Correct! Click OK to enter!');}
else
{
window.location="//Some Location//";
}
//-->
</SCRIPT>

If its simple enough (As per the title)
var varname = '<?php echo $_SESSION["variable_name"]; ?>';
But you have to seriously consider your logic. You are checking for authentication on javascript, which is going to be dumbest move in a web application.
The password is totally exposed, and any one can view them or turn off the javascript as a whole, then your whole site becomes vulnerable.
My suggestion is an AJAX request to a PHP page which separately checks and verifies the password and then returns message to the Javascript.

This is completely wrong:
You will have password displayed in the source code of the page and in the history of the browser for anybody to see. So even if they don't have the password, they can just check the source-code to get it.
You need to protect the current page server-side as anybody that disables javascript can open it now. An easy way to do that, would be to handle the login server-side and set a certain session variable for a successfully logged-in user. You can then check at the top of your page if that session variable is set.

Related

Login error after form submission

What I want to do is have a form that checks login information, and then, if the information is not right, it would redirect me back to the page where the login form was, but showing a p element that says something like "wrong username/password".
Is there any way I can do this? Or is there any way I can do the login check using only jQuery/ajax?
I have been trying to solve this for the past few hours, but I just could not get it right. Please bear in mind that I am a newbie in the field of web programming so don't be too harsh if there is an obvious answer to my question.
Credentials should be stored on your server.
Using ajax, on form submit:
Make ajax request to php with the users name and password
Have php verify authentication
If invalid return message to JavaScript
javascript can alert user if invalid, else it can change the location appropriately
Return from your server a 401 Unauthorized response code (see here: http://en.wikipedia.org/wiki/List_of_HTTP_status_codes#4xx_Client_Error)
You can return the code using a PHP header directive: http://php.net/manual/en/function.header.php
In your javascript function, add an error callback and update the DOM as you see fit.
Yep, you can POST to a login form with ajax. I'll assume you have some form elements already and just need to post to the login page. You can create a post request like this:
xhttp=new XMLHttpRequest(); //make a request
xhttp.onreadystatechange=function() { //The request is asynchronous, this function will be executed once it completes
if (xhttp.readyState==4 && xhttp.status==200) {
if (xhttp.responseText==0) { //or whatever else your "error" is
document.getElementById("errorDisplayDiv").innerHTML = "Login failed!"; //show a login error text
}
else if (xhttp.responseText==1) { //login page reported a success
document.location = "usercontent.php"; //redirect to a page for logged in users
}
}
}
xhttp.open("POST","login.php",true); //post to your login page
xhttp.send(); //send it
So there are a couple of things you need here:
Username and password form on your login page that will be posted to login.php
A login.php (or ASP, whatever) that verifies the username and password and records that the client is logged in
A usercontent.php page that verifies that the user is logged in and displays the proper content, or redirects them to the login page if they aren't.
This was just a quick answer, please comment if you need details on any of this.
Along with what dm03514 said, don't try to authorize users on the client side - anyone can view the source and figure out the credentials. Here's a very simple AJAX implementation using jQuery:
http://jsfiddle.net/UTCbM/
The 'url' (check_username.php) should contain the logic for processing the username and password. This can be via a database, or something as simple as this (but not recommended):
<?php
$users = array(
'user1' => 'password1',
'user2' => 'password2'
);
if ($users[$_POST['username']] == $_POST['password']) {
die(json_encode('login_success.php'));
}
die(json_encode(False));
?>
Things to note:
1) Don't store passwords in plaintext. If you're using PHP, check out Bcrypt:
http://phpmaster.com/why-you-should-use-bcrypt-to-hash-stored-passwords/
At the very least, hash and salt your passwords.
2) This jsfiddle doesn't do SSL, which you should strongly consider for logging in to a public site
3) You'll have to add 'dataType':'json' to the AJAX call (I forgot in the fiddle) if you want to return data as JSON.
4) By evaluating the AJAX response, you can display the appropriate error message in the .login-errors DIV. This is just a quick example.
Finally, if you're doing this on a public site, PLEASE read up on some security best practices in regards to storing/accessing login credentials. If this is beyond what you're looking for, consider reading up on access control via .htpasswd
Again, this is a VERY simple implementation, I would not go live with something like this, but hopefully it will get you started.
Edit: For clarity, the 'error' message returned is because of the 'error' function being called since the AJAX won't work on the fiddle. You'll actually want to code your error messages into the 'success' function, as counter-intuitive as it may seem at first.

How do I obtain URL variables with Javascript

I'm writing a log-in system using PHP, mySQL and Javascript. My site is effectively a 1 page app written in javascript - only 1 html page. All interaction and navigation is done through javascript.
When a user registers, I create their record in the db with a 32 digit key in the activation column. I e-mail this to the registrant as an activation link. This takes them to a php file that activates their account (or not if there is an error). All well and good.
After activation (or error) I could take them to an html page (e.g. header('somesite.com/success.html') telling them whether their account is activated or not but I'd much rather take them back to a specific function in my 1 page javascript site. How can I do this?
I can take them to the site but how do I pass a message from my php re-direct to the site so it knows whether to display a success or error message?
Do I put it in the URL of the re-direct e.g. http://somesite.com?activation=success? If so, how do I get this variable into my javascript?
I could set a session variable from the php activation script and check it in my code but that seems very clumsy.
I could set a hash in the URL and pick that up in the code but I avoid hash navigation if I can. Any ideas on the method to achieve this?
Final answer from the help below and elsewhere on the site:
function getURLParameter(name) {
return decodeURIComponent(
(RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]
);
}
then a redirect on registration such as somesite.com?email=somebody%40else#somewhere.com&key=7da93f78cb4942555863c161f50f258d
I can get these variables as simply as getURLParameter('email') and getURLParameter('key')
Thanks for everyone's help. Gotta love this site
You can get the variables from the URL with Javascript:
I actually asked a similar question (I can't find it) about getting URL variables with Javascript, and somebody very helpfully gave me this function:
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {vars[key] = value});
return vars;
}
So to obtain a GET variable called 'activation' you would simple call the function like this:
getUrlVars()['activation']
since you have everything in your one page app, you could use that for the activasion as well -- have the activation link go to http://homesite.com?activation=<32characterkey> and when your app detects the GET param, use AJAX to call the PHP activation, and notify the user of the outcome.
You should use to AJAX to login and call your functions in the AJAX success/error callbacks.
You can do that easily with jQuery $.ajax() function
http://api.jquery.com/jQuery.ajax/

Redirect website from within frame PHP

I have a web page, let's call it main.php which displays an image of football field and some players distributed on the field. However, that page uses list.php as a right side frame that loads a list of players.
What happens is, when the user clicks on a player on the field (main.php), let's say on the image of the Goal Keeper (GK), a list of GKs from world wide teams will load in right list fram (list.php). This is by using ajax.
So far we are good.
The current situation is, when session times out and the user clicks on a player from the field, the list on the right does not load, instead, list of players disappears from the list and a message says "Please login" is displayed on the right side frame (list.php)
The objective is, when session times out I want the whole website to redirect to the main page index.php
The problem is, I already put the redirecting code just before the code that is responsible of displaying the message "Please login". But what happened is, the redirection happens from within the frame, so i ended up having main.php displaying the field, and list.php displaying the main page!
Here's the code I added.
$user_id = NSession::get('user_id');
if (!isset($user_id))
{
NSession::removeall();
General::Redirect('index.php');
}
They are using Smarty. and btw, I added the same code to top of main.php, and now if user tries to access main.php without logging in, it will redirect him to the main page, so the code works!
n.b. The project is not mine, it belongs to the company I work in.
And I don't know which code is checking the session, all what I know is, if the user click on a player from the field after the session timeout, the "Please Login" message will be shown in the frame.
I'm guessing the redirect is essentially the same as using a header() function. It isn't possible to specify a target using a php redirect as it is server-side - specifying the target is client-side.
You would need to print something like this to the screen:
<script type="text/javascript">window.open('index.php','_parent');</script>
And that will redirect the user to the index.
Using frames for such purpose is... well... so 80ish...
Anyway, the frames are probably named in such a scenario. This means you can address them, but also that you have to address them. Just loading an url inside the "current" frame does exactly that, which is why your approach won't work.
If you really have to go with that frame based approach, then you will have to use javascript to address all known frames and redirect them.
Maybe you can use some javascript inside of your frame like so :
<script type="text/javascript">
window.top.location = 'YourPage.html';
</script>
Hope this helps
The issue was that the session expires while I'm on main.php. Therefore, any subsequent Ajax requested will fail since all requests requires session to be active.
the problem was that the Ajax request being sent from the IFrame (the IFrame is inside main.php and points to list.php thru Ajax calls) is failing due to session expiry.
So I've fixed this issue by adding another two session checks, one on main.php, list.php using PHP (check for session, if it's there, redirect). And in the main container, main.php, I check for the session via JS, interval Ajax requests to check the session, if session has ended, then use redirect using JS.
PHP:
$user_id = NSession::get('user_id');
if (isset($_POST["checklogin"]))//check loging
{
die(isset($user_id) ? "true" : "false");
}
if (!isset($user_id) || $user_id == "")
{
NSession::removeall();
General::Redirect('login.php');
}
JavaScript:
jQuery(document).ready(function($) {
$(window).focus(function() {
checkSession();
});
});
function checkSession()
{
$.ajax({
type: "POST",
data: {"checklogin": "cl"},
url: "list_players.php",
success: function(result) {
if (result === "false")
{
if (FIELD.showMessage === false)
{
FIELD.showMessage = true;
alert("Your session has been closed\nYou will be redirected to login page now. ");
window.location.href = ("login.php");//incase user clicks OK
}
}
}
});
}

Different page conten when JS is disabled

i've got a slight problem with JS enabled detection.
not too big, because i know i'm on the right track.
but here's my deal:
when i try to set a cookie in JS (jQuery) using this code
$(window).load(function(){
$.cookies.set('c_jsEnabled', 'true');
});
or just in plain JS using this code
function setCookie()
{
document.cookie='c_jsEnabled=true';
}
<body onload="setCookie();">
and then try to detect it in PHP using this code
if($_COOKIE['c_jsEnabled'] == 'true')
{
if(file_exists('./main.php'))
{
require_once ('./main.php');
}
echo getIndex();
}
else
{
if(file_exists('./noJS.php'))
{
require_once ('./noJS.php');
}
echo getIndex();
}
setcookie('c_jsEnabled', '');
it takes 2 page refreshes to actually get the right value into PHP.
my guess is that this bascially means that the PHP script is executed before the JS function is fired.
could this be because all codes shown above are in the same script (index.php)?
This is kind of a problem for me, because i want to prevent people from using my website when they have JS disabled.
is there a way to set the cookie before php tries to get the cookie variable?
PHP is always "fired" before JavaScript because PHP is processed on the server and then sends out the HTML and JavaScript for the browser to process and render. You can never expect JavaScript to execute before PHP for this reason.
In your case, use JavaScript to set the cookie and then do a redirect to refresh the page so PHP can get the cookie value and act accordingly.
You should be setting the cookie directly from the PHP file. That way, you know that it exists, and more importantly, you have control of the cookie. You can set it from the client, but that will always execute after the HTML has been sent to the browser, so the PHP file won't get it until the next request.
PHP only sends the cookie header when content is sent to the browser. Javascript then executes after that, so you would need a second load of the page to detect the cookie.
This can trigger infinite redirection loops (especially if the user has cookies disabled), so be careful.
To disable the site to users without Javascript, consider the following.
<div id="noscript" style="width:100%; height:100%; z-index:999; position:absoloute; top:0px; left:0px; background-color:#CC9900; display:block">
Please Enable Javascript!</div>
<script type="text/javascript">
document.getElementById('noscript').style.display = 'none';
</script>
I find the <noscript> tag is unreliable (there was a bug in iOS causing it to only show when there was Javascript, if I remember correctly).
A second option:
You can have the PHP check for a cookie. If it isn't set, have it redirect (header("Location: aaa.html");) to a page with the Javascript to set the cookie and redirect back. (Alternatively, have the PHP output Javascript to set the cookie reload the page.) You then only have to worry about users who "spoof" the cookie, although you will also lock out users who have cookies disabled.
Nope - PHP will always be called before client-side JavaScript, so with this method you'll always have to refresh the page at least once. You're better to develop your site so that non-JS users have a worse-but-still-acceptable experience, or at worst use the <noscript> HTML tag to serve alternative content to those users.
You can't get a cookie in PHP that's being set by JavaScript before the page renders/executes.
You could set the cookie using PHP, however. That will ensure it's set and available regardless of JavaScript or multiple page refreshes.

How to detect cookie and javascript with browsers

I am using PHP/JavaScript/MySQL on XAMPP to develop the prototype.
I need to use session that in-turn makes use of cookies. Here is the question,
how do I know whether or not the user's browser supports cookies or not.
For detecting javascript, I use <noscript></noscript>. Please correct me if I am wrong.
Thank you
You have to set a cookie and test it to see if they're enabled:
<script type = "text/javascript" language = "JavaScript">
var tmpcookie = new Date();
chkcookie = (tmpcookie.getTime() + '');
document.cookie = "chkcookie=" + chkcookie + "; path=/";
if (document.cookie.indexOf(chkcookie,0) < 0) {
window.location = 'nocookies.html';
}
else {
window.location = 'cookies.html';
}
</script>
Here is the question, how do I know whether or not
the user's browser supports cookies or not.
If a cookie isn't set, set a cookie and redirect to a page that checks if the cookie is set. If it is, redirect back, otherwise redirect to a "Sorry, we really need cookies" page.
Only do this if you do really need cookies.
For detecting javascript, I use <noscript></noscript>. Please correct me if I am wrong.
Better to build on things that work.
I will choose different style of detecting.
To detect whether javascript is enabled/disabled, i will write some little elements (perhaps div) and i will execute some javascript to remove such elements. Hence, when the javascript is disabled/doesn't exist, those elements will still be there saying that "Please activate your Javascript". On the other hand, those element(s) will be gone since javascript is already remove them. After all, it comes back to your website concept. Some website can't do anything when javascript is not exist/disabled and further they choose to redirect the request into another page (through tag). Some websites still can function but certain feature will not be available, and this concept leads to "warning" technique.
To detect whether cookie is enabled/disabled, just set a cookie using Javascript. In next request, you can check whether such cookie is set or not. If it's set, then both Javascript and Cookie is enabled. If it's not set, then Javascript or Cookie or both is disabled.
Good luck

Categories