unit 6 (part 1) PHP Global Variables and form validate
unit 6 (part 1) PHP Global Variables and form validate
unit 6 (part 1) PHP Global Variables and form validate
Some predefined variables in PHP are "superglobals", which means that they are always
accessible, regardless of scope - and you can access them from any function, class or file without
having to do anything special.
$GLOBALS
$_SERVER
$_REQUEST
$_POST
$_GET
$_FILES
$_ENV
$_COOKIE
$_SESSION
PHP $GLOBALS
$GLOBALS is a PHP super global variable which is used to access global variables from
anywhere in the PHP script (also from within functions or methods).
PHP stores all global variables in an array called $GLOBALS[index]. The index holds the
name of the variable.
The example below shows how to use the super global variable $GLOBALS:
Example
<?php
$x = 75;
$y = 25;
function addition() {
$GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y'];
}
addition();
echo $z;
?>
PHP $_SERVER
$_SERVER is a PHP super global variable which holds information about headers, paths, and
script locations.
The example below shows how to use some of the elements in $_SERVER:
Example
<?php
echo $_SERVER['PHP_SELF'];
echo "<br>";
echo $_SERVER['SERVER_NAME'];
echo "<br>";
echo $_SERVER['HTTP_HOST'];
echo "<br>";
echo $_SERVER['HTTP_REFERER'];
echo "<br>";
echo $_SERVER['HTTP_USER_AGENT'];
echo "<br>";
echo $_SERVER['SCRIPT_NAME'];
?>
PHP $_REQUEST
PHP $_REQUEST is a PHP super global variable which is used to collect data after submitting
an HTML form.
<html>
<body>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input field
$name = $_REQUEST['fname'];
if (empty($name)) {
echo "Name is empty";
} else {
echo $name;
}
}
?>
</body>
</html>
Information sent from a form with the GET method is visible to everyone (all variable names
and values are displayed in the URL). GET also has limits on the amount of information to send.
The limitation is about 2000 characters. However, because the variables are displayed in the
URL, it is possible to bookmark the page. This can be useful in some cases.
Note: GET should NEVER be used for sending passwords or other sensitive information!
Information sent from a form with the POST method is invisible to others (all names/values are
embedded within the body of the HTTP request) and has no limits on the amount of information
to send.
Moreover POST supports advanced functionality such as support for multi-part binary input
while uploading files to server.
However, because the variables are not displayed in the URL, it is not possible to bookmark the
page.
PHP $_POST
PHP $_POST is a PHP super global variable which is used to collect form data after submitting
an HTML form with method="post". $_POST is also widely used to pass variables.
<html>
<body>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input field
$name = $_POST['fname'];
if (empty($name)) {
echo "Name is empty";
} else {
echo $name;
}
}
?>
</body>
</html>
PHP $_GET
PHP $_GET is a PHP super global variable which is used to collect form data after submitting an
HTML form with method="get".
<html>
<body>
<a href="test_get.php?subject=PHP&web=W3schools.com">Test $GET</a>
</body>
</html>
When a user clicks on the link "Test $GET", the parameters "subject" and "web" are sent to
"test_get.php", and you can then access their values in "test_get.php" with $_GET.
Example
<html>
<body>
<?php
echo "Study " . $_GET['subject'] . " at " . $_GET['web'];
?>
</body>
</html>
Example
Below example shows the form with some specific actions by using post method.
<html>
<head>
<title>PHP Form Validation</title>
</head>
<body>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = test_input($_POST["name"]);
$email = test_input($_POST["email"]);
$website = test_input($_POST["website"]);
$comment = test_input($_POST["comment"]);
$gender = test_input($_POST["gender"]);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<tr>
<td>E-mail:</td>
<td><input type = "text" name = "email"></td>
</tr>
<tr>
<td>Specific Time:</td>
<td><input type = "text" name = "website"></td>
</tr>
<tr>
<td>Class details:</td>
<td><textarea name = "comment" rows = "5" cols = "40"></textarea></td>
</tr>
<tr>
<td>Gender:</td>
<td>
<input type = "radio" name = "gender" value = "female">Female
<input type = "radio" name = "gender" value = "male">Male
</td>
</tr>
<tr>
<td>
<input type = "submit" name = "submit" value = "Submit">
</td>
</tr>
</table>
</form>
<?php
echo "<h2>Your Given details are as :</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>
</body>
Form Validation in PHP
An HTML form contains various input fields such as text box, checkbox, radio buttons, submit
button, and checklist, etc. These input fields need to be validated, which ensures that the user has
entered information in all the required fields and also validates that the information provided by
the user is valid and correct.
There is no guarantee that the information provided by the user is always correct. PHP
validates the data at the server-side, which is submitted by HTML form
. You need to validate a few things:
1. Empty String
2. Validate String
3. Validate Numbers
4. Validate Email
5. Validate URL
6. Input length
Empty String
The code below checks that the field is not empty. If the user leaves the required field empty, it
will show an error message. Put these lines of code to validate the required field.
if (empty($_POST["name"])) {
$errMsg = "Error! You didn't enter the Name.";
echo $errMsg;
} else {
$name = $_POST["name"];
}
Validate String
The code below checks that the field will contain only alphabets and whitespace, for example -
name. If the name field does not receive valid input from the user, then it will show an error
message:
if ( $length !=10) {
$ErrMsg = "Mobile must have 10 digits.";
echo $ErrMsg;
} else {
echo "Your Mobile number is: " .$mobileno;
}
Validate URL
The below code validates the URL
of website provided by the user via HTML form. If the field does not contain a valid URL, the
code will display an error message, i.e., "URL is not valid".
$websiteURL = $_POST["website"];
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-
9+&@#\/%=~_|]/i",$website)) {
$websiteErr = "URL is not valid";
echo $websiteErr;
} else {
echo "Website URL is: " .$websiteURL;
}
Button Click Validate
The below code validates that the user click on submit button and send the form data to the
server one of the following method - get or post.
if (isset ($_POST['submit']) {
echo "Submit button is clicked.";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
echo "Data is sent using POST method ";
}
} else {
echo "Data is not submitted";
}
Note: Remember that validation and verification both are different from each other.
Now we will apply all these validations to an HTML form to validate the fields. Thereby you can
learn in detail how these codes will be used to validation form.
Create a registration form using HTML
and perform server-side validation. Follow the below instructions as given:
Create and validate a Registration form
<!DOCTYPE html>
<html>
<head>
<style>
.error {color: #FF0001;}
</style>
</head>
<body>
<?php
// define variables to empty values
$nameErr = $emailErr = $mobilenoErr = $genderErr = $websiteErr = $agreeErr = "";
$name = $email = $mobileno = $gender = $website = $agree = "";
//String Validation
if (emptyempty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = input_data($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only alphabets and white space are allowed";
}
}
//Email Validation
if (emptyempty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = input_data($_POST["email"]);
// check that the e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
//Number Validation
if (emptyempty($_POST["mobileno"])) {
$mobilenoErr = "Mobile no is required";
} else {
$mobileno = input_data($_POST["mobileno"]);
// check if mobile no is well-formed
if (!preg_match ("/^[0-9]*$/", $mobileno) ) {
$mobilenoErr = "Only numeric value is allowed.";
}
//check mobile no length should not be less and greator than 10
if (strlen ($mobileno) != 10) {
$mobilenoErr = "Mobile no must contain 10 digits.";
}
}
//URL Validation
if (emptyempty($_POST["website"])) {
$website = "";
} else {
$website = input_data($_POST["website"]);
// check if URL address syntax is valid
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-
9+&@#\/%=~_|]/i",$website)) {
$websiteErr = "Invalid URL";
}
}
//Checkbox Validation
if (!isset($_POST['agree'])){
$agreeErr = "Accept terms of services before submit.";
} else {
$agree = input_data($_POST["agree"]);
}
}
function input_data($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>Registration Form</h2>
<span class = "error">* required field </span>
<br><br>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" >
Name:
<input type="text" name="name">
<span class="error">* <?php echo $nameErr; ?> </span>
<br><br>
E-mail:
<input type="text" name="email">
<span class="error">* <?php echo $emailErr; ?> </span>
<br><br>
Mobile No:
<input type="text" name="mobileno">
<span class="error">* <?php echo $mobilenoErr; ?> </span>
<br><br>
Website:
<input type="text" name="website">
<span class="error"><?php echo $websiteErr; ?> </span>
<br><br>
Gender:
<input type="radio" name="gender" value="male"> Male
<input type="radio" name="gender" value="female"> Female
<input type="radio" name="gender" value="other"> Other
<span class="error">* <?php echo $genderErr; ?> </span>
<br><br>
Agree to Terms of Service:
<input type="checkbox" name="agree">
<span class="error">* <?php echo $agreeErr; ?> </span>
<br><br>
<input type="submit" name="submit" value="Submit">
<br><br>
</form>
<?php
if(isset($_POST['submit'])) {
if($nameErr == "" && $emailErr == "" && $mobilenoErr == "" && $genderErr == "" && $webs
iteErr == "" && $agreeErr == "") {
echo "<h3 color = #FF0001> <b>You have sucessfully registered.</b> </h3>";
echo "<h2>Your Input:</h2>";
echo "Name: " .$name;
echo "<br>";
echo "Email: " .$email;
echo "<br>";
echo "Mobile No: " .$mobileno;
echo "<br>";
echo "Website: " .$website;
echo "<br>";
echo "Gender: " .$gender;
} else {
echo "<h3> <b>You didn't filled up the form correctly.</b> </h3>";
}
}
?>
</body>
</html>