SitePoint Sponsor

User Tag List

Results 1 to 21 of 21
  1. #1
    SitePoint Zealot
    Join Date
    Oct 2004
    Location
    Rochester, NY
    Posts
    122
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Retaining Form Data after Submit

    Hey guys, I've got a small problem regarding forms and server-side validation. My validation is working, but the problem is, when the user hits the back button to enter the data that they missed -- all of the data is gone and they now have to reenter everything.

    From the little that I know about this, the fix is related to sessions, something that I don't have much knowledge about. Can anyone provide any help or reference as to where I can learn about how to retain these values in the textbox after the user has submitted them? Thanks guys.

  2. #2
    SitePoint Guru
    Join Date
    Jul 2004
    Location
    Raleigh, NC
    Posts
    783
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    PHP Code:
    <?php
    session_start
    ();
    if(isset(
    $_POST['submitted']))
    {
     foreach(
    $_POST as $p_key => $p_value)
     { 
    $_SESSION[$p_key] = $p_value; }
    }

    echo(
    '<form action=' $_SERVER['PHP_SELF'] . ' method=post>');
    echo(
    '<input type=text name=foo value="' $_SESSION['foo'] . '">');
    echo(
    '<input type=hidden name=submitted value=1>');
    echo(
    '<input type=submit>');
    echo(
    '</form>');
    ?>
    also make sure your ini is set up to handle sessions

    i typed this on the fly without testing so there may be errors, but the basics should be right

  3. #3
    SitePoint Guru
    Join Date
    Jul 2004
    Location
    Raleigh, NC
    Posts
    783
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    after i typed the above i realized i overlooked exactly what you want to do. the above will re input the data into the desired fields but you will still have issues with the back arrow. when you hit 'back', the browser will try to reload the same html that was already there. it will not call your php script again and therefore the php will not recreate the html (like the values). i guess you could try a javascript trick. but in general, try to keep your users moving forward with regards to data entry

  4. #4
    SitePoint Zealot lemkepf's Avatar
    Join Date
    Feb 2002
    Location
    WI, USA
    Posts
    128
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Some browsers keep that data; i just tried firefox and it kept the data.

    Could it be the caching on the page? If you have the header telling the page to never use the cache them maybe it will reload it, and in escence(sp) clear the fields. Try using a meta like:
    <META HTTP-EQUIV="expires" CONTENT="Wed, 26 Feb 2010 08:21:57 GMT">
    Totally guessing here...
    Happiness is a belt-fed weapon
    Consciousness: That annoying time between naps.
    Modevia Web Services LLC.

  5. #5
    SitePoint Zealot
    Join Date
    Oct 2004
    Location
    Rochester, NY
    Posts
    122
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Ya...

    ...sometimes it does maintain the values, it's real, real weird. Darchangel, now I feel bad that you tried to help me and wasted your time! I'm sorry man

    I don't think that it has to do with the Meta refresh, but it wouldn't hurt for me to try it. Personally, I'd much rather have it display the fields that are missing right above the contact form rather than have the form go away and have just the errors appear so that you're forced to click back on the browser. Actually, the script that I'm using's example actually SHOWS that happening, yet I can't seem to achieve that result. Feel free to look at the example and code that I'm using if you're interested:

    http://dave.imarc.net/php/index.php#form

    ( the form validator class )

    The difference is that my form is index.php, and it's action is mail.php. The guy's example has the validation code and the actual form in the same document (his form's action is the PHP_SELF thing ), and I'm guessing that might have something to do with it.

    Ah well, thanks guys, if there's any other help you can offer though it's appreciated

  6. #6
    dooby dooby doo silver trophybronze trophy
    spikeZ's Avatar
    Join Date
    Aug 2004
    Location
    Manchester UK
    Posts
    13,804
    Mentioned
    157 Post(s)
    Tagged
    3 Thread(s)
    Why not put the validation/ session details onto the same page as the form ie:
    the form submits to $_SERVER['PHP_SELF']
    register the posted data as session vars,
    do the validating
    if all ok continue if not display the original form with the session vars echoed and a polite message.....
    Mike Swiffin - Community Team Advisor
    Only a woman can read between the lines of a one word answer.....

  7. #7
    SitePoint Guru
    Join Date
    Jul 2004
    Location
    Raleigh, NC
    Posts
    783
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    spikeZ has a good suggestion (if not vaguely familiar ). alternatively, you can also implement javascript validation. http://javascript.internet.com has tons of free validation scripts

  8. #8
    SitePoint Zealot
    Join Date
    Oct 2004
    Location
    Rochester, NY
    Posts
    122
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Well...

    ...the problem with that is that I have the mail script as a separate file. Therefore, the action of my form has to be 'mail.php' and not the echo to itself. I'm trying something right now so I'll let ya guys know how it goes!

    Oh, and I do have javascript validation ( that was the easy part! ), it's just that you should always have both to ensure an incomplete form submission never gets past the form page.

  9. #9
    SitePoint Zealot
    Join Date
    Oct 2004
    Location
    Rochester, NY
    Posts
    122
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Well alright...

    I have a good idea about what needs to be done, but only some knowledge on how to do it. First, I'm posting the whole validator class, where I figured that this has to occur:

    PHP Code:
    <?php
    # =================================================================== #
    #
    # iMarc PHP Library
    # Copyright 2002, iMarc, LLC
    #
    # @version: 1.4
    # @last_update: 2003-01-01
    # @description: Form Validation Functions
    #
    # @changes: v1.4 - Added isset() when validating (compatibale with PHP error notices)

    # =================================================================== #
    /*
        METHODS:
            validate_fields()     - Validates a comma-separated string of $required_fields
            create_error()     - Private class function to handle errors
    */
    # ------------------------------------------------------------------- #
    # VALIDATOR CLASS
    # ------------------------------------------------------------------- #
    class validator {
        var 
    $error$error_message;        // (string) HTML formatted error message
        
    var $error_array = array();        // (array)    Error

        # ----------------------------------- #
        # FUNCTION:     validate_fields
        # DESCRIPTION:     Validates a comma-separated string of $required_fields
        #
        # ARGS:         $required_fields    (string) comma separated string of required form field names
        # 
        # RETURNS:        TRUE if all form fields are not NULL, FALSE if at least one fields is NULL.
        # ----------------------------------- #
        
    function validate_fields($required_fields='') {
            if (!
    $required_fields) {
                return 
    true;
            }
            
    $__errors = array();

            
    // Delete all spaces from the field names and place the them in an array.
            
    $__fields explode (","str_replace(" """$required_fields));
            foreach (
    $__fields as $__current_field) {    
                if (
    trim($__current_field)) {
                    if (
    strstr($__current_field"||")) {
        
                        
    /* * * *  "OR" fields * * * */
                        
                        // this_field||that_field - double pipe separated field names will check <this_field> or <that_field>
                        
    $__error      false;
                        
    $__no_error   false;
                        
    $__sub_fields explode("||"$__current_field);
            
                        foreach (
    $__sub_fields as $__current_sub_field) {
                            
    $__current_sub_field trim($__current_sub_field);
                            
                            
    settype($_REQUEST[$__current_sub_field], "string");
                            
                            if (!
    $__no_error && isset($_REQUEST[$__current_sub_field]) && !strlen(trim($_REQUEST[$__current_sub_field]))) {
                                
    $__error      true;
                            } else {
                                
    $__no_error   1;
                                
    $__error      false;
                            }
                        }

                        if (
    $__error) {
                            
    $__errors[] = $__current_field;
                        }
                    } else {
                        
                        
    /* * * *  Regular fields * * * */
                        
                        // This separates regular single fields and makes them global variables
                        
    $__current_field trim($__current_field);                
                        
    settype($_REQUEST[$__current_field], "string");

                        if (isset(
    $_REQUEST[$__current_field]) && !strlen(trim($_REQUEST[$__current_field]))) {
                            
    $__errors[] = $__current_field;
                            
                            foreach (
    $__current_field)
                            {
                                
    $_SESSION[$__current_field] = ;
                            }
                            
                        }
                    }
                }
            }
            
            if (
    count($__errors)) {
                
    $this->create_error($__errors"validate_fields");
                return 
    FALSE;
            } else {
                return 
    TRUE;
            }
        }

    /* Private */
        # ----------------------------------- #
        # FUNCTION:     create_error
        # DESCRIPTION:     Creates error messages
        #
        # ARGS:         $error        (mixed)  error message[s]
        #                 $type        (string) type of error
        # 
        # RETURNS:        VOID
        #                Sets $obj->error and $obj->error_array
        # ----------------------------------- #
        
    function create_error($error$type='') {
            
    $this->error ereg_replace("<br>$"""$this->error);
            
            if (
    $type == "validate_fields") {
                
    $r "<b>You have not filled in all of the necessary fields!  Please fill in the following:</b><br>\n";
                foreach (
    $error as $v) {
                    
    $i  1;
                    
    $r .= "&nbsp;&nbsp;&nbsp;&nbsp;";
                    
    $v_array explode("||"$v);
                    foreach (
    $v_array as $c) {
                        if (
    trim($c)) {
                            if (
    $i 1) { $r .= " <b>or</b> "; }
                            
    $missing_fields[] = $c;
                            
    $r .= ucwords(eregi_replace("_"" "$c));
                            
    $i++;
                        }
                        
                    }
                    echo 
    "<a href=\"../index.php\">index.php</a>";
                    
    $r .= "<br>\n";
                }
                
    $this->error .= $r;
                
    $this->error_array['missing_fields'] = $missing_fields;
            
            } elseif (
    $type == "message") {
                if (!
    $this->error_array['message']) {
                    
    $this->error .= "<b>The following errors occured:</b><br>\n";
                }
                
    $this->error .= "&nbsp;&nbsp;&nbsp;&nbsp;" $error "<br>\n";
                
    $this->error_array['message'][] = $missing_fields;
            }
            
    $this->error .= "<br>";
            
    $this->error_message $this->error;
        }
    }

    /*
    <readme>
        
        Validator Class is a PHP object that can be used to validate 
        the presence of HTML form data. 
        
        By "validating", the function simply checks if a variable is 
        NOT NULL. The class is intended to be called AFTER the end-user 
        has submitted an HTML form. 
        
        The class is first initiated, then the validate_fields function 
        is called by passing the field names of all the required form 
        fields. If any of the variables (field names) are NULL the 
        function returns FALSE, along with an error message of which 
        fields are null. If all the variables are NOT NULL, the function 
        returns TRUE. 
        
        # --------------------------------------------------------------- #
        # VALIDATOR CLASS USAGE
        # --------------------------------------------------------------- #
        - Start a new instance of the object:
          $my_validator = new validator();
        
        - Check for the presence of data in one variable named $my_variable
          $my_validator->validate_fields("my_variable");
        
        - Check for the presence of data in three variables 
          named $first_name, $last_name, and $email
          $my_validator->validate_fields("first_name, last_name, email");
        
        - Check for the presence of data in at least one check box. There
          are 3 checkboxes on the form ($ch_1, $ch_2, and $ch_3)
          $my_validator->validate_fields("ch_1||ch_3||ch_3");
        
        - Check for the presence of data in at least one check box, 

          AND each of 2 text fields:
          $my_validator->validate_fields("ch_1||ch_3||ch_3, text_1, text_2");
          
        - Printing Errors
            if (!$my_validator->validate_fields("last_name, email")) {
                echo $my_validator->error;
            } else {
                ...
            }
        
        # --------------------------------------------------------------- #
        # VALIDATOR CLASS SET UP
        # --------------------------------------------------------------- #
        The only set up is to include this file on the page that you're 
        using it

    </readme>

    <license>

        Copyright (c) 2002, iMarc LLC
        All rights reserved.
        
        Redistribution and use in source and binary forms, with or without 
        modification, are permitted provided that the following conditions 
        are met:
        
        *    Redistributions of source code must retain the above copyright 
            notice, this list of conditions and the following disclaimer.
        *    Redistributions in binary form must reproduce the above 
            copyright notice, this list of conditions and the following 
            disclaimer in the documentation and/or other materials 
            provided with the distribution.
        *    Neither the name of iMarc LLC nor the names of its 
            contributors may be used to endorse or promote products 
            derived from this software without specific prior 
            written permission.
        
        
        THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND 
        CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, 
        INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 
        MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 
        DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS 
        BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 
        EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
        TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 
        DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 
        ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 
        OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 
        OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
        POSSIBILITY OF SUCH DAMAGE.

    </license>

    */
    ?>
    Now, what I need to do is create session variables for each input that the user has entered ( btw, I'm providing a link back to index.php to discourage the use of a back button ), so this is the code that I put for that ( it's in the above code as well, but just so things are a bit more focused ):

    PHP Code:
                        // This separates regular single fields and makes them global variables
                        
    $__current_field trim($__current_field);                
                        
    settype($_REQUEST[$__current_field], "string");

                        if (isset(
    $_REQUEST[$__current_field]) && !strlen(trim($_REQUEST[$__current_field]))) {
                            
    $__errors[] = $__current_field;
                            
                            foreach (
    $__current_field)
                            {
                                
    $_SESSION[$__current_field] = ;
                            }
                            
                        } 
    I entered the foreach part, and the point of that is that for each field name, make a session variable with that field name and assign the actual value of the textbox ( user input ) to that variable. The problem is, I have no idea how to pull out the user input to assign it to that. Any help would be greatly appreciated!
    Last edited by dannov; Oct 29, 2004 at 08:45.

  10. #10
    SitePoint Zealot
    Join Date
    Oct 2004
    Location
    Rochester, NY
    Posts
    122
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    top

    top

  11. #11
    SitePoint Zealot
    Join Date
    Oct 2004
    Location
    Rochester, NY
    Posts
    122
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    top

  12. #12
    SitePoint Zealot lemkepf's Avatar
    Join Date
    Feb 2002
    Location
    WI, USA
    Posts
    128
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    pull out the user input? Explain more.....
    do you mean pull the stuff out of the session variables? i'm lost....
    Happiness is a belt-fed weapon
    Consciousness: That annoying time between naps.
    Modevia Web Services LLC.

  13. #13
    SitePoint Zealot
    Join Date
    Oct 2004
    Location
    Rochester, NY
    Posts
    122
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hey Iemkepf, from what I collected from a professor, this can't be done. I basically would have to take mail2.php ( my mailing script ) and merge it with index.php ( my HTML form ), as values can't be retained after clicking the back button since it refreshes the page as well as the session variables.

    Now, maybe there's a way to use cookies to store what the users input, so when they reload the page that input is there?

  14. #14
    SitePoint Zealot lemkepf's Avatar
    Join Date
    Feb 2002
    Location
    WI, USA
    Posts
    128
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Refreshses the session variables? Like the script will overwrite them? Because i know for a fact that if a session variable is created it wont get overwritten unless you do it.

    You should be able to use session variables to do what you want... if i have time later i'll look at your scripts again.... you might want to post your two scripts in full so we can take a look.
    Happiness is a belt-fed weapon
    Consciousness: That annoying time between naps.
    Modevia Web Services LLC.

  15. #15
    SitePoint Zealot
    Join Date
    Oct 2004
    Location
    Rochester, NY
    Posts
    122
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Hmm...

    ...alrighty, but this is going to get crazy = / The first script is for my mail function, the 2nd script is for my server-side validation, and my form action for my html form is the mail script ( mail.php ). Here goes!

    ==-/==-/==-/==-/==-/==-/==-/==-/==-/==-/==-/==-/==-/==-/==-/==-/==

    MAIL.PHP

    PHP Code:
    <html>
    <head>
    <title> Sending Email </title>
    </head>
    <body>
    <?php

    if ($_REQUEST['form_complete']) {

    include(
    "./validator-class.php");

    $my_form = new validator;

    $required_fields "$to$fullname$absent$subject$message";

    $passed $my_form->validate_fields("to, fullname, absent, subject, message");

    if (!
    $passed) {
        print(
    $my_form->error "<br><br>");
        exit;
    } else {
        
    // Send mail, insert into the database, or
        // do whatever you were planning on doing
        // with your freshly validated form data...


    // Read POST request params into global vars
    $to        $_POST['to'];
    $from      $_POST['from'];
    $fullname $_POST['fullname'];


    $fullnametrim rtrim($fullname);

    $absent    "Date that '" $fullnametrim "'" ." will be absent:  " $_POST['absent'];
    $subject   $_POST['subject'] . " <" $fullnametrim ">";
    $message   $absent "\n\n\n\n" "Substitution Plan:" "\n\n" $_POST['message'];

    // Obtain file upload vars
    $fileatt      $_FILES['fileatt']['tmp_name'];
    $fileatt_type $_FILES['fileatt']['type'];
    $fileatt_name $_FILES['fileatt']['name'];

    $from "SubPlan.org";

    $headers "From: $from";

     
    // Generate a boundary string
    $semi_rand md5(time());
    $mime_boundary "==Multipart_Boundary_x{$semi_rand}x";

    // Add the headers for a file attachment
    $headers .= "\nMIME-Version: 1.0\n" .
    "Content-Type: multipart/mixed;\n" .
    " boundary=\"{$mime_boundary}\"";

    // Add a multipart boundary above the plain message
    $message "This is a multi-part message in MIME format.\n\n" .
    "--{$mime_boundary}\n" .
    "Content-Type: text/plain; charset=\"iso-8859-1\"\n" .
    "Content-Transfer-Encoding: 7bit\n\n" .
    $message "\n\n";

    // ---------- Obtain file upload vars -------------------
    // image 1
    $fileatt $_FILES['fileatt1']['tmp_name'];
    $fileatt_type $_FILES['fileatt1']['type'];
    $fileatt_name $_FILES['fileatt1']['name'];
    if (
    is_uploaded_file($fileatt)) {
    // Read the file to be attached ('rb' = read binary)
    $file fopen($fileatt,'rb');
    $data fread($file,filesize($fileatt));
    fclose($file);

    // Base64 encode the file data
    $data chunk_split(base64_encode($data));

    // Add file attachment to the message
    $message .= "--{$mime_boundary}\n" .
    "Content-Type: {$fileatt_type};\n" .
    " name=\"{$fileatt_name}\"\n" .
    //"Content-Disposition: attachment;\n" .
    //" filename=\"{$fileatt_name}\"\n" .
    "Content-Transfer-Encoding: base64\n\n" .
    $data "\n\n";
    }
    // image 2
    $fileatt $_FILES['fileatt2']['tmp_name'];
    $fileatt_type $_FILES['fileatt2']['type'];
    $fileatt_name $_FILES['fileatt2']['name'];
    if (
    is_uploaded_file($fileatt)) {
    // Read the file to be attached ('rb' = read binary)
    $file fopen($fileatt,'rb');
    $data fread($file,filesize($fileatt));
    fclose($file);

    // Base64 encode the file data
    $data chunk_split(base64_encode($data));

    // Add file attachment to the message
    $message .= "--{$mime_boundary}\n" .
    "Content-Type: {$fileatt_type};\n" .
    " name=\"{$fileatt_name}\"\n" .
    //"Content-Disposition: attachment;\n" .
    //" filename=\"{$fileatt_name}\"\n" .
    "Content-Transfer-Encoding: base64\n\n" .
    $data "\n\n";
    }

    // image 3
    $fileatt $_FILES['fileatt3']['tmp_name'];
    $fileatt_type $_FILES['fileatt3']['type'];
    $fileatt_name $_FILES['fileatt3']['name'];
    if (
    is_uploaded_file($fileatt)) {
    // Read the file to be attached ('rb' = read binary)
    $file fopen($fileatt,'rb');
    $data fread($file,filesize($fileatt));
    fclose($file);

    // Base64 encode the file data
    $data chunk_split(base64_encode($data));

    // Add file attachment to the message
    $message .= "--{$mime_boundary}\n" .
    "Content-Type: {$fileatt_type};\n" .
    " name=\"{$fileatt_name}\"\n" .
    //"Content-Disposition: attachment;\n" .
    //" filename=\"{$fileatt_name}\"\n" .
    "Content-Transfer-Encoding: base64\n\n" .
    $data "\n\n";
    }

    // ------------------------
    $message .= "--{$mime_boundary}--\n";

    $ok = @mail($to$subject$message$headers);

    if (
    $ok) {
    //  echo "<p>Thank you " . $firsttrim . " " . $lasttrim . ", your SubPlan has been successfully submitted to the following address: <a href=\"mailto:" . $to . "\">" . $to . "</a></p>";
      
    echo "<p>Thank you " $fullnametrim ", your SubPlan has been successfully submitted to the following address: <a href=\"mailto:" $to "\">" $to "</a></p>";

    } else {
      echo 
    "<p>I'm sorry, but your e-mail could not be sent.  Please report any errors to the administrator: 
      <a href=\"mailto: dannovitski@hotmail.com\">Dan Novitski</a></p>"
    ;
    }

    }
    }
    ?>
    </body>
    </html>
    ==-/==-/==-/==-/==-/==-/==-/==-/==-/==-/==-/==-/==-/==-/==-/==-/==

    VALIDATOR-CLASS.PHP

    PHP Code:
    <?php
    # =================================================================== #
    #
    # iMarc PHP Library
    # Copyright 2002, iMarc, LLC
    #
    # @version: 1.4
    # @last_update: 2003-01-01
    # @description: Form Validation Functions
    #
    # @changes: v1.4 - Added isset() when validating (compatibale with PHP error notices)

    # =================================================================== #
    /*
        METHODS:
            validate_fields()     - Validates a comma-separated string of $required_fields
            create_error()     - Private class function to handle errors
    */
    # ------------------------------------------------------------------- #
    # VALIDATOR CLASS
    # ------------------------------------------------------------------- #
    class validator {
        var 
    $error$error_message;        // (string) HTML formatted error message
        
    var $error_array = array();        // (array)    Error

        # ----------------------------------- #
        # FUNCTION:     validate_fields
        # DESCRIPTION:     Validates a comma-separated string of $required_fields
        #
        # ARGS:         $required_fields    (string) comma separated string of required form field names
        # 
        # RETURNS:        TRUE if all form fields are not NULL, FALSE if at least one fields is NULL.
        # ----------------------------------- #
        
    function validate_fields($required_fields='') {
            if (!
    $required_fields) {
                return 
    true;
            }
            
    $__errors = array();

            
    // Delete all spaces from the field names and place the them in an array.
            
    $__fields explode (","str_replace(" """$required_fields));
            foreach (
    $__fields as $__current_field) {    
                if (
    trim($__current_field)) {
                    if (
    strstr($__current_field"||")) {
        
                        
    /* * * *  "OR" fields * * * */
                        
                        // this_field||that_field - double pipe separated field names will check <this_field> or <that_field>
                        
    $__error      false;
                        
    $__no_error   false;
                        
    $__sub_fields explode("||"$__current_field);
            
                        foreach (
    $__sub_fields as $__current_sub_field) {
                            
    $__current_sub_field trim($__current_sub_field);
                            
                            
    settype($_REQUEST[$__current_sub_field], "string");
                            
                            if (!
    $__no_error && isset($_REQUEST[$__current_sub_field]) && !strlen(trim($_REQUEST[$__current_sub_field]))) {
                                
    $__error      true;
                            } else {
                                
    $__no_error   1;
                                
    $__error      false;
                            }
                        }

                        if (
    $__error) {
                            
    $__errors[] = $__current_field;
                        }
                    } else {
                        
                        
    /* * * *  Regular fields * * * */
                        
                        // This separates regular single fields and makes them global variables
                        
    $__current_field trim($__current_field);                
                        
    settype($_REQUEST[$__current_field], "string");

                        if (isset(
    $_REQUEST[$__current_field]) && !strlen(trim($_REQUEST[$__current_field]))) {
                            
    $__errors[] = $__current_field;
                        }
                    }
                }
            }
            
            if (
    count($__errors)) {
                
    $this->create_error($__errors"validate_fields");
                return 
    FALSE;
            } else {
                return 
    TRUE;
            }
        }

    /* Private */
        # ----------------------------------- #
        # FUNCTION:     create_error
        # DESCRIPTION:     Creates error messages
        #
        # ARGS:         $error        (mixed)  error message[s]
        #                 $type        (string) type of error
        # 
        # RETURNS:        VOID
        #                Sets $obj->error and $obj->error_array
        # ----------------------------------- #
        
    function create_error($error$type='') {
            
    $this->error ereg_replace("<br>$"""$this->error);
            
            if (
    $type == "validate_fields") {
                
    $r "<b>You have not filled in all of the necessary fields!  Please press your browser's \"Back\" button (Followed by \"Refresh\" if the page doesn't load) and fill in the following:</b><br>\n";
                foreach (
    $error as $v) {
                    
    $i  1;
                    
    $r .= "&nbsp;&nbsp;&nbsp;•&nbsp;";
                    
    $v_array explode("||"$v);
                    foreach (
    $v_array as $c) {
                        if (
    trim($c)) {
                            if (
    $i 1) { $r .= " <b>or</b> "; }
                            
    $missing_fields[] = $c;
                            
    $r .= ucwords(eregi_replace("_"" "$c));
                            
    $i++;
                        }
                        
                    }
                    
    //echo "<a href=\"../index.php\">index.php</a>";
                    
    $r .= "<br>\n";
                }
                
    $this->error .= $r;
                
    $this->error_array['missing_fields'] = $missing_fields;
            
            } elseif (
    $type == "message") {
                if (!
    $this->error_array['message']) {
                    
    $this->error .= "<b>The following errors occured:</b><br>\n";
                }
                
    $this->error .= "&nbsp;&nbsp;&nbsp;•&nbsp;" $error "<br>\n";
                
    $this->error_array['message'][] = $missing_fields;
            }
            
    $this->error .= "<br>";
            
    $this->error_message $this->error;
        }
    }

    /*
    <readme>
        
        Validator Class is a PHP object that can be used to validate 
        the presence of HTML form data. 
        
        By "validating", the function simply checks if a variable is 
        NOT NULL. The class is intended to be called AFTER the end-user 
        has submitted an HTML form. 
        
        The class is first initiated, then the validate_fields function 
        is called by passing the field names of all the required form 
        fields. If any of the variables (field names) are NULL the 
        function returns FALSE, along with an error message of which 
        fields are null. If all the variables are NOT NULL, the function 
        returns TRUE. 
        
        # --------------------------------------------------------------- #
        # VALIDATOR CLASS USAGE
        # --------------------------------------------------------------- #
        - Start a new instance of the object:
          $my_validator = new validator();
        
        - Check for the presence of data in one variable named $my_variable
          $my_validator->validate_fields("my_variable");
        
        - Check for the presence of data in three variables 
          named $first_name, $last_name, and $email
          $my_validator->validate_fields("first_name, last_name, email");
        
        - Check for the presence of data in at least one check box. There
          are 3 checkboxes on the form ($ch_1, $ch_2, and $ch_3)
          $my_validator->validate_fields("ch_1||ch_3||ch_3");
        
        - Check for the presence of data in at least one check box, 
          AND each of 2 text fields:
          $my_validator->validate_fields("ch_1||ch_3||ch_3, text_1, text_2");
          
        - Printing Errors
            if (!$my_validator->validate_fields("last_name, email")) {
                echo $my_validator->error;
            } else {
                ...
            }
        
        # --------------------------------------------------------------- #
        # VALIDATOR CLASS SET UP
        # --------------------------------------------------------------- #
        The only set up is to include this file on the page that you're 
        using it

    </readme>

    <license>

        Copyright (c) 2002, iMarc LLC
        All rights reserved.
        
        Redistribution and use in source and binary forms, with or without 
        modification, are permitted provided that the following conditions 
        are met:
        
        *    Redistributions of source code must retain the above copyright 
            notice, this list of conditions and the following disclaimer.
        *    Redistributions in binary form must reproduce the above 
            copyright notice, this list of conditions and the following 
            disclaimer in the documentation and/or other materials 
            provided with the distribution.
        *    Neither the name of iMarc LLC nor the names of its 
            contributors may be used to endorse or promote products 
            derived from this software without specific prior 
            written permission.
        
        
        THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND 
        CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, 
        INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 
        MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 
        DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS 
        BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 
        EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
        TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 
        DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 
        ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 
        OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 
        OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
        POSSIBILITY OF SUCH DAMAGE.

    </license>

    */
    ?>

    The mail file is easy enough to follow, the validator-class is wicked crazy though...

  16. #16
    SitePoint Zealot
    Join Date
    Oct 2004
    Location
    Rochester, NY
    Posts
    122
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    *bump*

    Bumped for Iemkepf

  17. #17
    SitePoint Zealot lemkepf's Avatar
    Join Date
    Feb 2002
    Location
    WI, USA
    Posts
    128
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Well first... your form isn't storing any of the entered data in a session variable. Here is what you should do.
    On the form iteself for each field, set the value to a session variable.
    On the form your submitting too, set the value of the session variable to the posted data. That way if they go back, the form will pull the session data.
    Happiness is a belt-fed weapon
    Consciousness: That annoying time between naps.
    Modevia Web Services LLC.

  18. #18
    SitePoint Zealot
    Join Date
    Oct 2004
    Location
    Rochester, NY
    Posts
    122
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Doesn't work...

    Well, here's what I did:

    HTML Code:
    <form action="form/mail.php" name="subplanform" method="post" onSubmit="return checkform(this.elements)" method="POST" enctype="multipart/form-data">
    
    <table class="chalktableattribs" cellspacing="5"><tr><td><input type="hidden" name="form_complete" value="1">
    <p>To:<br /> <input type="text" size="50" name="to" value="<?PHP echo $array[0];?>" /><br />
    <span style="color: #000">(Do not alter the above field unless absolutely necessary)</span><br /><br />
    Full Name:<br /> <input type="text" size="50"  name="fullname" value="<?PHP $_SESSION['fullname']; ?>" /><br /><br />
    Date(<span style="color: #000000">s</span>) to be Absent:<br /> <input type="text" size="50"  name="absent" value="<?PHP $_SESSION['absent']; ?>" /><br />
    <span style="color: #000000">(Please separate multiple dates with commas)</span><br /><br />
    Subject:<br /> <input type="text" size="50" name="subject" value="<?PHP $_SESSION['subject']; ?>" /></p></td><td align="right"><br /><div class="chalka"><div class="chalkb"><?php print("<br /><br />" . $login . "!");?></div></div></td></tr></table>
    
    <p><table class="messageattribs" cellspacing="5"><tr><td>Type Your Substitute Teacher Plan Below:<br />
    <textarea cols="84" rows="27" value="<?PHP $_SESSION['message']; ?>" wrap="hard" name="message"></textarea></td></tr></table></p>
    
    <br/>
    </td></tr></table>
    </form>
    And, for the mail.php file, I made these:

    PHP Code:
    $_SESSION['fullnametrim'] = $_POST['fullname'];
    $_SESSION['absent'] = $_POST['absent'];
    $_SESSION['subject'] = $_POST['subject'];
    $_SESSION['message'] = $_POST['message']; 
    Suffice it to say, it doesn't work = /

  19. #19
    SitePoint Zealot
    Join Date
    Oct 2004
    Location
    Rochester, NY
    Posts
    122
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    *bump*

  20. #20
    SitePoint Zealot lemkepf's Avatar
    Join Date
    Feb 2002
    Location
    WI, USA
    Posts
    128
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    You need a print statement before your session thing.
    <?php print $_SESSION['absent']; ?>
    Happiness is a belt-fed weapon
    Consciousness: That annoying time between naps.
    Modevia Web Services LLC.

  21. #21
    SitePoint Zealot
    Join Date
    Oct 2004
    Location
    Rochester, NY
    Posts
    122
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Ah, no dice = / I don't think that it can be done, but it's really no big deal. The server-side validation is the last attempt to make sure the e-mail doesn't go out, the chances of this specific audience that the site is tailored towards having both javascript disabled and missing fields isn't a large one. I can always try combining mail.php and index.php too so I can just have it echo itself right? Ah well, thanks Iemkepf, I appreciate your help!


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •