1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
<?php

/* 
    Example form submission script for http://security.stackexchange.com/questions/4094/attack-vectors-in-posting-variables-from-one-php-script-to-the-next/4095#4095 
*/

/*
    function to remove non-alpha characters from a supplied input
*/
function clean_alpha($input) {
    return preg_replace("/[^a-zA-Z]+/","", $input);
}

/* 
   function to print a form. done in a function so we can reuse code
   as the form submission may fail
*/
function print_form($name) {
    // output validation
    $name = htmlentities($name);

    print <<<EOF
<form action="" method="POST">
    <input type="text" name="name" value="$name" />
    <input type="submit" value="Submit" />
</form>
EOF;
}

?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
                      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> 
<head><title>Example script for Security StackExchange</title></head>
<body>

<h1>Example for Security StackExchange</h1>
<p>There is only correct value for the form below - "wicky". Enter anything else and you'll get an error.</p>

<?php
// Let's see if someone has posted to us
if (isset($_POST['name'])) {
    // input validation - name should only contains alpha characters
    // there should be a length check here too to make sure it's
    // not bigger than the field in the db, etc
    // if this were another language you would certainly need a length check
    // to prevent things like buffer overflows
    $name = clean_alpha($_POST['name']);
    
    // we should have $name var with only alpha characters. should be safe?
    // let's use it for something
    if ($name == "wicky") {
        print "<p>Hello Wicky, how are you?</p>";
        print "<p>If I were a real script I would go and put stuff in a database now.</p>";
    } else {
        print "<p>You're not Wicky, try again.</p>";
        print_form($name); // call the print_form function and pass the name with it
    }
} else {
    // nothing was sent in the $_POST superglobal so we'll assume the form
    // hasn't been submitted yet and just render the form
    print_form();
}

?>

</body>
</html>