After authentication, the server side code either goes to a default page or goes to the original page on which the user had clicked before authentication. In all cases, the page is rendered after a redirect (I am using django). In this case, how do you execute a one time javascript code on the rendered page? One way I can think of is to add a "parameter" that indicates to the page being rendered that the one time code should be executed. The "onload" function can then check and execute the code. Is there any other, "more elegant" way?
You can either set a cookie or add a class on the body with Django. On the client side you simply check if the cookie or the class is present. In case of the cookie it would be best to delete it with JavaScript.
I think the solution you're describing is within the acceptable range of elegance. Anyway, another approach is to use cookies:
The authentication page will set a cookie, the page you land at (after authentication) will check this cookie. If it's there it will run this 'one time' code and clear the cookie.
Related
Exactly when and where should I use session_start() in PHP?
For example, say I have a login script that sets a session variable to tell whether or not the user is logged in. Must I then put the session_start() at the top of the script, or only right before I actually set the session variable if the login was successful?
<?php
// session_start(); here?
if (login($username, $password)) {
// session_start(); or here?
$_SESSION["username"] = $username;
}
?>
Another case is this, according to w3schools
Note: The session_start() function must be the very first thing in your document. Before any HTML tags.
As others have said, the absolute requirements of what you must do are:
You must run session_start before you read or write to $_SESSION (otherwise it will just be an ordinary array and not saved anywhere).
You must not run session_start twice during a single script execution (page load) unless you use session_write_close to close it in between.
There is an extra rule that technically has exceptions, but is best treated as absolute:
Do not start the session after you have written any output (echo, HTML outside PHP blocks, etc), because PHP may not be able to send cookies to the browser if the server has already started sending the content.
There are two reasons you might want to avoid starting the session:
PHP locks the session when you open it to avoid two processes writing conflicting data into it, so if you have several requests happening at once, you want to avoid them waiting for each other unless they really need to. For instance, if you're responding to an AJAX request, and don't need any data from the session, don't open it.
As mentioned by symcbean, there is some cost to creating a new session, so if your site is busy with either legitimate or malicious traffic, you might want to serve some landing pages or error messages without starting it at all.
After that, it becomes a matter of style and architecture, but the rule of thumb that covers most of the above is "as soon as possible, if you're sure the page needs it".
Unless you have output buffering enabled, the session_start() must come before anything other than headers are sent to the browser (as it sets a cookie in the header).
It must come before you attempt to reference the $_SESSION data.
In your example there are no html tags being output before either instance - so both would work.
There some cost to opening a session, so if you are doing additional, non-session based validation of the request, then deferring session_start() till these checks have passed does give you a bit more resillience against DOS attacks.
Starting the session at the top of the page is most of the times the best. But if you don't need the session for the whole document/code, you could always put it, as in this example, after the if() clause.
The session_start() function can go anywhere in your code. You should just place it at the beginning of your document for consistency and call it a day. If you have a separate database or config file you are including on all your login/database driven pages, you should place it in there so you don't have to recode it into every page.
I'm totally new to make a website with javascript AJAX. I want to provide every experience on my website with one domain(like Facebook), thus I made every page-changing method with javascript AJAX. At first, when you visit my website, you have to log in, after that it turns to the main page and you can go to several menus with clicking button which triggers page-changing method.
The problem what I faced is.. I've recently seen someone typed javascript code into the console to delete all of his(or her) photos on Tumblr instead of clicking all of that. The idea hit my head.
Every page-changing method in my website also can be called without login. Someone can input page-changing javascript code in the console without login and see the contents of pages.
The first idea came to my head to prevent this situation was, to send id/pw every time when I make a post request to the server and everytime server gets the request, server checks the id/pw to assign the browser to change page. For instance, when a user wants to go to menu A, he(or she) has to send his(or her) id/pw to see the content of menu A.
I thought this is such a bad idea. As I guess it will result overload in server CPU when the server always has to check id and pw(sorry, I don't know well about server CPU and process, this is just my supposition). So I guess there is another way to verify the user and their requests without sending id/pw every time.
Does anyone know about that? Or should I check id/pw with every post requests?
To answer you, you are talking about Cross Site Scripting. Let me first point you to some documents in order to make you aware of what you are dealing with:-
Its called Cross Site Scripting using which a user on the client side inject script in your website and change the different stuff on it.
https://en.wikipedia.org/wiki/Cross-site_scripting
Now to deal with such things there are remedies as following:-
CSRF Token
JWT
Both of them work in somewhat identical way but there are data and payload carrying capacity and encryption involved in JWT and I recommend that.
This is a very known problem in the community and is also pretty old.
On the other hand I will also recommend you to do a data sanitization before storing it into your database. Someone can easily input some JS in your site and you can be defaced in no time.
Have a look at this Sanitizing user input before adding it to the DOM in Javascript
Last but not the least. Stop exposing the functions in the Global level while writing JavaScript. Stop creating global variables and functions and rather use closures.
(function(){
var a =10;
var b = 20;
function add(msg){
console.log(msg)
return a+b;
}
add("I am calling from Inside the self executing function");
})();
add("I am calling from outside the self executing function");
Have a look at the code above and how it protects that add() method to be called from outside.
Hope this answers your questions.
Yes, on stateless scenarios you should send some client identification like a token and verify on the server. Don't worry about the performance :)
You could take a look to JWT: https://jwt.io/
I'm in trouble. I'm trying to do something which can appear easy but I don't manage to do it.
Here is the situation :
I have 3 different html pages :
The first one called index.html is my main page with a button to lauch a test in AJAX (I'm gonna talk about it after).
The second one corresponds to a redirection to the third page.
The third one has data.
What I wanna do is :
Click on "test" button on the first page and then start an AJAX request on the second one to reach data from the third one (with the redirection) to print it in the first.
I mean the first page calls the second one in AJAX, but the just to redirect on a specific third page. Depending on the third page which is called, data returned to the first page will change.
Do you think it's possible to find a solution to this problem in Javascript ? I hope I have been clear enough.
Thank you in advance for answer.
What you are describing doesn't really make sense. There are methods of redirection that AJAX follows (an HTTP 301 code, for example). However, what you are describing is not that sort of redirect. You are describing Javascript code that, when run, will redirect the browser elsewhere.
However, you are not loading that Javascript with the browser, you are downloading the page via AJAX. Once it is downloaded, you will have the text that represents that page, but in order to find out where it would redirect to when run, you would either have to run it and somehow capture the redirect value (not recommended), or parse it yourself (also not recommended).
There are other options that could work, depending on what you are trying to accomplish:
The server could return an HTTP redirect code when the second page is requested
The second page could instead be a text or JSON file containing a URL, which the first page could read, then request data from that URL.
If there is logic in the second page that determines where the redirect goes, it could be moved to the first page
You could have the second page employ server-side scripting (PHP, etc) to determine what data should be returned and return it directly to the first page
What would be the better/best solution? previously all my markup were all initialized in an html file,
index.php:
//login block
<div id="login">
form ...
</div>
so whenever I logged in, I have to remove/hide these login block by using $.ajax to check if there's an existing session then hide the whole login markup ( .hide() ) and show a different markup for logged in users.
The problem with this is that, it waits for the whole document to load before it executes the script, so the unintended/hidden markup will show and then vanished quickly upon page load.
I also tried putting the markup inline inside javascript, but I think it violates the "Unobtrusive" idea in js.
e.g.
var markup_arr = [
'<h4>Login</h4>',
'<form></form>'
];
var markup = markup_arr.join('');
So I end up with this
Current solution: separate html file and loading it using jQuery's $.load()
What are you using, which are the best practices and which one loads fast? Or are there any better solution out there that you can suggest? Thanks.
EDIT:
These are all javascript/ajax processes, so I'm not looking for a server side solution(include,require_once)
There's no correct answer to this. My view is you want to deliver the minimum amount of data to your users, in the minimum number of requests. It's all about finding the right balance. Depending on your users the balance will change to.
For me, I'd prefer sending two files that are 5kB each, rather than four that are 2kB. You're sending more data, but as there are less requests it should be just as quick. I'd think that delivering it as part of the Javascript might be best. Note it doesn't necessarily need to be the same file, although I'd deliver it as one - have a simple (PHP etc) script which joins the code file and the data file into one, then passes it out
The other thing I'd make sure is that you're caching everything as best you can. Having a slightly bigger file isn't generally an issue if you only have to download it once and it caches for a year. If your users are downloading a larger file every day, or worse, every page view it becomes an issue.
What I would do is check server side if the session exists, and include your separate "html" (php/rb/py/asp/whatever really) file if the session exist, and the login form if not. When the user logs, ajax would answer the same "html" file. (if I understand your problem correctly, and the login form is a single line in the page header).
If JavaScript is disabled what's a way of linking to the previous document in the session history?
Can PHP be used to simply link to the REFERRER or is there a better alternative?
Edit: Further to this, can previous post variables be retained?
You're really mixing the idea of previous document in client session history vs. server session history.
Since Javascript is client-side, executing a history.back() renders the control to the browser, which then decides which page was last in the history (keeping in mind that the last page may not be a page within your domain). When you're using server-side PHP, the HTTP header referrer is whatever the browser supplied to you. If your server-side URI wasn't called as a result of an explicit click on a link, form GET/POST, etc. , your script probably won't get a referrer header value.
If you only want to capture the referrer within your site's domain, you can start maintaining a breadcrumb trail server-side (in the user's session). eg: $_SESSION['breadcrumbs'] = array( 'page1', 'page2', ... )
POST variables can be persisted in the SESSION too though I've never seen a good reason to do so. If you're trying to return an error message for a form and expect to get back the POST, you shouldn't be saving the state of the original POST.