Solved

Passing form params twice

Posted on 2010-11-09
15
543 Views
Last Modified: 2012-05-10
Hi Experts,

I'm wanting to change a couple of php scripts (which someone else wrote) to add validation of form variables (name & email).  Currently the scripts don't validate the form fields at all, and it works like this (in summarised pseudo code):

    script1.php:
        Display web page with form
        form action=script2.php with method=post

    script2.php:
        Store params in database
        etc.

I'm considering implementing the validation like this:

    script1.php:
        If submit param from script1.php received
            Do validation on received param fields (name & email)
            If errors found
                Put messages in errmsg variable
            Else
                Call script2.php passing fields with method=post
        Display web page with form, including errmsg (from above) if any.
        form action=script1.php (NOT script2.php) with method=post

    script2.php:
        Store params in database
        etc.

Q1: How can I code this in php?:
    Call script2.php passing fields with method=post
    I know how to do this using a form, but I'm not using a form at this point, I'm just passing received parameters on to the next script.  I'd rather not use JavaScript here, if possible.

Q2: Does my the above pseudo code look like a good way of implementing the validation?  Any other suggestions?

Thanks.
tel2
0
Comment
Question by:tel2
  • 5
  • 4
  • 3
  • +1
15 Comments
 
LVL 31

Expert Comment

by:Marco Gasi
ID: 34099525
Have you considered to validate fields in script 2? You could use sacript 1 to display form and pass data to the script 2. Script 2 get data, validate them and if validation process return true then data are inserted in db else script2 can redirect to script 1.

Cheers
0
 
LVL 20

Accepted Solution

by:
Mark Brady earned 225 total points
ID: 34099897
I always validate with simple javascript. It is fast and easy and before it submits any data to the php script, it validates all fields and if any errors it can display them right there on the form without the page refreshing. If you do not want to use javascript then I would use just one script to both display the form, validate the posted results (form post back to it'self) and if everything ok submits results to database. You don't need two scripts to do this only one. Here is the layout.

<?php // sample.php
include("connection_script.php"); // include a connection script if you have one

$form = "<form method = \"POST\">
Name <input type=\"text\" name=\"name\" value=\"\"><br />
Email <input type=\"text\" name=\"email\" value=\"\"><br />
<input type=\"submit\" value=\"Submit\"></form>";

$name = $_POST['name'];
$email = $_POST['email'];

// Do some validation with the posted data here for eg:
if($name != "" && $email != ""){
mysql_query("INSERT INTO users (username,email) VALUES ('$name','$email')")or die(mysql_error());
header("location: thanks.html"); // or some other URL after successful form sent
}else{
echo $form;
}
?>

Obviously that is a very basic example but you can see how by using <form> with no "action" it will send data to it'self. Secondly, you put the form in a php variable but only display it if both $name and $email have values in them. The only way to get values is a isers needs to submit the form. Get it?
Pretty simple. Not the best way of doing it but it will certainly work including the database entry part with that simple IF statement.
0
 
LVL 12

Author Comment

by:tel2
ID: 34100442
Thanks marqusG,

Yes, I did consider that, but it still leaves me with the same question (Q1) of how to pass those fields back to script1.php if there were validation errors.  I want to use the "post" method, as I don't want them to appear in the URL.  I also want to avoid having to put them in a temporary database table if possible (too much hassle and probably not as fast).  How are you proposing the fields be passed back?  If you can give me a bit of sample code, that might help.


Hi elvin66,

Thanks for your efforts.  I'll try to study your answer tomorrow, and get back to you.

Later.
tel2
0
 
LVL 31

Expert Comment

by:Marco Gasi
ID: 34101150
I would write in script1

$errorMsg=array();

if (count($errorMsg)>0){
  echo "Please check following fields for wrong data:<ul>"
  foreach ($errorMsg as $e){
    echo "<li>$e</li>";
  }
  echo "</ul>";
}

//here your form

Script2

global $errorMsg;

//validate email and name code here
if (!validateName){
  $errorMsg[] = "Name";
}
if (!validateEmail){
  $errorMsg[] = "Email";
}
if (count($errorMsg)>0){
  header("Location: script1.php");
}

Now in script1 $errorMsg array is not empty so error message will be diplayed above your form.

Cheers
0
 
LVL 108

Assisted Solution

by:Ray Paseur
Ray Paseur earned 225 total points
ID: 34102277
" Any other suggestions?"  Yes!

Combine script one and script two.   You can combine the code directly, or you might use a variant of include() to bring in the script two code.

    script1.php:
        If submit param from script1.php received
            Do validation on received param fields (name & email)
            If errors found
                Put messages in errmsg variable
            Else
                Store params in database // THE OLD SCRIPT TWO FUNCTIONALITY GOES HERE
            EndIf
        Display web page with form, including errmsg (from above) if any.
        form action=SELF with method=post

HTH, ~Ray
0
 
LVL 20

Expert Comment

by:Mark Brady
ID: 34106692
Pretty much what I suggested to Ray. I would use just the one script in his case. Personally, I always use javascript to validate then use ajax to submit the form to my php script. Very clean very fast and you can show any errors with the page refreshing.

Tel2#    You do realize that you will need to use sessions to keep track of the form data when the page gets refreshed? Otherwise as soon as you try to post messages back the input data will be gone. That's why I use javascript.
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 34106991
I don't think you have to use sessions to keep track of the data.
<?php // RAY_post_error_message_example.php

error_reporting(E_ALL);





// THIS IS THE ACTION SCRIPT - OPTIMISTICALLY INITIALIZE THESE FIELDS

$myField = '';

$errmsg  = '';



// HAS ANYTHING BEEN POSTED?

if (!empty($_POST))

{

    // TEST TO SEE IF THE FIELD CONTAINS THE RIGHT INFORMATION

    $myField = (isset($_POST["myField"])) ? $_POST["myField"] : NULL;

    if (trim(strtoupper($myField)) == 'ABC')

    {

        // THIS IS WHERE WE PROCESS THE GOOD INFORMATION FROM THE FORM

        echo "<br/>Congratulations, you entered ABC";

        echo "<br/><a href=\"{$_SERVER["PHP_SELF"]}\">Try Again?</a>";

        die();

    }

    else

    {

        // THIS IS WHERE WE CREATE - BUT DO NOT PRINT - THE ERROR MESSAGE

        $errmsg = "<br/>Sorry, your entry, '$myField' did not match 'ABC'<br/>";

    }

} // END OF THE ACTION SCRIPT









// THIS IS THE FORM SCRIPT

// IF NOTHING HAS BEEN POSTED, OR IF THERE WAS AN ERROR WE LAND HERE

?>

<form method="post">

<h2>Here is the form</h2>



<!-- IF THERE IS AN ERROR MESSAGE WE PRINT IT HERE -->

<?php echo $errmsg; ?>



Type the three letters 'ABC' here:

<input name="myField" value="<?php echo $myField; ?>" />

<input type="submit" name="My_SUBMIT_Button" value="go" />

</form>

Open in new window

0
3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

 
LVL 20

Expert Comment

by:Mark Brady
ID: 34108400
Ray ~ as soon as the user clicks this link in your code

echo "<br/><a href=\"{$_SERVER["PHP_SELF"]}\">Try Again?</a>";

your $myField value will be blank again because the page has been reloaded. That's what I was saying. Cookies or sessions will keep the form values for as long as he wants that's what I was trying to get across.
0
 
LVL 12

Author Comment

by:tel2
ID: 34108814
Hi elvin,

Thanks for all your suggestions.  Good point re reducing it to 1 script.  I actually tried this kind of thing (re-entrant code, I guess), when I was writing a Perl-based web page a couple of months back.  I thought it was *my* idea!  Disappointing to hear that the planet already knew about it.  In this case, I was wanting to avoid that if possible, because I was after a quick hack, not a significant revamp, but it seems that the revamp might be the easiest tidy solution in this case, if there is no way to pass on these POSTed variables, without:
- Putting them in the URL
- Putting them in a database
- Using a cookie (or is this easy?)
- Forcing a dummy form submit (with method="post") with JavaScript (I assume this is possible)
none of which I want to get into.

A few minor questions of clarification about what you've written:

a) Re JavaScript for validation.  One of the reasons I want to do the validation without JS is, I'm wanting to do reasonable (it still won't be perfect) check on the existence of the email address, and for that, I'll be calling a Perl module called "Mail::CheckUser".  It will tell me that things like "abc@microsoftz.com" is invalid, but "abc@microsoft.com" is valid.  Do you if/know how that can be done in JS?

b) I see you are using escaped code like this:
    Name <input type=\"text\" name=\"name\" value=\"\"><br />
I also see similar escaped code in the code I'm trying to modify.  Is there any good reason why people don't just change the quotes, avoid the escapes, and write this?:
    Name <input type='text' name='name' value=''><br />
It seems to work for me.

c) When you say "You do realize that you will need to use sessions to keep track...".  Does "session" mean "session cookie" in this context (i.e. a cookie that expires after the session)?  (Yes, I see your later comment re "Cookies or sessions...", but I'm not sure if you are describing them as 2 different things or 1.)  I think the code does do something like that, but I'm not yet sure whether I'll have to get into it for my changes.


Hi again marqusG,

Thanks for your code.  A couple of questions for you:

d) How is $errorMsg being passed from script2.php to script1.php?  I am pretty new to PHP, and I see you're using "global", but I don't see how that could do it.  Pls explain.

e) Also, I would want the 2 fields (name & address) to be passed back to script1.php, so they could appear in the fields, so the user could see where he went wrong, and edit them.  How would you be doing that, in the context of your code?


Hi Ray,

Thanks for your pseudo code and code.  Appreciated.  No further questions at this point, your honour.


tel2
0
 
LVL 31

Assisted Solution

by:Marco Gasi
Marco Gasi earned 50 total points
ID: 34109248
I'm sorry tel2. Effectively my memory failed and I was wrong. Keeping separated the two scripts makes sense only if you decide to put in script2 only validate function. Ultimately, the best thing is to join the two script, mantaining functions in a dedicated script. In this sense you can look at snippet below with two script builded this way and that satisfy all your requirements (tracking error and mantaining values in form fields.

Cheers
Script1
<?php
include("global2.php");
if (isset($_POST['submit'])){
    $name=$_POST['name'];
    $pwd=$_POST['password'];
    $values=array("Name"=>$name,"Password"=>$pwd);
    $error=array();
    if (!validateValues($values)){
        var_dump($error);
    }else{
        //update database here
    }
        
}
echo "<form id='' action='" . $_SERVER['PHP_SELF'] . "' method='post'>";
if (isset($_POST['submit']) && $name != ''){
    echo "<input type='text' id='' name='name' value='$name' />";
}else{
    echo "<input type='text' id='' name='name' />";
}
if (isset($_POST['submit']) && $pwd != ''){
    echo "<input type='text' id='' name='password' value='$pwd' />";
}else{
    echo "<input type='text' id='' name='password' />";

}
echo "<input type='submit' id='submit' name='submit' value='Submit' />";
echo "</form>";
?>

Script2
<?php
function validateValues($val){
    global $error;
    foreach ($val as $k=>$v)
    if($v==''){
        $error[]="$k is empty";
    }
    if (count($error)>0){
        return false;
    }
}
?>

Open in new window

0
 
LVL 20

Expert Comment

by:Mark Brady
ID: 34109377
Ok, here is what I meant in a nutshell.

Write one (1) webpage to handle 3 jobs.

1: Display and submit a web form
2: Accept the posted data and validate that data either using javascript, php validation or a pearl script if you want. Whatever the method you use, you will require some sort of validation to stop spammers/robots etc...
3: Process the data, post it to your database and give the user some response via php or javascript to tell them their form was successful or they had errors.

Those 3 jobs can be done in one form. Sessions don't require cookies which are a physical file that is downloaded and stored on your computer. If a user turns off cookies acceptance then you can't pass them a cookie therefore your site will not function reliably. Session variables are stored in memory/ram. The wonderful thing about them is you can use them to display data that was posted on one page, on any page in your website. For eg: when the user posts your form, it will not only get posted and evaluated but the posted values like "username" for eg will be stored in a session variable.

All you need to do on any other page in your website is to add 'session_start()' before any other content and you then have the ability to recall the username. This is useful for eg when you have a site that you have to log into. On each page you need to check if the user is logged in or not before displaying the page to them.

So, in your case, if you follow my example, you will have this as your form (ignore the crudeness of the form)

$form = "<form method = \"POST\">
Name <input type=\"text\" name=\"name\" value=\"".$_SESSION['name']."\"><br />
Email <input type=\"text\" name=\"email\" value=\"".$_SESSION['email']."\"><br />
<input type=\"submit\" value=\"Submit\"></form>";

You can either refer to those variables in the raw form like

echo $_SESSION['name'];

or put them into easier to read variables like this...

$user = $_SESSION['name'];
$email = $_SESSION['email'];

Now you can use $user and $email anywhere on this page BUT as soon as the page is refreshed, the values inside $user and $email are wiped clean. The $_SESSION['name'] however is not wiped.

Now, the reason I escaped the double quotes is a force of habit. I like to use double quotes for php variables and single quotes for inner parts like this:

$name = "My name is ".$_POST['name'];
echo $name;

So I used both single and double quotes. For that reason I had to escape them when I setup the form values in $form. There are many ways to do the same thing, this is just a habit I get into and I likie to try and write clean, good code so other more experienced coders don't tell me off haha.

Anyway, I hope I've explained it enough for you. As for the javascript submitting a form, this is very simple as long as the form has a name. Rather than "submitting" the form though, I tend to use plain old javascript to read each of the values entered by the user, validate each one, create error messages if necessary and if all is good, I then tell ajax to send the posted variables to a php script which places them into the database.
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 34112064
"Sessions don't require cookies" - maybe, or maybe not.  But almost 100% of all session handling requires cookies.  The cookie is usually named PHPSESSID.  You can use Firefox to see the cookies.  Follow the general path Tools => Options => Privacy and look for the link that talks about individual cookies.  Try turning off cookies and see what happens to your sessions.  You want to design programs that will either work correctly or fail gracefully when cookies are turned off.  It should not be too hard to take that into consideration.  Google, Facebook, eBay and many other sites have it figured out.  Clients who do not accept cookies cannot use some of the functionality of these sites.

Suggest you install the code posted at ID:34106991 and run it to see the moving parts.  It performs rudimentary data validation on line 14.  On line 17, the script is completed with success.  This is "where we process the good information from the form" as the comment says.  If you have processed the information (perhaps put it into a data base) you've done the job.  The "Try Again" link will never be fired until the good information has been processed.  You can remove line 18 and the script will still work correctly.  This seemed to confuse Elvin66.  But if you run the script you will see how it works.  Until the data validation is passed successfully, the script will remember the client input and will present a sensible response error message.  As a matter of policy, I do not post untested code without giving you a warning that it is untested.  In the instant case I cannot test the data base portions of your application because I do not have your data base.  But I can and did test the example I posted, so I understand how it works, and where (line 17) you would put your data base interface.

In case you're thinking about putting meaningful data into a cookie, stop right now.  Keep the meaningful information on your server (probably in your data base) and only put a pointer value into the cookie.  Cookies are external data and must be considered to be tainted.  If you have meaningful data in the cookie, you will be unable to validate its contents, and your site will get hacked.  If you want an example of how to set tamper-resistant cookies, please post a question about it.

Javascript validation is nice for your clients, but you still have to do server-side validation.  Like cookies, Javascript is a client-side technology, and it can be hacked, bypassed, etc.  So do your validation on the server side for safety.  Hackers and attackers don't care one iota about how you provided a nicer client experience.  Learn about the PHP functions mysql_real_escape_string() and filter_var() - if you use these right, you will save yourself from a future catastrophe.  This search will also help you understand how to deal safely with external input:
http://lmgtfy.com?q=PHP+Security

The web has many examples of using a single script to provide the Model-View-Controller.  Some of the principles are illustrated in this article.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_2391-PHP-login-logout-and-easy-access-control.html

A really good book that will answer most of your current questions, with good examples and a downloadable code library is available here.  Now in its fourth printing, it has been a part of my professional library since Version One.  I recommend it.
http://www.sitepoint.com/books/phpmysql4/

Best of luck with your project, ~Ray
0
 
LVL 20

Expert Comment

by:Mark Brady
ID: 34115177
Actually you can still use sessions if cookies are disabled but you must pass the variables differently. For eg you could pass information like this:

echo "http://www.yoursite.com/yourphppage.php?PHPSESSID=".session_id();

Then to retrieve it on another page, you could do this:


echo $_GET['PHPSESSID'];

But in a nutshell Ray is right, basically cookies need to be turned on for sessions to work in the usual way.
0
 
LVL 12

Author Comment

by:tel2
ID: 34118142
It seems I've stumbled into a gold mine of experience and willingness to help!
Thanks guys for your awesome responses.  I've learnt stuff from each of you, and will award points in proportion to how much your answer blew me away (multiplied by some random number...).

There are some things you've said which I don't fully understand yet, but I don't yet need to, and I can use the above as a resource for the future.

I've combined the 2 scripts into 1, and it works just like a bought one, including the email address validation, which calls a small Perl script, which calls the above mentioned Perl module.

> Session variables are stored in memory/ram.
Yes Elvin, it sounds as if this is the same as the "session cookies" I mentioned (they also stay in RAM only).
See: www.webopedia.com/TERM/S/session_cookie.html
In IE8 you can allow session cookies via: Tools > Internet Options > Privacy > Advanced > Override automatic cookie handling > Always allow session cookies.  I'm guessing that Firefox (for example) allows them all the time, as I can't see an option for "session cookies".

Good to have you all on the EE team.  If you ever end up asking questions in the Perl zone, I might be able to help you...for a small fee (i.e. points), of course!
0
 
LVL 12

Author Closing Comment

by:tel2
ID: 34118161
Thanks guys!
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

An enjoyable and seamless user experience can go a long way on an eCommerce site. While a cohesive layout and engaging copy play roles in creating a positive user experience, some sites neglect aspects that seem marginal but in actuality prove very …
Finding original email is quite difficult due to their duplicates. From this article, you will come to know why multiple duplicates of same emails appear and how to delete duplicate emails from Outlook securely and instantly while vital emails remai…
The viewer will get a basic understanding of what section 508 compliance can entail, learn about skip navigation links, alt text, transcripts, and font size controls.
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

914 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now