Dealing with forms

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
nigma
DevNet Resident
Posts: 1094
Joined: Sat Jan 25, 2003 1:49 am

Dealing with forms

Post by nigma »

i'm trying to figure out how I can display success/failure messages after a user submits a form and after i've redirected the user back to the form. (the redirect is to prevent them from resubmitting the form when they hit f5.) I've thought about using get variables to say whether it was success or failure like so:

Code: Select all

if user submitted form
  header("script.php?message=$messagetext");
but I don't like the idea of a user being able to change text on the page by altering the url.

Anyone willing to share some insight into possible alternatives?
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post by Chris Corbyn »

Here's what I always do... but it's probably not "the" best way.

Submit the data via POST to a script dedicated to processing the data.

Validate data within the second script, with no output whatsoever, just processing.

If something doesn't validate, redirect to the form page with either a new session variable or a GET variable identifying that particular error (or if I'm in a rush, just something that identifies an error, full-stop). If all is OK, process the database query (or whatever you're doing) and then redirect to the form page with a GET or session variable which identifies success.

Example:

Code: Select all

<form action=&quote;process.php&quote; method=&quote;post&quote;>
Enter a number : <input type=&quote;text&quote; name=&quote;the_number&quote; />
<br />
<input type=&quote;submit&quote; value=&quote;Submit&quote; />
</form>
<br />
<?php
if (isset($_GETї'success'])) {
    echo 'Thanks, your number has been submitted';
}
if (isset($_GETї'failure'])) {
    echo 'no, I aksed you to enter a NUMBER';
}
?>

Code: Select all

<?php

if (!empty($_POST)) {
    if (isset($_POSTї'the_number'])) {
        if (is_nan($_POSTї'the_number']) || $_POSTї'the_number'] == '') {
            header ('location: Form.php?failure=1'); //Fail
        } else {
            //Process your data now!
            header ('location: Form.php?success=1'); //Success
        }
    } else {
        header ('location: Form.php?failure=1'); //Fail
    }
} else {
    echo 'This page is for form submissions only'; //Shouldn't be here
}
?>
If you dont want the user to be able to change the address bar to make it say "Success" (even though nothing will have been done anyway), then use $_SESSION instead ;-)

EDIT | Tinkered with !empty($_POST)
Post Reply