Retaining information in php contact form

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
slaterino
Forum Commoner
Posts: 46
Joined: Fri Jul 11, 2008 10:50 am

Retaining information in php contact form

Post by slaterino »

Hi,
I have designed a contact form in php but for the life of me can't work out how I can set it so that if the user types in the wrong details and the page refreses it keeps the data that was originally typed in. I have simply setup the contact page so that if the data typed in is not valid it will add a message to the header. When this message is added however it always wipes all the previous data. Here is the code I am using:

Code: Select all

<?php
   // start PHP session
   session_start();
 
    if(isset($_POST['docontact']))
    {
 
        $to = "yes@email.com";
 
        $def_subject = "HELP!";
 
        $min_name_len = 2;
 
        $min_message_len = 5;
 
        if (
        strtoupper($_POST['code']) == $_SESSION['code']
        ) 
        {
 
        if(
        isset($_POST['name']) and 
        strlen($_POST['name']) >= $min_name_len and 
        isset($_POST['message']) and 
        strlen($_POST['message']) >= $min_message_len and 
        isset($_POST['email']) and 
        preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i", $_POST['email'])
        )
        {
            $subject = (isset($_POST['subject'])) ? $_POST['subject'] : $def_subject;
            $message = $_POST['message'] ."\n==================================================\n" .$_POST['name'] ." | " .$_POST['email'];
            $header = "From: " .$_POST['name'] ." <" .$_POST['email'] .">\r\n";
 
            mail($to, $subject, $message, $headers);
 
            header("location: ?" .$_SERVER['QUERY_STRING'] ."&sent");
        }
        else
        {
            header("location: ?" .$_SERVER['QUERY_STRING'] ."&fillall");
        }
        }
        else 
        {
            header("location: ?" .$_SERVER['QUERY_STRING'] ."&wrongcode");
        }
    }
?>
And these are the headers that appear if the criteria are not met:

Code: Select all

       <?php
            
            if(isset($_GET['sent']))
            {
                echo "<p class=\"success\">Thank you, your message was sent successfully.</p>";
            }
            if(isset($_GET['wrongcode']))
            {
                echo "<p class=\"wrongcode\">You have entered the wrong code. Please try again.</p>";
            }
            if(isset($_GET['fillall']))
            {
                echo "<p class=\"error\">Please fill out all mandatory fields. This error may also occur if your email address is invalid.</p>";
            }
        ?>
Does anyone have any suggestions how I can go about resolving this?

Many thanks!
Russ
mattpointblank
Forum Contributor
Posts: 304
Joined: Tue Dec 23, 2008 6:29 am

Re: Retaining information in php contact form

Post by mattpointblank »

Set the fields for the form to have $_POST['fieldname'] as their values? Make sure to clean data beforehand though.
slaterino
Forum Commoner
Posts: 46
Joined: Fri Jul 11, 2008 10:50 am

Re: Retaining information in php contact form

Post by slaterino »

hey thanks for the reply. when you say clean, is that the addslashes thing? Is that the best way of doing it?

Cheers
mattpointblank
Forum Contributor
Posts: 304
Joined: Tue Dec 23, 2008 6:29 am

Re: Retaining information in php contact form

Post by mattpointblank »

It's one way - there's a fairly comprehensive article about breaking addslashes, though, by Chris Shiflett. Personally I use a combination of mysql_real_escape_string, htmlentities, htmlspecialchars, strip_tags and addslashes, in a function called cleanGet:

Code: Select all

 
function cleanGet($input)
{
    if (isset($_GET[$input])){
        $new = htmlentities($_GET[$input], ENT_QUOTES); // converts html to literal characters
        $new = strip_tags($new); // removes anything else that might have made it through
        $new = addslashes($new); // adds slashes - can be replaced with mysql_real_escape_string if you prefer
        return $new;
    } else {
        return null;
    }
}
 
Then instead of using $_GET['variable'], I just use cleanGet('variable').
slaterino
Forum Commoner
Posts: 46
Joined: Fri Jul 11, 2008 10:50 am

Re: Retaining information in php contact form

Post by slaterino »

Does this also work the same for POST as I am using POST to get the data from the form?

Thanks
Russ
mattpointblank
Forum Contributor
Posts: 304
Joined: Tue Dec 23, 2008 6:29 am

Re: Retaining information in php contact form

Post by mattpointblank »

Oops - yes, I posted the wrong function, haha. You can just rename it cleanPost and change the $_GET parts to $_POST. There you go, two functions for the price of one.
slaterino
Forum Commoner
Posts: 46
Joined: Fri Jul 11, 2008 10:50 am

Re: Retaining information in php contact form

Post by slaterino »

Sorry can I just check one last thing. Will I have to repeat the function for every variable? Say for instance I wanted to clean the name, email and subject fields would I then have to have functions for each variable? I can't tell if I'm being a bit stupid by asking this but hey, tis always worth an ask!
TheBrandon
Forum Commoner
Posts: 87
Joined: Tue May 20, 2008 8:55 am

Re: Retaining information in php contact form

Post by TheBrandon »

slaterino wrote:Sorry can I just check one last thing. Will I have to repeat the function for every variable? Say for instance I wanted to clean the name, email and subject fields would I then have to have functions for each variable? I can't tell if I'm being a bit stupid by asking this but hey, tis always worth an ask!
You won't need an entirely new function for each variable, but like mattpointblank said:
Then instead of using $_GET['variable'], I just use cleanGet('variable').
You don't need to create a new function for each, but you will need to execute the function for each variable (if that is your intention).
User avatar
Syntac
Forum Contributor
Posts: 327
Joined: Sun Sep 14, 2008 7:59 pm

Re: Retaining information in php contact form

Post by Syntac »

Don't do a refresh if they put wrong details in. Try this:

Code: Select all

<textarea name="blah"><?php echo @$_POST["blah"]; ?></textarea>
The @ is to keep it from throwing a notice if $_POST["blah"] isn't set.
mattpointblank
Forum Contributor
Posts: 304
Joined: Tue Dec 23, 2008 6:29 am

Re: Retaining information in php contact form

Post by mattpointblank »

slaterino wrote:Sorry can I just check one last thing. Will I have to repeat the function for every variable? Say for instance I wanted to clean the name, email and subject fields would I then have to have functions for each variable? I can't tell if I'm being a bit stupid by asking this but hey, tis always worth an ask!
If you're going to apply the same function to several form fields, you could do something like this:

Code: Select all

 
$cleanvars = array_map('cleanPost', $_POST); // applies cleanPost() function to all $_POST variables
extract($cleanvars,EXTR_PREFIX_ALL,'form'); // extracts all $_POST variables into usable $form_ prefixed variables
 
The comments should make it clear, but basically, these two lines, when used with the cleanPost function posted above, will turn all of the form fields on your page into cleaned up variables, with "form_" prefixed at the start (you can change this in the final argument of the extract() function on the second line).

For example, if you have this code:

Code: Select all

 
<input name="subject" />
 
And then process it using the PHP above, you'll end up with a variable called $form_subject which will have been cleaned up using that function.

Hope this is useful to anyone.
Post Reply