This is my summary of the W3 Schools’ documentation, with emphasis of the weird parts.
The PHP superglobals $_GET
'get'
and $_POST
'post'
are used to collect and send data such as for a form.
<form action="welcome.php" method="post">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
When the user clicks the submit input button, execution will go to welcome.php
and assign the value provided by the user for the Name to $_POST['name']
and the email to $_POST['email']
.
$_GET
and $_POST
are both arrays.
Superglobal: you can access it from any file and any scope at any time.
$_GET
: visible to all users, with a size limit. Less secure, but lets a user save all their presets when they reload the page due to an internet issue, or it also lets presets be carried over when you share a link.
$_POST
: invisible to others with no limit. secure. Can’t be bookmarked. Supports multipart binary input. Preferred for forms.
If you want the form to reload to its current page, you can use the following tag:
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
htmlspecialchars()
protects against xss attacks.
If you want to clean the user inputs from potential attacks, you can do so with the following:
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}function lintUserNameFor($stringName, &$hasError) {
$name = test_input($stringName);
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
$hasError = true;
echo $nameErr;
}
}function lintEmailFor($stringEmail, &$hasError) {
$email = test_input($stringEmail);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
$hasError = true;
echo "<h1>" . $emailErr . "</h1>";
}
}function lintURL($url, &$hasError) {
$website = test_input($_POST["website"]);
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {
$websiteErr = "Invalid URL";
$hasError = true;
}
}
You can use these functions to check if a username, email or url are valid.
Lets say the user clicks the submit button and but they made a mistake. You wouldn’t clear their inputs. That would be annoying, because they’d have to retype them.
Here is how you keep their inputs for after they click the submit button. You set the value equal to a php script that will return the name property as a variable.
E-mail: <input type="text" name="email" value="<?php echo $email;?>">
If you want the user to be able to edit inputs as well, you can have something like so:
<input type="text" name="email" value="<?
echo $_POST['editthis'] ? $_POST['email'] : $email;
?>">