Avatar of tel2
tel2Flag for New Zealand

asked on 

Passing form params twice

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
PHPWeb DevelopmentHTML

Avatar of undefined
Last Comment
tel2
Avatar of Marco Gasi
Marco Gasi
Flag of Spain image

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
ASKER CERTIFIED SOLUTION
Avatar of Mark Brady
Mark Brady
Flag of United States of America image

Blurred text
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
Avatar of tel2
tel2
Flag of New Zealand image

ASKER

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
Avatar of Marco Gasi
Marco Gasi
Flag of Spain image

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
SOLUTION
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

Blurred text
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
Avatar of Mark Brady
Mark Brady
Flag of United States of America image

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.
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

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

Avatar of Mark Brady
Mark Brady
Flag of United States of America image

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.
Avatar of tel2
tel2
Flag of New Zealand image

ASKER

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
SOLUTION
Avatar of Marco Gasi
Marco Gasi
Flag of Spain image

Blurred text
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
Avatar of Mark Brady
Mark Brady
Flag of United States of America image

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.
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

"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.
https://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
Avatar of Mark Brady
Mark Brady
Flag of United States of America image

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.
Avatar of tel2
tel2
Flag of New Zealand image

ASKER

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!
Avatar of tel2
tel2
Flag of New Zealand image

ASKER

Thanks guys!
PHP
PHP

PHP is a widely-used server-side scripting language especially suited for web development, powering tens of millions of sites from Facebook to personal WordPress blogs. PHP is often paired with the MySQL relational database, but includes support for most other mainstream databases. By utilizing different Server APIs, PHP can work on many different web servers as a server-side scripting language.

125K
Questions
--
Followers
--
Top Experts
Get a personalized solution from industry experts
Ask the experts
Read over 600 more reviews

TRUSTED BY

IBM logoIntel logoMicrosoft logoUbisoft logoSAP logo
Qualcomm logoCitrix Systems logoWorkday logoErnst & Young logo
High performer badgeUsers love us badge
LinkedIn logoFacebook logoX logoInstagram logoTikTok logoYouTube logo