-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path004-validation.php
96 lines (82 loc) · 2.29 KB
/
004-validation.php
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
<?php
/**
* SCRIPT LOGIC
* ============
*
* here at the beginning of the file we can do all the heavy logic computation for our script.
* the point is to set variables, check variables and change variables value.
*
* - all the operations are done here
* - simple variables are filled up for the presentation
* - no output is sent, no "echo" is being used here!
*
*/
// setup initial values, this is the "default status" of the script
$showForm = true;
$showResult = false;
$showErrors = false;
$fieldValue = '';
// a "constant" represent some non modificable data we need to use inside our script.
define('CORRECT_ANSWER', 'mpeg');
// perform the logic only when the form is sent
if ($_SERVER['REQUEST_METHOD'] == "POST") {
// data gathering
$fieldValue = $_POST['answer'];
// data validation
if ($fieldValue == CORRECT_ANSWER) {
$showForm = false;
$showResult = true;
} else {
$showErrors = true;
}
}
/**
* SCRIPT PRESENTATION
* ===================
*
* down here there is almost HTML with some "PHP placeholders" inside.
* the main pourpose is to **present the output**.
*
* >
* > !!! there is almost no logic in the following code !!!
* >
*/
?>
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>PHP004 - Single Script Form Example</title>
</head>
<body>
<?php
/**
* SHOW THE FORM AND ERROR MESSAGES
*/
if ($showForm): ?>
<form action="004-validation.php" method="post">
<?php if ($showErrors): ?>
<div style="color:red">
"<?= $fieldValue ?>" is not the correct answer!
</div>
<?php endif; ?>
<div>
<label for="answer">Who's the best?</label><br>
<input type="text" name="answer" value="<?= $fieldValue ?>">
<input type="submit" value="send"></input>
</div>
</form>
<?php endif; ?>
<?php
/**
* SHOW THE "RESULT PAGE"
*/
if ($showResult) {
// strings coded with double quotes can contains and evaluate variables:
echo "<p>Yeah! <b>$fieldValue</b> is the best!</p>";
// but it is always better to code strings with single quotes like this:
echo '<p><a href="004-validation.php">« Back</a></p>';
}
?>
</body>
</html>