/    Sign up×
Community /Pin to ProfileBookmark

Separate or same page form handlers

I have a main page (main.html) with a link to a feedback page (either feedback.html or feedback.php based on how I do it). The feedback page will have a form which will be submitted to the php server, and it should then return to main.html.

I can use a totally different file to handle the form by adding the following to feedback.html:

[CODE]<form action=”process_feedback.php” method=”post”>[/CODE]

Or I can include the form handling script in the feedback.php adding the following to feedback.php:

[CODE]<?php
….
$self=$_SERVER[‘PHP_SELF’];
….?>
….
<form action=”<?php $self ?>” method=”post”>[/CODE]

Can anyone comment of the pros and cons of both method?

Thanks

to post a comment
PHP

27 Comments(s)

Copy linkTweet thisAlerts:
@NightShift58Feb 07.2007 — You can do both in a single script but you'll have to intercept/differentiate with something like:[code=php]<?
$Error_in_Form = false;
IF (isset($_POST['submit'])) :
// process input
ENDIF;

IF ($Errors_in_Form or !isset($_POST['submit'])) :
//display form with error messages
ELSE :
// redirect user to wherever
ENDIF;
?>[/code]
Copy linkTweet thisAlerts:
@NotionCommotionauthorFeb 07.2007 — Do you recommend doing both in the same script (and intercept/differentiate as you explained), or use two scripts? Thanks
Copy linkTweet thisAlerts:
@NightShift58Feb 07.2007 — Whatever makes your life easier...

Mine is (usually) easier when I combine both aspects in one script.
Copy linkTweet thisAlerts:
@NotionCommotionauthorFeb 07.2007 — Thanks NightShift58. I am a believer in easy.

Are there any situations that blatantly cry out to use separate files or my life will be less easy?

Also, is it possible to make the action a php function that exists in my_php_functions.php and then add the function using include_once "my_php_functions.php";? I expect it not to be possible, but thought I’d ask anyways.

Thanks again
Copy linkTweet thisAlerts:
@NightShift58Feb 07.2007 — I don't think anything is blatant. When you - potentially - need code both before and after posting, it makes the most sense. I have seen entire applications written in a single script page and using various IF/ELSE to control the flow and I've seen the other extreme as well. I don't think there's a "rule" out, yet...

The action must be a page/file/script and cannot be a function inside a script, as that wouldn't be visible to HTTP, who only sees files and not their content.
Copy linkTweet thisAlerts:
@NotionCommotionauthorFeb 07.2007 — Thanks again NightShift58. That makes perfect sense.

I try not to ask auxiliary off-topic questions, but will do a quick yes or no one this time.

I noticed your use of ENDIF, and upon a little research, I found it was an alternative control structure. If I am still fairly new to PHP and feel confident with the other approach ( i.e. if (this) {xxx} else {yyy} ) should learn more about the syntax you are using?

Thanks
Copy linkTweet thisAlerts:
@NightShift58Feb 07.2007 — That's a matter of personal taste. I started coding PHP with the curly brackets in the late 90's. And for better or for worse, that's the way I did it and things were fine. I discovered the alternative syntax by accident, having been handed a script to modify which had been coded that way. I discovered that it was better - for me - and I've been coding that way since.

The code works the same - there's no magic either way. It's just what is easier to maintain and debug, as a matter of personal opinion.

A lot of other languages use a BEGIN-END sequence (Visual Basic, ASP, Visual FoxPro, modern COBOL and a few more) and nobody really complains. Some people like to make a big deal out of it. The truth is that good code is good code and bad code is bad code, regardless of the ENDIF's.

In the end, it's up to you.
Copy linkTweet thisAlerts:
@NotionCommotionauthorFeb 07.2007 — Not really a "yes or no" answer, but I appreciate your explaination. As someone that started in mid 2006, your and other's help has been invaluable.

I will work on getting my single script working. If and likely when I need help, you will likely hear my plea for assistance!

Thank you again!!!
Copy linkTweet thisAlerts:
@NightShift58Feb 07.2007 — You're welcome!
Copy linkTweet thisAlerts:
@bokehFeb 07.2007 — I don't think anything is blatant.[/QUOTE]I disagree. I would say always have the form and processing script in the same page. For a start it means a lot less code also it allows the form to be sticky. It might seem more work when you are a beginner but later it saves lots of work.
Copy linkTweet thisAlerts:
@NightShift58Feb 07.2007 — I disagree.[/QUOTE]With whom?

With me? ... who said that I prefer putting both parts in a single script?
Copy linkTweet thisAlerts:
@bokehFeb 07.2007 — I can see how that could be ambiguous! What I don't agree with is doing something for the wrong reasons.
Copy linkTweet thisAlerts:
@ycubedFeb 07.2007 — Try using sessions!

There's more about this at http://www.webbudd.co.za
Copy linkTweet thisAlerts:
@bokehFeb 07.2007 — Try using sessions![/QUOTE]What for?
Copy linkTweet thisAlerts:
@NightShift58Feb 07.2007 — I can see how that could be ambiguous! What I don't agree with is doing something for the wrong reasons.[/QUOTE]Yes, the story of my life... ?
Copy linkTweet thisAlerts:
@russellFeb 07.2007 — What for?[/QUOTE]

That's SPAM. he put three posts with nothing but links to his own (completely unrealted) forum.
Copy linkTweet thisAlerts:
@NotionCommotionauthorFeb 08.2007 — I am not sure if I understand the logic to handle the form in a single page. You had the following:
[CODE]<?
$Error_in_Form = false;
IF (isset($_POST['submit'])) :
// process input
ENDIF;

IF ($Errors_in_Form or !isset($_POST['submit'])) :
//display form with error messages
ELSE :
// redirect user to wherever
ENDIF;
?> [/CODE]

Would something like the following be as good?
[CODE]<?php
$error="";
if (isset($_POST['submit'])) {
// Process form, and if there is an error, set $error="error discription"
if ($error.="") { echo($error); }
else {//store data in database and redirect to new location}
}
else
{//Display Form}
?>[/CODE]


I used the different control syntax just because I know it better, but that shouldn't have any effect.

Thanks
Copy linkTweet thisAlerts:
@NightShift58Feb 08.2007 — No, because in case of errors, you would want to display the (sticky) form once again. So you can't/should make it an ELSE case - or the purpose of putting both in a single is lost.
Copy linkTweet thisAlerts:
@NotionCommotionauthorFeb 08.2007 — Thanks again Nightshift58

I had previously been using javascript to verify forms, and while I later used php to revalidate, I hadn't been as worried about implementing sticky forms and thus haven't learned how to. I since concluded that I should learn this technique for non js enabled users, however, am optimistic I can find out how elsewhere and won't burden you with newbie questions (at this time!).

As for as the basic logic, do I understand it correctly:
[code=html]<?
$Error_in_Form = "";
if (isset($_POST['submit']))
{
// validate each input and if something wrong, set $Error_in_Form.="detailed error description<br>"
}
if (($Errors_in_Form!="") or !isset($_POST['submit']))
{
if ($Error_in_Form.="") { echo($Error_in_Form); }
//display form using sticky inputs
}
else
{
// store data in database
// redirect user to wherever
}
?>[/code]
Copy linkTweet thisAlerts:
@NightShift58Feb 08.2007 — [code=php]<?php
$Error_in_Form = "";
if (isset($_POST['submit']))
{
foreach (input)
{
validate
}
if (something wrong )
{
set $Error_in_Form.="detailed error description<br>"
}
else
{
store data in database
redirect user to wherever
}
}
if (($Errors_in_Form!="") or !isset($_POST['submit']))
{
if ($Error_in_Form.="")
{
echo($Error_in_Form);
}
echo form using sticky inputs
}
?>[/code]
Copy linkTweet thisAlerts:
@NightShift58Feb 08.2007 — Just for fun, I put a page together with a sample input/update sticky form and tried to include all the elements that I think should be there. I'm sure I've forgotten this or that.

It's only two input fields but I tried to make it somewhat representative of the type of checks and steps that I go through when I do a single script, two-step form-processing.

I've include some client-side validation, server-side as well, etc. The kind of stuff we've been discussing... Threw in two mini functions for good measure and optional redirection or bleed-through back to the form with user message.

Take a look. Some ideas may come of it...[code=php]<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html dir="ltr" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<style type="text/css">
<!--
.err_msg {font-weight: bold; color:red; height:35pt; width:250pt; border: 1px dotted navy; padding:3px; background-color:lightyellow;}
.fld_set {width:255pt; padding:3px;}
.fld_legend {font-weight: bold; color:navy; font-variant:small-caps; padding-left:5px;padding-right:5px;}
-->
</style>
<script type="text/javascript">
<!--
// Validation of required input fields
function form_validate(thisform,popup) {
var err_msg = "";
with (thisform) {
if (col1.value==null || col1.value=="") {
col1.focus();
err_txt = "Please enter a value for Column1";
err_msg = err_msg + err_txt + "<br />";
if (popup) {
alert(err_txt);
}
}
if (col2.value==null || col2.value=="") {
if (err_msg == "") {
col2.focus();
}
err_txt = "Please enter a value for Column2";
err_msg = err_msg + err_txt + "<br />";
if (popup) {
alert(err_txt);
}
}
}
if (err_msg != "") {
document.getElementById("err_msg").innerHTML = err_msg;
return false;
}
return true;
}
// -->
</script>
</head>
<body>
<?php
// Check self-referral
$CHECKfromself = true;
// Set form action if different than PHP_SELF
$ACTIONpage = "";
// Enter a redirect location if desired
$REDIRlocation = "";
// Initialize fields
$COL1 = "";
$COL2 = "";
// Set to empty, used as a flag item
$USRmsg = "";
// With JS Alert?
$JSalert = true;

// Check submit button and hidden form name variable to confirm
IF (isset($_POST['submit']) AND (isset($_POST['FrmName']) AND $_POST['FrmName'] == "do_insert")) :

IF (!CheckOrigin($CHECKfromself)) :
$USRmsg = "Data submission from unauthorized source.";
ELSE :
require_once "../DBconnect2.inc.php";
// Server-side sanitization of POST variables
$COL1 = CheckPrepSQL("col1");
IF ($COL1 == "") :
$USRmsg .= "Please enter a value for Column1.<br />";
ENDIF;
$COL2 = CheckPrepSQL("col2");
IF ($COL2 == "") :
$USRmsg .= "Please enter a value for Column2.<br />";
ENDIF;

IF ($USRmsg == "") :
// PHP Search Script
$sql = "INSERT INTO yourtable ";
$sql .= " SET col1 = '$COL1', ";
$sql .= " col2 = '$COL2' ";
$sql .= " ON DUPLICATE KEY UPDATE col2 = '$COL2' ";
$qry = mysql_query($sql) or die ('SQL Error: ' . $sql . '<br />' . mysql_error());
IF ($REDIRlocation == "") :
$USRmsg = "The record has been succesfully inserted or updated.";
ELSE :
header("Location: $REDIRlocation");
exit;
ENDIF;
ENDIF;
ENDIF;
ENDIF;
?>

<fieldset class="fld_set">
<legend class="fld_legend">Sample Input Form</legend>
<form method="POST" name="FrmInput" action=<?php echo ($ACTIONpage==""? $_SERVER['PHP_SELF'] : $ACTIONpage) ?>" enctype="multipart/form-data" onsubmit="return form_validate(this,<?php echo ($JSalert? "true" : "false") ?>);">

<input type="hidden" name="FrmName" value="do_insert" />

<label for="col1">Enter Column1: </label>
<input type="text" name="col1" id="col1" value="<? echo $COL1 ?>" /><br />

<label for="col2">Enter Column2: </label>
<input type="text" name="col2" id="col2" value="<? echo $COL2 ?>" /><br />

<input type="SUBMIT" name="submit" value="Search!" />
</form>
<div id="err_msg" class="err_msg"><?php echo $USRmsg ?></div><br />
</fieldset>

</body>
</html>

<?php
//----------------------------------------------
function CheckOrigin($pCheck=true) {
return (!$pCheck OR ($_SERVER['HTTP_REFERER'] <> "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']));
}
//----------------------------------------------
function CheckPrepSQL($pField) {
$retVAL = "";
IF (isset($_POST[$pField]) AND $_POST[$pField] <> "") :
$retVAL = mysql_real_escape_string(trim(get_magic_quotes_gpc() ? stripslashes($_POST[$pField]) : $_POST[$pField]));
ENDIF;
return $retVAL;
}
?>[/code]
Copy linkTweet thisAlerts:
@bokehFeb 08.2007 — I'm sure I've forgotten this or that.[/QUOTE]You have your logical order wrong. Always run through the descission making process before sending any content to the client. In the case of this script that order should be:[LIST=1]
  • [*]if necessary, process form

  • [*]decide if to redirect

  • [*]if not send output

  • [/LIST]
    Heres a slightly different take on it:[code=php]<?php

    $Error_in_Form = '';

    if($_POST)
    {
    if(!($Error_in_Form = validate($_POST)))
    {
    # store data in database
    # header('Location: some.page');
    die('Redirection failure message!');
    }
    }

    header('Content-Type: text/html; charset=ISO-8859-1');

    ?><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
    "http://www.w3.org/TR/html4/strict.dtd">

    <html lang="en">
    <head>

    <title>Sticky form</title>

    <style type="text/css">
    form p{clear:left;}
    label, input{width:5em;float:left;margin-bottom:0.2em;}
    input{width:8em;}
    .error-message{color:red;font-weight:bold;}
    </style>

    </head>

    <body>

    <?php echo form(($_POST?$_POST:null), $Error_in_Form) ?>

    </body>
    </html><?php

    function form($in, $error)
    {
    $text_fields = array('name', 'email');
    foreach($text_fields as $fieldname)
    {
    @$printout .= "<p><label for='$fieldname'>".ucfirst($fieldname).
    ": <label><input type='text' name='$fieldname' id='$fieldname'".
    (@$in[$fieldname] ? " value='".$in[$fieldname]."'" : '').
    '></p>'."n";
    }
    return '<form action="" method="post">'."n".
    ($error ? '<p class="error-message">'.$error.'</p>'."n":'').
    $printout.
    "<p><label for='submit'>Proceed: </label><input type='submit' name='submit' id='submit' value='next step'></p>n".
    '</form>'."n";
    }

    function validate($in)
    {
    $errors = '';
    if(!preg_match('/^[a-z]+$/i', trim($in['name'])))
    {
    $errors .= 'Name field incorrectly filled in!<br>'."n";
    }
    if(!preg_match('/^([_a-z0-9-]+)(.[_a-z0-9-]+)*@([a-z0-9-]+)(.[a-z0-9-]+)*(.[a-z]{2,6})$/', trim($in['email'])))
    {
    $errors .= 'Email field incorrectly filled in!<br>'."n";
    }
    return $errors;
    }

    ?>[/code]
    Copy linkTweet thisAlerts:
    @NightShift58Feb 08.2007 — You're right.

    Last minute, untested addition. At 5:29 p.m., it seemed right.

    Will repost... after first coffee...
    Copy linkTweet thisAlerts:
    @NightShift58Feb 08.2007 — [code=php]<?php
    // Check self-referral
    $CHECKfromself = true;
    // Set form action if different than PHP_SELF
    $ACTIONpage = "";
    // Enter a redirect location if desired
    $REDIRlocation = "";
    // Initialize fields
    $COL1 = "";
    $COL2 = "";
    // Set to empty, used as a flag item
    $USRmsg = "";
    // With JS Alert?
    $JSalert = true;

    // Check submit button and hidden form name variable to confirm
    IF (isset($_POST['submit']) AND (isset($_POST['FrmName']) AND $_POST['FrmName'] == "do_insert")) :

    IF (!CheckOrigin($CHECKfromself)) :
    $USRmsg = "Data submission from unauthorized source.";
    ELSE :
    require_once "../DBconnect2.inc.php";
    // Server-side sanitization of POST variables
    $COL1 = CheckPrepSQL("col1");
    IF ($COL1 == "") :
    $USRmsg .= "Please enter a value for Column1.<br />";
    ENDIF;
    $COL2 = CheckPrepSQL("col2");
    IF ($COL2 == "") :
    $USRmsg .= "Please enter a value for Column2.<br />";
    ENDIF;

    IF ($USRmsg == "") :
    // PHP Search Script
    $sql = "INSERT INTO yourtable ";
    $sql .= " SET col1 = '$COL1', ";
    $sql .= " col2 = '$COL2' ";
    $sql .= " ON DUPLICATE KEY UPDATE col2 = '$COL2' ";
    $qry = mysql_query($sql) or die ('SQL Error: ' . $sql . '<br />' . mysql_error());
    IF ($REDIRlocation == "") :
    $USRmsg = "The record has been succesfully inserted or updated.";
    ELSE :
    header("Location: $REDIRlocation");
    exit;
    ENDIF;
    ENDIF;
    ENDIF;
    ENDIF;
    ?>

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html dir="ltr" lang="en">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
    <style type="text/css">
    <!--
    .err_msg {font-weight: bold; color:red; height:35pt; width:250pt; border: 1px dotted navy; padding:3px; background-color:lightyellow;}
    .fld_set {width:255pt; padding:3px;}
    .fld_legend {font-weight: bold; color:navy; font-variant:small-caps; padding-left:5px;padding-right:5px;}
    -->
    </style>
    <script type="text/javascript">
    <!--
    // Validation of required input fields
    function form_validate(thisform,popup) {
    var err_msg = "";
    with (thisform) {
    if (col1.value==null || col1.value=="") {
    col1.focus();
    err_txt = "Please enter a value for Column1";
    err_msg = err_msg + err_txt + "<br />";
    if (popup) {
    alert(err_txt);
    }
    }
    if (col2.value==null || col2.value=="") {
    if (err_msg == "") {
    col2.focus();
    }
    err_txt = "Please enter a value for Column2";
    err_msg = err_msg + err_txt + "<br />";
    if (popup) {
    alert(err_txt);
    }
    }
    }
    if (err_msg != "") {
    document.getElementById("err_msg").innerHTML = err_msg;
    return false;
    }
    return true;
    }
    // -->
    </script>
    </head>
    <body>
    <fieldset class="fld_set">
    <legend class="fld_legend">Sample Input Form</legend>
    <form method="POST" name="FrmInput" action=<?php echo ($ACTIONpage==""? $_SERVER['PHP_SELF'] : $ACTIONpage) ?>" enctype="multipart/form-data" onsubmit="return form_validate(this,<?php echo ($JSalert? "true" : "false") ?>);">

    <input type="hidden" name="FrmName" value="do_insert" />

    <label for="col1">Enter Column1: </label>
    <input type="text" name="col1" id="col1" value="<? echo $COL1 ?>" /><br />

    <label for="col2">Enter Column2: </label>
    <input type="text" name="col2" id="col2" value="<? echo $COL2 ?>" /><br />

    <input type="SUBMIT" name="submit" value="Search!" />
    </form>
    <div id="err_msg" class="err_msg"><?php echo $USRmsg ?></div><br />
    </fieldset>

    </body>
    </html>

    <?php
    //----------------------------------------------
    function CheckOrigin($pCheck=true) {
    return (!$pCheck OR ($_SERVER['HTTP_REFERER'] <> "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']));
    }
    //----------------------------------------------
    function CheckPrepSQL($pField) {
    $retVAL = "";
    IF (isset($_POST[$pField]) AND $_POST[$pField] <> "") :
    $retVAL = mysql_real_escape_string(trim(get_magic_quotes_gpc() ? stripslashes($_POST[$pField]) : $_POST[$pField]));
    ENDIF;
    return $retVAL;
    }
    ?>[/code]
    Copy linkTweet thisAlerts:
    @NotionCommotionauthorFeb 09.2007 — Thank you both.

    bokeh, haven't digested your script yet, but will.

    NightShift58, a couple of questions.

    Why do you verify the hidden input?

    (isset($_POST['FrmName']) AND $_POST['FrmName'] == "do_insert")

    Why encript the form?

    enctype="multipart/form-data"

    Why does this signify it is coming from the wrong source?

    ($_SERVER['HTTP_REFERER'] <> "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'])

    Can you explain the following line:

    $retVAL = mysql_real_escape_string(trim(get_magic_quotes_gpc() ? stripslashes($_POST[$pField]) : $_POST[$pField]));

    Thanks!!!
    Copy linkTweet thisAlerts:
    @NotionCommotionauthorFeb 09.2007 — Okay, bokeh, your turn.

    I am sure you know it, but == and not =. This line also helped me realize that $_POST is an array which gives a lot of options.

    if(!($Error_in_Form = validate($_
    POST)))

    Any advantages of defining in php, and not directly in html using meta?

    header('Content-Type: text/html; charset=ISO-8859-1');

    Three questions on this one. First, why suppress errors using @ (took me a while to search what @ meant!). Second, should I be worried about not closing the label tag (I know, not a php question). Third, why use ucfirst?

    @$printout .= "<p><label for='$fieldname'>".ucfirst($fieldname).

    I appreciate both of your approaches, and you have both taught be a lot.

    Thanks
    Copy linkTweet thisAlerts:
    @NightShift58Feb 09.2007 — Why do you verify the hidden input?

    (isset($_POST['FrmName']) AND $_POST['FrmName'] == "do_insert")[/quote]
    I don't need to in this case, but I often use a single script to insert, delete and modify data. I use that to keep track of where I'm coming from and going to...Why encript the form? enctype="multipart/form-data"[/quote]It's not encrypted. It doesn't hurt to have it there and if I use the form to upload a file, I must have it there. So for the older, forgetful types, why not?Why does this signify it is coming from the wrong source?

    ($_SERVER['HTTP_REFERER'] <> "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'])[/quote]
    I (usually) don't want anyone sending me data to insert in a database unless they're coming from one of my pages. In this case, it' a self-calling form so the referrer can only be itself.Can you explain the following line:

    $retVAL = mysql_real_escape_string(trim(get_magic_quotes_gpc() ? stripslashes($_POST[$pField]) : $_POST[$pField]));
    [/quote]
    I'm not too fond of the way it's written either but I got lazy... This is basically an IF/ELSE. I check if magic quotes are set and if so, remove any quotes the server may have added to ensure safe passage of the variables - if they are set - through HTTP. Once removed, I escape the string so that if can be used for MySQL. That value is returned to the main script.



    Thanks!!![/QUOTE]You're welcome!
    ×

    Success!

    Help @NotionCommotion spread the word by sharing this article on Twitter...

    Tweet This
    Sign in
    Forgot password?
    Sign in with TwitchSign in with GithubCreate Account
    about: ({
    version: 0.1.9 BETA 5.22,
    whats_new: community page,
    up_next: more Davinci•003 tasks,
    coming_soon: events calendar,
    social: @webDeveloperHQ
    });

    legal: ({
    terms: of use,
    privacy: policy
    });
    changelog: (
    version: 0.1.9,
    notes: added community page

    version: 0.1.8,
    notes: added Davinci•003

    version: 0.1.7,
    notes: upvote answers to bounties

    version: 0.1.6,
    notes: article editor refresh
    )...
    recent_tips: (
    tipper: @AriseFacilitySolutions09,
    tipped: article
    amount: 1000 SATS,

    tipper: @Yussuf4331,
    tipped: article
    amount: 1000 SATS,

    tipper: @darkwebsites540,
    tipped: article
    amount: 10 SATS,
    )...