I know this has been asked before but I really can't relate any of the threads to my code. A'll I'm trying to do is get this quick PHP form to echo the error messages in the form as appose to a new page. (I'm sure you know what I mean)

The Form:

<form method="post" action="/includes/php/forms/contact/validation/contact.php" name="contactform" id="contactform" class="contact-form">
  <h2 class="form-title">Initial Information</h2>
  <fieldset>
    <!-- full-name -->
    <section class="form-section">
      <label name="first" class="left">Your Full Name</label>
      <p class="right required">*</p>
      <input name="name" id="name" type="text" value="">
    </section>
  </fieldset>
  <input class="form-submit" id="submit" value="Submit" type="submit">
</form>

The PHP:

// Initial Information.
$name = $_POST['name'];

// Error Messages
if(trim($name) == '') {
    echo '<div class="error_message">Attention! You must enter your full name.</div>';
    exit();
}

I've tried to cut down the code to the relevant parts, but what's confusing me is I can't find an example of the if(trim etc...) being used in any tutorials, so I'm not entiely sure that's correct.

Any info on where to go from here would be appreciated.

Recommended Answers

All 3 Replies

There are many tutorials out there but they might vary in completeness since they often omit some parts to emphasizes others. But your question is spot on. If I got it right you are asking about what to do with the posted values to use them securely.

The trim is actually a good function to get rid of extraneous spaces in before and after the actual text since the user might not be aware of them and they might cause some trouble. But more important is to escape and sanitize the data sent form the form.

The functions you will use depend on the context the value goes to. If you intend to store the value to a database, you tipically escape it (e.g. using mysqli_real_escape_string). If the value goes to the URL then you use urlencode function. If you stick the value into html use htmlspecialchars function etc.
You also have php filters you can use or filter_var.

And also you can also add your custom validating functions (e.g. for checking local phone numbers).

Member Avatar for diafol

It always a temptation to send a form to itself but that can cause a number of problems such as the refresh/reload/F5 issue - which resends the data. So, the usual workaround is to send to a formhandler page and then to redirect back to the form or to another page, depending on the result.

Because web pages are stateless, the usual way of sending data back to the form page is via session variables.

formhandler.php
session_start();
...
if(....){
    $_SESSION['formerror']['msg']['username'] = '...';
    $_SESSION['formerror']['data']['username'] = '...';
}
if(....){
    $_SESSION['formerror']['msg']['email'] = '...';
    $_SESSION['formerror']['data']['email'] = '...';
}
header('Location: formpage.php');
formpage.php
session_start();
...
if(isset($_SESSION['form_error'])){
    $msg = $_SESSION['formerror']['msg'];
    $data = $_SESSION['formerror']['data'];
    unset($_SESSION['formdata']);
}

//now insert/test data and msgs to relevant places

Well, that's a little contrived - sure you could de-bloat it

Another way would be to use bitwise operators for error messages:

formhandler.php
session_start();
$errorTotal = 0;
if(....){
    $errorTotal += 1; 
}
if(....){
    $errorTotal += 2;
}
if(....){
    $errorTotal += 4;
}
if(....){
    $errorTotal += 8;
}

//either store in session var or in the querystring
$qs = ($errorTotal) ? "?err=$errorTotal" : "";
header("Location: formpage.php$qs");
formpage.php
$err = 0;
if(isset($_GET['err'])){
    $err = intval($_GET['err']);
}

if($err & 1)echo "...";
if($err & 2)echo "...";
if($err & 4)echo "...";

//etc

This is obviously not production code - just something to show different approaches. I quite like the last one BUT, it does cause some degree of separation of the error number and the error description.

Thanks for the replies guys.

Managed to fix this using

<?php
if($_POST['formSubmit'] == "Submit")
{
    $errorMessage = "";

    if(empty($_POST['formMovie']))
    {
        $errorMessage .= "<li>You forgot to enter a movie!</li>";
    }
    if(empty($_POST['formName']))
    {
        $errorMessage .= "<li>You forgot to enter a name!</li>";
    }

    $varMovie = $_POST['formMovie'];
    $varName = $_POST['formName'];

    if(empty($errorMessage)) 
    {
        $fs = fopen("mydata.csv","a");
        fwrite($fs,$varName . ", " . $varMovie . "\n");
        fclose($fs);

        header("Location: thankyou.html");
        exit;
    }
}
?>

And simply including it at the top of the page. Worked fine, suprisingly.

Appreciate the help.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.