Will bad things happen if I control the content of $_POST? - php

In my days of writing web applications, I'm missing a simple way for a PHP script to direct to another PHP script while passing along data without using the URL
Browsers can pass data invisibly to a PHP script using the $_POST array. So I'm devising a script that will dump the contents of $_SESSION["POST"] into the $_POST array to mimic the passing of post data, then clears $_SESSION["POST"].
For instance, a page X contains a login form. Page X directs to page Y to validate the data. Page Y discovers that the login information is incorrect, and redirects back to page X - which now displays the error message "Login information incorrect" from $_POST.
Am I crazy for missing this feature? Is there some other method of doing this easily that I'm missing?
Please respond with anything that can be helpful.

You could use the session. On page X, you'd put the data into the session. On page Y, you'd validate the data and handle the redirect. You can put your error message into the session too.
The session persists between requests, so it's the perfect place to store that kind of data.
EDIT
OK, I'd do things with session variables, but if you want to avoid that you do have a few other options I can think of besides posting:
You can use files on the server (such as temporary files). Use the user's session key to identify which file is theirs, and you can read and write whatever data you care to it.
You can put the data in a database. That would work too.
Of course neither of those is a true post. If you want a true post, you have another two options.
First, you can return the data to the page in a hidden form, and use JavaScript to trigger a POST. This is simple to do, but it requires the data to pass through the browser. This means you'd have to take care that a user didn't change the data, and the user would have to have JavaScript on. You can checksum the data to ensure it isn't modified, but the JavaScript problem is unsolvable.
Another way to do it would be to take the user out of the equation entirely. When the user submits to page A, page A could make a POST to page B, check the response, and then redirect the user to the proper place. This would be just like if you had to make a JSON or SOAP call to a 3rd party service, except you control that service. It's been a little while, but I believe that HttpRequest is the class to use to do this.
It would be ideal if that URL you check with returns a simple answer ("true", "false", "yes", "no", "good", "bad", whatever), but as long as you can tell by the response whether they were successful or not, you can do it.
Now I should note that I'd agree with mvds, this sounds like a function that should be included in page A so that it can do all the work but the code can be shared with other pages. Having page A post to page B and then redirect to A or C seems unnecessarily complex. Page A can easily accomplish all this. I read your comment on his answer, but it seems there should be another way to accomplish this.

Abstract the performed actions to functions and/or classes, and the need for such kludges will vanish. Concrete: both page X and Y could call the same function to validate the posted login data.
Page X redirecting to page Y to do validation means handing back control to the client, while you could (and should) validate the data right away.

Related

Data from the exact form

I have been googling a lot but i am still without an answer so i decided to ask this question here:
Is there a way in PHP how to check that the data i am receiving in some script are from the specific form on the page? I am asking because everyone can see the name of the script i am using for saving the data to my database, so if somebody is able to find out the whole URL, he is also able to send some fake data to the script and i need a condition, that the saving process is triggered only when the data comes from the proper form on my page.
I am using jQuery to call AJAX function, so basically if i click on the button "send", the $.POST() method is triggered to call the script for saving the data.
Thanks,
Tomas
Use tokens to check if request is valid
You could always add some kind of security token when submitting data:
Tokens can be easily extended for many different uses and covers wide area when it comes to checking if some request is valid, for example you could let your non critical forms open for public, ask users to get their secret keys from some page (forcing them to open that page) and then use those keys to identify them when submitting data.
Of course all of this can be completely transparent to user as you could give keys from front page via cookies (or session cookies, it does not matter here, no more or less security as server keys should change after use and invalidate within specified time or when user's identity changes).In this example of use, only user that opened front page can submit data to server.
Another case is when cookies is given away at same page which contains form for submitting data to server. Every user that open page will have their keys to submit data straight away, however if someone tries to make request from outside it will fail.
See OWASP Cross Site Request Forgery
and codinghorror.com Blog CSRF and You
Only with AJAX?
Here is my answer to another question, this answer covers different methods for inserting additional data to ajax request: Liftweb: create a form that can be submitted both traditionally and with AJAX (take a closer look at
$.ajax({
...
data: /* here */
...
Currently I am using tokens this way:
Form used to submit
This hidden input can be added to form, it is not requirement as you can use methods described earlier at another answer.
<input type="hidden" name="formid" value="<?php echo generateFormId(); ?>" />
Function generateFormId()
Simply generate random string and save it to session storage
function generateFormId() {
// Insert some random string: base64_encode is not really needed here
$_SESSION['FORM_ID'] = 'FormID'.base64_encode( uniqid() );
// If you want longer random string mixed with some other method just add them:
//$_SESSION['FORM_ID'] = 'FormID'.base64_encode( crypt(uniqid()).uniqid('',true) );
return $_SESSION['FORM_ID'];
}
Processing submitted form data
if (!isset($_SESSION['FORM_ID']) || $_SESSION['FORM_ID'] != $_POST['formid']) {
// You can use these if you want to redirect user back to form, preserving values:
//$_SESSION['RELOAD_POST'] = $_POST;
//$_SESSION['RELOAD_ID'] = uniqid('re');
echo 'Form expired, cannot submit values.';
//echo 'Go back and try again';
exit(1); // <== Stop processing in case of error.
}
If you need to check which form is submitting data
Then you could just add prefix when generating id's and check for that prefix when processing form data.
This is case when one php script deals with many different forms.
Remember that only ultimate answer to prevent evil users is to pull off all wires from your server...
This is an interesting topic, but you are missing an important point: A spam robot / bad user could also bomb your database by using that specific form page (!).
So, the question is not how to check if the request comes from that page or not, the question is how to check if he's a regular user or a robot/spammer/bot.
Do it with a captcha, like http://www.recaptcha.net
In case i slightly misunderstood the question: If you want to be sure that the request comes from a "real" user you will have to work with a login system / user system and check for users id / password (via db or sessions) every time you want to do a db request.
You can verify that the page is being requested via AJAX with checking against this:
strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest'
You could also check the HTTP_REFERER.
But it sounds like you're trying to protect a page that processes vulnerable data. This requires more than just the two things above. I'd recommend googling 'CSRF Forgery' to get more information on this.
These are something that you should take a look at.
Capthcas.
Referer check.
Use POST than GET. [Still Curl can automate it.]

How can I pass variables in PHP from the same page?....logical thinking puzzle

so I've hit a potential problem in my site....it's a post-based system, with the posts being in text files. Uses some Javascript and a lot of PHP.
When you make a submission on the form on the homepage, you are sent to a page where data is posted and processed, but you don't see it because you get redirected back. Then the homepage is changed based on what the post you made says. All that was working fine.
But now I'm trying to add a new feature that modifies the post you made, based on a button you hit which submits a hidden form using javascript, and sends to another process and redirect page you don't see, and it works fine until the block that I realized today. I don't know how to specify that the post being altered is the right one.
I anticipate a good amount of users of this site, so my concern is what if user X makes a post while user Y is making a post, and the post of user X becomes the top post, so user Y's options actually change user X's post.....
I was thinking of adding to the main processing page (the one that happens when you first submit) a COOKIE or something that would make note of the number of the line that post will become, by counting the number of the lines in that file at the time and adding 1 to it. Then checking it against the user's number (each user has a number) to see if it's that user's most recent post....but the problem is I don't know how I would pass that value around to be read in the next page.
Setting a COOKIE is out I think because the page both redirects, AND reads and writes to files. The only output to the page though are currently var_dumps.
POST/GET is out because to my knowledge the user would have to do SOMETHING to submit it, and the user's not even going to see the page.
Writing to a file would be messy if lots of users are trying to get their own data.
I think what I may be looking for is SESSION variables...but I don't know anything about those except that they're used to login to pages, and this site has no login.
To make things more fun, when a user posts the same content within a minute of another user, the first user's post is replaced and it gets a little +1 next to it...which makes it harder to check it against the user's number....
AND in the end I'm trying to use AJAX (which I dont know yet) to make the updates in real-time...now THAT is going to suck. But for now I'm worried about my static little site.
Baby steps.
Any ideas how to go about this??
Use Session variables, just as you have alluded. They aren't just used by login pages, they are used by everything. Sessions are the equivalent of server-side cookies / server-side storage, so you don't have to worry (as much) about your users tampering with them.
If you want to make life more difficult for yourself, you can json encode your variables and store them as an object in a database or even flat text file. But really, read up on sessions.
All you need to know is session_start(); before anything else then $_SESSION['var']=$yourvar; to save data and $_SESSION['yourvar'] to retrieve it later (such as on another page).

Should I go with AJAX and JQuery's complexity and speed or GET's simplicity?

If a user tries to log in and the login fails the page should display an error message to the user. There are two main ways I see to do this: use a form action on the HTML page and in the php script if the login information is incorrect redirect with header to the login page with a $_GET value like loginfailed. The login page would check for this value and if it exists it would display the error.
The second way I see to do this is not use a form at all and instead use JQuery to capture the submit button press and use AJAX to determine if an error occurs. The php file would echo back a status and the javascript file would interpret it and if it was loginfailed, it would use JQuery to append the error message on to the page.
Now I will go over what I feel the pros and cons of each method are.
Method 1 Pros:
Very simplistic with no need for JQuery, Javascript, and AJAX.
The error status is displayed within the URL as well.
Method 1 Cons:
Since there is a header call, a redirect is necessary. Also, the login page must be reloaded. It is a small page but it is a reload nonetheless.
The status message is displayed in the URL. This means that users can type in status messages in to the URL and receive error messages on the page for errors that did not actually occur. Is this a problem? Maybe. Maybe not.
Method 2 Pros:
Since it is using AJAX, there is no need to load another URL and thus, no extra page is loaded.
This method uses JQuery to update the page with the error message so no redirect is necessary.
The error status is not displayed in the URL.
Method 2 Cons:
Much more complex than the first solution.
An external javascript file is needed and must be loaded every time the login page is accessed regardless of whether or not it is used.
The default behavior of the submit button is overridden and annulled. Its only behavior comes from its interaction with the javascript file.
What would SO do? I would like to stay away from answers such as "it depends on how much traffic your site would have" if that would be at all possible.
Always use the simplest solution possible until/unless there's a very good reason to do otherwise. It's better to finish something that's maybe (and maybe not) less than ideal than to deliver something gold-plated eventually, maybe.
Also, I generally prefer to follow a progressive enhancement strategy, such that everything works without Javascript, and then add Javascript to make it work in an improved manner. This has the added benefit of being functional, even when/where Javascript is disabled.
I think you fail to grasp the matter.
Login is not something self-sufficient. It is used to change state of the site. But with no reload it will not be changed. So, page reload is required anyway. or user will have to do it manually to get access to the authorized section.
Is login the only site feature that uses JQuery/AJAX? If not - why you're worrying about loading this library once, when most likely it will be loaded at every page?
There are still clients with JS disabled, for various reasons. A good web application will always let these clients in, even at cost of less functionality.
The latter is the main question, most important one. Why to choose between two? Why not to use both? - one for compatibility and another for usability?
So, I'd suggest to create basic functionality using GET to pass come codes, not messages.
And optionally improve it with some AJAX bells and whistles but with JS-based reload on succesful login anyway

proper way to craft an ajax call with php and auth

From a security standpoint, can someone give me a step-by-step (but very simple) path to securing an ajax call when logged in to PHP?
Example:
on the php page, there is a session id given to the logged in user.
the session id is placed dynamically into the javascript before pushing the page to the client.
the client clicks a "submit" button which sends the data (including the session id) back to the php processing page.
the php processing page confirms the session id, performs the task, and sends back data
I'm stuck on how (and whether) the session data should be secured before sending it through an ajax request. I'm not building a bank here, but i'm concerned about so many ajax calls going to "open-ended" php pages that can just accept requests from anywhere (given that sources can be spoofed).
PHP can get the session data without you having to send a session ID via javascript. Just use the $_SESSION variable. If you want to check if a session exists you can just do
if(isset($_SESSION['some_val'))
//do work son.
You'll need to use JavaScript to asynchronously pass user input back to the server, but not to keep track of a session.
Don't send your session data with javascript.
You don't need to (in most cases).
Just post the data with javascript and let PHP retrieve the session data from... the session.
Depends on how you setup your session data.
One simple example would be you have a session called username.
When PHP gets the request from javascript you can do: $_SESSION['username'] to retrieve the sessiondata.
This is a very simple example just to show how it can be done.
As noted above, you don't need to send any session identifiers out with your javascript, to the server an AJAX request is the same as any other request and it will know your session just fine. So basically, just don't worry about it, it's already taken care of.
It's another part of your question that worries me.
i'm concerned about so many ajax calls going to "open-ended" php pages that can just accept requests from anywhere
It worries me too; you shouldn't have any "open-ended" PHP pages hanging around at all. Every public .php script should have authentication and authorisation done. The easiest and most maintainable way to achieve this, IMHO, is to have a single controller script (e.g. index.php) that does authentication and authorisation then sends the request to an appropriate controller. Aside from this controller, all other scripts should be outside the document root so that they cannot be called directly.
This means that you only ever have to worry about authentication and authorisation in one place; if you need to change it, it only changes in one place. It means you don't need to worry about accidentally leaving some executable stuff in some library PHP file that's not meant to be called directly. It means you don't need to shag around with mod_rewrite rules trying to protect .php files that shouldn't be in the doc root at all.

Prevent Back button from showing POST confirmation alert

I have an application that supplies long list of parameters to a web page, so I have to use POST instead of GET. The problem is that when page gets displayed and user clicks the Back button, Firefox shows up a warning:
To display this page, Firefox must send information that will repeat any action (such as a search or order confirmation) that was performed earlier.
Since application is built in such way that going Back is a quite common operation, this is really annoying to end users.
Basically, I would like to do it the way this page does:
http://www.pikanya.net/testcache/
Enter something, submit, and click Back button. No warning, it just goes back.
Googling I found out that this might be a bug in Firefox 3, but I'd like to somehow get this behavior even after they "fix" it.
I guess it could be doable with some HTTP headers, but which exactly?
See my golden rule of web programming here:
Stop data inserting into a database twice
It says: “Never ever respond with a body to a POST-request. Always do the work, and then respond with a Location: header to redirect to the updated page so that browser requests it with GET”
If browser ever asks user about re-POST, your web app is broken. User should not ever see this question.
One way round it is to redirect the POST to a page which redirects to a GET - see Post/Redirect/Get on wikipedia.
Say your POST is 4K of form data. Presumably your server does something with that data rather than just displaying it once and throwing it away, such as saving it in a database. Keep doing that, or if it's a huge search form create a temporary copy of it in a database that gets purged after a few days or on a LRU basis when a space limit is used. Now create a representation of the data which can be accessed using GET. If it's temporary, generate an ID for it and use that as the URL; if it's a permanent set of data it probably has an ID or something that can be used for the URL. At the worst case, an algorithm like tiny url uses can collapse a big URL to a much smaller one. Redirect the POST to GET the representation of the data.
As a historical note, this technique was established practice in 1995.
One way to avoid that warning/behavior is to do the POST via AJAX, then send the user to another page (or not) separately.
I have been using the Session variable to help in this situation. Here's the method I use that has been working great for me for years:
//If there's something in the POST, move it to the session and then redirect right back to where we are
if ($_POST) {
$_SESSION['POST']=$_POST;
redirect($_SERVER["REQUEST_URI"]);
}
//If there's something in the SESSION POST, move it back to the POST and clear the SESSION POST
if ($_SESSION['POST']) {
$_POST=$_SESSION['POST'];
unset($_SESSION['POST']);
}
Technically you don't even need to put it back into a variable called $_POST. But it helps me in keeping track of what data has come from where.
I have an application that supplies long list of parameters to a web page, so I have to use POST instead of GET. The problem is that when page gets displayed and user clicks the Back button, Firefox shows up a warning:
Your reasoning is wrong. If the request is without side effects, it should be GET. If it has side effects, it should be POST. The choice should not be based on the number of parameters you need to pass.
As another solution you may stop to use redirecting at all.
You may process and render the processing result at once with no POST confirmation alert. You should just manipulate the browser history object:
history.replaceState("", "", "/the/result/page")
See full or short answers

Categories