Post data again after authorization - php

I have a CakePHP application where there is a form that is visible to visitors who haven't even logged in. If they submit the form without logging in, they are redirected to a login page from where I want them to go back to the add controller with all the submitted form data.
Is this possible? If yes, how?

Off the top of my head, something like this should work:
function beforeFilter() {
// be sure to do this before any Auth or security checks
if ($this->RequestHandler->isPost() && $this->data) {
$this->Session->write('last_post_data', $this->data);
}
}
function add() {
if (!$this->data && $this->Session->check('last_post_data')) {
$this->data = $this->Session->read('last_post_data');
}
$this->Session->delete('last_post_data');
if ($this->data) {
// save as usual
}
}
Just make sure to properly dispose of the POST data saved in the Session, or it could wreck havoc later on. In fact, you should not only save the data in the Session, but also which action it was intended for ($this->action and $this->controller) and check for that before reusing the data in the action. Possibly also put a very tight timeout on the data.

I think you will have to use the SESSION or do something like to this:
<input type="text" name="user" value="<?php echo $_POST['user'];?>">
<input type="password" name="password" value="<?php echo $_POST['password'];?>">
Note that above i have used the POST array but you can also use Cake's array for this if there is one.

Assign a session to the users before logging in, and store the data in the session. That session might have an attribute loggedIn which is default false.
Don't store the session data in a cookie though, keep it server side :)

Put session_start(); on the top of the form, and login page. On the form's action page set session variables:
$_SESSION['name'] = $_POST['name'];
$_SESSION['address'] = $_POST['address'];
etc...
On the form page, set values by saying the following:
<input type="text" name="name" id="name" value="<?php echo $_SESSION['name']; ?>" />
<input type="text" name="address" id="address" value="<?php echo $_SESSION['address']; ?>" />
etc...

If you only allow logged in users to access the form, you could also add a periodic AJAX request to the page with the form that keeps the session alive.
window.setInterval(function(){
jQuery.get("/url/to_page_that_does_nothing");
}, 600000);
You could also set it up so that the timer is acticated only when the user starts filling out the form.
Disclaimers: 1) this uses jQuery 2) not as secure as logging in again, but faster/easier to implement.

Related

inject url param into html form

just wanted to find out the safest way to do something so it is not vulnerable.
Say I have a url like www.mysite.com?name=nick
This loads a static html page with a form. One of the forms fields is
<input type="text" id="pName" value="" name="pName" readonly>
What is the best way to get the url param into the value of this input? Basically, I have an app which will be used by several people in different locations. I need a way to identify who is using it, so I thought I could just add their name into the url and then inject this into my form.
Any information appreciated,
UPDATE
Going off the comments, I have added this to the top of index.php
<?php
session_start();
if (!isset($_SESSION['pName'])) {
$_SESSION['pName'] = $_GET['pName'];
}
?>
And then the input is like so
<input type="text" id="pName" value="<?php $_SESSION['pName'] ?>" name="pName" readonly>
Would this be acceptable?
Use session and put $_SESSION['YourSessionVariable'] into textbox.
<?php
$valueForTextbox = '';
if(isset($_POST['yourSubmitName'])){
$_SESSION['pName'] = $valueForTextbox = $_POST['pName'];
}else if(isset($_SESSION['pName'])){
$valueForTextbox = $_SESSION['pName'];
}
?>
<input type="text" id="pName" value="<?php echo $valueForTextbox;?>" name="pName" readonly>
Why ?
What if I change url GET parameter ? It will be security issue as well..
Also if I have to maintain that data in many pages(say a wizard to complete) And if I delete some parameters from URL, it will create issue.
Query string will be unnecessarily big with GET parameters which can easily saved in sessions.
Edit :
When form is Not submitted. Fetch value from Database rather than taking from Query string. And after form submit put value in SESSION. Form posting will keep updating value for that session variable.
If the user is to be defined in the URL, you must check on the server, if the user is authorized.
Since you need to have a safe method to identify the authorized user, the identification happens before the form is called, for example through login.
On login you store the user's name on the server, usually in the session, then you forward him to the form.
If a user tries to call the form for another, not identified user, you will realize this on the server. The form comes back, but the user does not match the username stored in the session.
Now, as you already have the user in the session, the question arises, if you really need the user in the url. Reasons for that could be, that you want more than one form open at a time, or you have authorized access to the form of other users (for example admin access).

PHP - Destroying Sessions properly on un-submitted form pages?

If I have a php contact form with session_start() at the top, I know this creates a session. But what if the user doesn't fill out the form and instead navigates to a different page?
Do I still need to use session_destroy since I only want a session created when a user submits a php form via my contact page?
Thanks.
UPDATE: For a better idea on my form without posting lengthy code.
contact-form.html
<?php session_start(); ?>
<?php $fname = isset($_SESSION['fname'] ) ? $_SESSION['fname'] : NULL ; ?>
<form method="post" action="http://www.mysite.com/form-process.php">
<input value="<?php echo $fname ?>" type="text" id="fname" name="fname" />
<input type="submit" value="Submit Request" />
</form>
form-process.php
<?php
session_start();
$_SESSION['fname'] = $_POST['fname'];
$user = "John" ;
session_write_close();
if ($_SESSION['fname'] != $user) {
header('Location: http://www.mysite.com/contact-form.html');
}
else {
$_SESSION = array();
session_destroy();
header('Location: http://www.mysite.com/thankyou.html');
}
?>
The overhead of creating a session is miniscule, there's no real reason you'd need to session_destroy() though you could put the session_start() in the block that detects post rather than at the top of the script if you only want to use the session when the user posts.
If you only want a session created when the user submits certain form, just do it as you describe. It's not mandatory to put session_start() on every page of the site and it doesn't need to be the first line in the file (it just needs to be able to generate a cookie, thus it needs to be before any output).
// contact-form.php
if( $_SERVER['REQUEST_METHOD']=='POST' ){
session_start();
// ...
}
The stateless nature of HTTP makes it impossible to actively remove a session if the user hasn't completed certain task. But if you don't load session on other parts of the site, the session file will be removed on next garbage collection after its expiration time, even if the user is still browsing your site. Other than that, a session is just a tiny text file lying harmlessly on a temporary directory.

php - process and validate form - correct process

In PHP I want to use a script held in a separate file to process a form and validate it. If there are errors I want the form to display the errors and original values for the user to change.
At the moment the validation script is on the same page as the form and all works ok. However I would like this away from the form and send the form variables to the script using the 'action' in the form.
If I do this though, how can I then go back to the form with error messages and original values — do I simply use $_POST in the script and a header location? or is there a better method.
If the form validates okay I'll then go to a separate page (using a header).
Can anyone help me understand the process/logic I should be trying to achieve and the function s to past variables between the pages ($_GET?)
If you want to track variables across multiple pages, it might be feasible to investigate sessions. You can assign variables from $_GET or $_POST to the session, and they will be accessible across pages.
I think what you are looking for is a framework called Model-View-Controller (MVC). In your case, your form is the "view" and script to process data is "controller" then the controller has the option what to show to the user (view) which is your form with error message or some other page with success message. But MVC is a bit more complex than that. If you want to study MVC, read some articles and choose MVC framework to use like CakePHP, CodeIgniter, Zend framework et cetera.
If you are studying basics of PHP, you might not want to start using a framework, in that case, you can do something like this (login sample):
login.php
<?php
$error = "";
$username = "";
$password = "";
//POST method used. The user is trying to login
if(isset($_POST))
{
$username = $_POST["username"];
$password = $_POST["password"];
//process login here
//check database
if($success == true)
{
header( 'Location: home.php' ) ;
}
else
{
include "login-view.php";
$error = "Either username or password is incorrect.";
}
}
else //GET method used. The user visits the login page
{
include "login-view.php";
}
?>
login-view.php
<p><?php echo $error; ?></p>
<form method="post" action="login.php">
<input type="text" name="username" value="<?php echo $username ?>" />
<input type="password" name="password" />
<input type="submit" value="send" />
</form>
The code above goes like this:
1) The user visit the login page. login.php will detect that the method used is GET -- cliocking a link, opening a bookmark or typing URL to address bar. login.php then will include login-view which contains the form.
2) The user type his username and password and click submit button. login.php will detect that the request is POST, then validate username and password, provide error message if necessary. If valid, then redirect to home page, if not, include login-view.php (form), this time with error message and previously typed username.

Storing form data with PHP Session

I am working on an HTML form whose data would be saved on a failed submit, or page refresh.
We are using a PHP Session to store this data, and we post the elements back when needed.
The issue is that it's not working. We need the form data to be preserved on a submit with errors, or page refresh. Currently on a failed submit, or page refresh, there is no data being stored in the session.
I'm fairly new to PHP, and most of this code is not mine, so go easy on me.
The PHP Sumbit code being used is:
Software: PHPMailer - PHP email class
Version: 5.0.2
Contact: via sourceforge.net support pages (also www.codeworxtech.com)
Info: http://phpmailer.sourceforge.net
Support: http://sourceforge.net/projects/phpmailer/
SESSION:
<?php
session_name("fancyform");
session_start();
$str='';
if($_SESSION['errStr'])
{
$str='<div class="error">'.$_SESSION['errStr'].'</div>';
unset($_SESSION['errStr']);
}
$success='';
if($_SESSION['sent'])
{
$success='<div class="message-sent"><p>Message was sent successfully. Thank you! </p></div>';
$css='<style type="text/css">#contact-form{display:none;}</style>';
unset($_SESSION['sent']);
}
?>
FORM:
<form id="contact-form" name="contact-form" method="post" action="submit.php">
<p><input type="text" name="name" id="name" class="validate[required]" placeholder="Enter your first and last name here" value="<?=$_SESSION['post']['name']?>" /></p>
<p><input type="text" name="email" id="email" class="validate[required,custom[email]]" placeholder="Enter your email address here" value="<?=$_SESSION['post']['email']?>" /></p>
<p><input type="text" name="phone" id="phone" placeholder="Enter your phone number here" value="<?=$_SESSION['post']['phone']?>" /></p>
<p>
<select name="subject" id="subject">
<option>What event service are you primarily interested in?</option>
<option>Event Creation</option>
<option>Project Management</option>
<option>Promotion</option>
</select>
</p>
<textarea name="message" id="message" class="validate[required]" placeholder="Please include some details about your project or event..."><?=$_SESSION['post']['message']?> </textarea>
<input type="submit" value="" />
</form>
You are outputting $_SESSION['post']['form_element'] to your template but in the above PHP code there is no mention of setting that data. For this to work, you would have to loop through the $_POST array and assign each key pair to $_SESSION['post']
At that point you should be able to access the previously submitted form data from the session just as you have coded above.
add this to your submit.php:
session_start();
foreach ($_POST AS $key => $value) {
$_SESSION['post'][$key] = $value;
}
This will move all the data from $_POST to $_SESSION['post'] for future use in the template, and should be all you need to get it working.
HTTP is stateless, and data that is not submitted will not remain unless you use a client-side approach (webstorage, etc).
You need to parse the post variables and add them to the session super global, right now you are referencing $_SESSION['post']['phone'] which won't work as you expect.
// Assuming same file, this is session section
if (array_key_exists('submit', $_REQUEST)) {
if (array_key_exists('phone', $_REQUEST)) {
$_SESSION['phone'] = $_REQUEST['phone'];
}
}
// Form section
<?php $phone = (array_key_exists('phone', $_SESSION)) ? $_SESSION['phone'] : null;?>
<input type="text" name="phone" id="phone" placeholder="Enter your phone number here" value="<?php echo $phone ?>" />
Either you didn't include the code for submit.php or, if you did, the problem is clear: you're never setting the session values. In order to do that, you'd use
session_start();
// etc...
$_SESSION['post']['name'] = $_POST['name'];
$_SESSION['post']['email'] = $_POST['email'];
$_SESSION['post']['phone'] = $_POST['phone'];
// etc...
on submit.php and then the form page (presumably another page?) could then check if those values have been set
.. value="<?php if (isset($_SESSION['post']['name'])) echo $_SESSION['post']['name']; ?>" ..
I may be wrong, but I think you need to get the posted values from the form by using something like
if ($_POST['errStr']) {
$_SESSION['errStr'] = $POST['errStr'];
}
If i'm right its the way you're trying to access the variables after posting the form
If you look at the METHOD attribute of the form it set as post, so this should return the values you want to pass accross pages.
Maybe this isn't what you were asking though, i'm a little unclear what part the problem is with, i'm assuming its taking values from the form and getting them out on the next page.
If you want to do it when the page is refreshed/exited you'd probably need to use some javascript client side to try and catch it before the action happens.
Don't know if this is possible. PHP wont help you for that as its executed server-side, and the client wont submit anything (useful) to the server when they exit/reload, only the command to perform the action.
This'll probably require using javascript listeners, eg window.onclose (although apparently that doesn't work for safari or firefox 2), and within that an ajax xmlhttprequest to send the data to your server.
For failed submit (ie capture form with invalid data in?) its almost the same case as form that submit worked on. Just re-check the data on the other side when you're processing it.

pass value from page to another in PHP

I am sending login status = fail, back to my login page.Here is my code-
header("location:index.php?login=fail");
but that is sending through URL like-
http://localhost/303/index.php?login=fail
is there any way to pass value without showing in URL? And how to get this value on the second page?
You are passing that value via a GET request, which is why it appears in the URL. In order to pass a value without showing it in the URL, you want to pass it via a POST request.
In order to do this you aren't going to want to "return" the value to your login page. Instead, whatever php form is handling the process of logging in the user after they click the "login" button, will decide what to show the user.
In PHP post variables can be accessed by the global $_POST object -
$_POST['username'];
Would get the value with the name "username" that you passed via POST:
<form method="post" action="checkLogin.php">
Username:
<input type="text" name="username" maxlength="25" />
Password:
</td><td><input type="password" name="password" />
<input type="submit" name="submit" value="Login">
</form>
In order to dynamically save and show errors to the user, you can store them in the session, for example have a file called "errors.php"
<?php
if (isset($_SESSION['errors']))
{
echo $_SESSION['errors'];
}
unset($_SESSION['errors'])
?>
And in your php that checks the login, do:
session_start();
$_SESSION['errors'] = "Invalid username or password.";
Then redirect to your login page (don't pass any variables) and on your form always have this field:
<?php include("errors.php"); ?>
If you didn't have any errors, it won't show anything and the login page will look normal.
Note: In any php form that you use a session_start(), it HAS TO BE THE FIRST THING in the form.
Other ways are to use session or hidden fields but you what you are doing is fine for the purpose. You can later retrieve the value like this:
if ($_GET['login'] === 'fail')
{
// failed.......
}
there are several ways to accomplish your task
Modern AJAX way. Form being sent using AJAX. No page reload until password is correct. Errors shown in place. Requres javascript.
Post/Redirect/Get pattern. Form being sent using regular POST. No redirect on errors, shown in place.
sessions, when we store an error in the session

Categories