Working With Forms
Working With Forms
Overview of forms
A form is a document with blank fields for a user to insert or
update data. The user’s data is stored in the database and
retrieved anytime.
Contact Forms
Search Forms
Login Forms
Registration Forms
POST method
POST is a superglobal method, which collects form data and
submits it to the HTTP server. The data entered is encoded,
and the content is hidden. POST method has a global scope,
and data is accessed from any script.
It can be in the same script where the HTML form is, or it can
be on a different script. In this case, we will have the PHP
code in the same script as the HTML form.
<?php
# Check if name and email fileds are empty
if(empty($_POST['name']) && empty($_POST['email'])){
# If the fields are empty, display a message to the user
echo " <br/> Please fill in the fields";
# Process the form data if the input fields are not empty
}else{
$name= $_POST['name'];
$email= $_POST['email'];
echo ('Your Name is: '. $name. '<br/>');
echo ('Your Email is:' . $email. '<br/>');
}
?>
$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).
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;
?>
In the example above, since z is a variable present within the $GLOBALS array,
it is also accessible from outside the function!
OUTPUT:
100
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'];
?>
OUTPUT:
/demo/demo_global_server.php
35.194.26.41
35.194.26.41
https://tryphp.w3schools.com/showphp.php?filename=demo_global_server
Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:93.0) Gecko/20100101 Firefox/93.0
/demo/demo_global_server.php
The following table lists the most important elements that can go inside
$_SERVER:
Element/Code Description
PHP $_REQUEST
PHP $_REQUEST is a PHP super global variable which is used to collect data after
submitting an HTML form.
The example below shows a form with an input field and a submit button. When
a user submits the data by clicking on "Submit", the form data is sent to the file
specified in the action attribute of the <form> tag. In this example, we point to
this file itself for processing form data. If you wish to use another PHP file to
process form data, replace that with the filename of your choice. Then, we can
use the super global variable $_REQUEST to collect the value of the input field:
Example
<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>
OUTPUT:
Submit
Name:
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.
The example below shows a form with an input field and a submit button. When
a user submits the data by clicking on "Submit", the form data is sent to the file
specified in the action attribute of the <form> tag. In this example, we point to
the file itself for processing form data. If you wish to use another PHP file to
process form data, replace that with the filename of your choice. Then, we can
use the super global variable $_POST to collect the value of the input field:
Example
<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>
OUTPUT:
Submit
Name:
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>
</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>
OUTPUT:
Test & GET
Introduction
The global predefined variable $_FILES is an associative array containing items
uploaded via HTTP POST method. Uploading a file requires HTTP POST method form
with enctype attribute set to multipart/form-data.
$HTTP_POST_FILES also contains the same information, but is not a superglobal, and
now been deprecated
The _FILES array contains following properties −
$_FILES['file']['name'] - The original name of the file to be uploaded.
$_FILES['file']['type'] - The mime type of the file.
$_FILES['file']['size'] - The size, in bytes, of the uploaded file.
$_FILES['file']['tmp_name'] - The temporary filename of the file in which the uploaded
file was stored on the server.
$_FILES['file']['error'] - The error code associated with this file upload.
Following test.html contains a HTML form whose enctype is set to multiform/form-data.
It also has an input file element which presents a button on the form for the user to
select file to be uploaded.
<form action="testscript.php" method="POST"
enctype="multipart/form-data">
<input type="file" name="file">
<input type ="submit" value="submit">
</form>
The PHP script is as follows:
Example
<?php
echo "Filename: " . $_FILES['file']['name']."<br>";
echo "Type : " . $_FILES['file']['type'] ."<br>";
echo "Size : " . $_FILES['file']['size'] ."<br>";
echo "Temp name: " . $_FILES['file']['tmp_name'] ."<br>";
echo "Error : " . $_FILES['file']['error'] . "<br>";
?>
Output
This will produce following result −
Filename: hello.html
Type : text/html
Size : 56
Temp name: C:\xampp\tmp\php32CE.tmp
Error : 0
In this article, We will discuss two methods for reading console or user
input in PHP:
Method 1: Using readline() function is a built-in function in PHP.
This function is used to read console input.
The following things can be achieved by readline() function:
// For input
// Hello World
// For output
echo $a;
?>
Output:
Enter a string: GeeksforGeeks
GeeksforGeeks
By default, the data type of the variable accepted through readline()
function is string. So for any other data type, we have
to typecast it explicitly as described below.
PHP
<?php
// Input section
// $a = 10
// $b = 9.78
$b = (float)readline('Enter a floating'
?>
Output:
Enter an integer: 10
Enter a floating point number: 9.78
Entered integer is 10 and entered float is 9.78
We can achieve the same things without prompting the user
also:
$a = readline();
In this case, as soon as the user hits enter, the entered value is
stored in the variable a.
Accept multiple space separated inputs: For this, we use
another function explode() together with readline(). The first
argument of explode() is the delimiter we want to use. In the above
example, the delimiter is space. The second argument is
the readline() function. Here also the data type of $var1 and $var2
will be string. So we have to separately typecast them for other data
types. In the above example, the typecasting is shown for integers.
PHP
<?php
// Input 10 20
list($var1, $var2)
// Typecasting to integers
$var1 = (int)$var1;
$var2 = (int)$var2;
?>
Output:
The sum of 10 and 20 is 30
<?php
// For input
// 1 2 3 4 5 6
// For output
print_r($arr);
/*Array
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
)*/
?>
Output:
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
)
Method 2: Using fscanf() function works same as the fscanf() function
in C. We can read 2 integers from Keyboard(STDIN) as below:
This is different from the previous method
PHP
<?php
// Input 1 5
// Output
?>
Output:
The sum of 1 and 5 is 6
Comparison between two methods:
No need to use explicit typecasting for fscanf() function, because
it is done by the format specifiers , e.g. %d, %f, %c etc.
scanf() function is much faster than the readline() function.
How to Use PHP in
HTML English
In this article, I'll show you how to use PHP code in your HTML pages. It’s
aimed at PHP beginners who are trying to strengthen their grip on the world's
most popular server-side scripting language.
Since PHP is a server-side scripting language, the code is interpreted and run
on the server side. For example, if you add the following code in
your index.html file, it won’t run out of the box.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
</body>
</html>
If you want to run your HTML files as PHP, you can tell the server to run
your .html files as PHP files, but it's a much better idea to put your mixed
PHP and HTML code into a file with the .php extension.
Let’s have a look at a very simple example, which displays a message using
PHP code. Create the index.php file with the following contents under your
document root.
<!DOCTYPE html>
<html>
<head>
<title>How to put PHP in HTML - Simple Example</title>
</head>
<body>
</body>
</html>
The important thing in the above example is that the PHP code is wrapped by
the PHP tags.
And, if you look at the page source, it should look like this:
As you can see, the PHP code is parsed and executed on the server side, and
it's merged with HTML before the page is sent to the client browser.
Let’s have a look at another example:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div>
Today’s date is <b><?php echo date('Y/m/d') ?></b> and it’s a <b><?php echo
</div>
</body>
</html>
This will output the current date and time, so you can use PHP code between
the HTML tags to produce dynamic output from the server. It’s important to
remember that whenever the page is executed on the server side, all the code
between the <?php and ?> tags will be interpreted as PHP, and the output
will be embedded with the HTML tags.
In fact, there’s another way you could write the above example, as shown in
the following snippet.
<!DOCTYPE html>
<html>
<head>
<title>How to put PHP in HTML- Date Example</title>
</head>
<body>
<div>
<?php
<b>'.date('l').'</b> today!';
?>
</div>
</body>
</html>
In the above example, we’ve used the concatenation feature of PHP, which
allows you to join different strings into one string. And finally, we’ve used
the echo construct to display the concatenated string.
The output is the same irrespective of the method you use, as shown in the
following screenshot.
The overall structure of the PHP page combined with HTML and PHP code
should look like this:
<!DOCTYPE html>
<html>
<head>
<title>...</title>
</head>
<body>
HTML...
HTML...
HTML...
</body>
</html>
How to Use PHP Loops in Your
HTML Page
Iterating through the arrays to produce HTML content is one of the most
common tasks you'll encounter while writing PHP scripts. In this section,
we’ll see how you could iterate through an array of items and generate
output.
In this example, we’ll initialize the array with different values at the
beginning of the script itself.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php
?>
<h1>List of Employees</h1>
<ul>
<?php } ?>
</ul>
</body>
</html>
Firstly, we’ve initialized the array at the beginning of our script. Next, we’ve
used the foreach construct to iterate through the array values. And finally,
we’ve used the echo construct to display the array element value.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php
$total = count($employees);
?>
<h1>List of Employees</h1>
<ul>
<?php
$i = 0;
?>
<?php } ?>
</ul>
</body>
</html>
And the output will be the same. So that’s how you can
use foreach and while loops to generate HTML content based on PHP
arrays.
How to Use PHP Short Tags
In the examples we’ve discussed so far, we’ve used the <?php as a starting
tag everywhere. In fact, PHP comes with a variation, <?= , which you could
use as a short-hand syntax when you want to display a string or value of the
variable.
Let’s revise the example with the short-hand syntax which we discussed
earlier.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
</body>
</html>
As you can see, we can omit the echo or print construct while displaying a
value by using the shorthand syntax. The shorthand syntax is short and
readable when you want to display something with echo or print .
Where,
To use hidden fields and pass the name of the continents in a PHP
script.
<html>
<head>
</head>
<body>
<option>AUSTRALIA</option>
<option>EUROPE</option>
<input type=”submit”>
</form>
</body>
</html>
<?php
// Redirect browser
header("Location: http://www.geeksforgeeks.org");
exit;
?>
Redirection is done by outputting a Location using PHP using the header() function.
Here's how to redirect to a page called thanks.html:
header( "Location: thanks.html" );
Don't output any content to the browser via echo() or print(), or by including HTML
markup outside the <?php ... ?> tags before calling header().
Example
Here's a quick example of a form handler script that redirects to a thank - you page: