Syllabus
Chapter 2 Handling Html Form with Php
2.1 Capturing Form Data
2.2 Dealing with Multi-value filed
2.3 Generating File uploaded form
2.4 Redirecting a
form after submission
HTML
Form:
The HTML <form> element defines a form that is used
to collect user input:
<form>
.
form elements.
.
form elements.
.
</form>
</form>
An HTML form contains form elements.
Form elements are different types of input
elements, like text fields, checkboxes, radio buttons, submit buttons, and
more.
The
<input> Element:
The <input> element is the most important form
element.
The <input> element can be displayed in several
ways, depending on the type attribute.
Here are some examples:
Type
|
Description
|
<input type="text">
|
Defines a one-line text input field
|
<input type="radio">
|
Defines a radio button (for selecting one
of many choices)
|
<input type="submit">
|
Defines a submit button (for submitting
the form)
|
Example:
<html>
<body>
<form>
First name:<br>
<input type="text"
name="firstname"><br>
Last name:<br>
<input type="text" name="lastname"><br>
<input type="radio"
name="gender" value="male" checked> Male<br>
<input type="radio"
name="gender" value="female"> Female<br>
<input type="radio"
name="gender" value="other"> Other <br>
<input type="submit"
value="Submit">
</form>
</body>
</html>
2.1
Capturing Form Data
First of all, the form's action attribute needs to contain the URL
of the PHP script that will handle the form.
For example:
<form
action="form_handler.php"method="post">
When users send their forms, their data is sent to the server and
the form_handler.php script is run.
The script then needs to read the form data and act on it.
Superglobal Array
|
Description
|
$_GET
|
Contains a list of all the field names and values sent by a form
using the get method
|
$_POST
|
Contains a list of all the field names and values sent by a form
using the post method
|
$_REQUEST
|
Contains the values of both the $_GET and $_POST arrays combined,
along with the values of the $_COOKIE superglobal array
|
Each of these three superglobal arrays contains the field names
from the sent form as array keys, with the field values themselves as array
values.
For example, suppose you created a form using the get method, and
that form contained the following control:
<input type="text" name="emailAddress"value=""/
>
You could then access the value that the user entered into that
form field using either the $_GET or the $_REQUEST superglobal:
$email = $_GET["emailAddress"];
$email = $_REQUEST["emailAddress"];
Example
In this example, you create a simple user registration form, then
write a form handler script that reads the field values sent from the form and
displays them in the page.
First, create the registration form.
Save the following HTML code as capformdata.html in your document
root folder:
<html>
<body>
<form action="capformdata.php"
method="get">
<label for="firstName">First name</label>
<input type="text" name="firstName"
id="firstName" value="" />
<label for="lastName">Last name</label>
<input type="text" name="lastName"
id="lastName" value="" />
<label for="genderMale">male ?</label>
<input type="radio" name="gender"
id="genderMale" value="M" />
<label for="genderFemale">female?</label>
<input type="radio" name="gender"
id="genderFemale" value="F" />
<input type="submit" value="Submit"
id="moveRight">
</form>
</body>
</html>
Next, save the
following script as capformdata.php in your document root, the folder where you
placed capformdata.html.
<html>
<body>
<?php
$first=$_GET["firstName"];
$last=$_GET["lastName"];
$sex=$_GET["gender"];
if($sex == "F")
echo "$first $last is
a female.<br />";
else
echo "$first $last is
a male.<br />";
?>
</body>
</html>
Fill in the fields
in the form, then click the Submit button.
If all goes well, you should see a page displaying the data that
you just entered.
the process of capturing and displaying the submitted form data is
really quite simple.
Because the form is sent using the post method, the script extracts
the form field values from the $_POST superglobal array, and displays each
field value using echo.
2.2
Dealing with Multi-value filed
The following form
fields are capable of sending multiple values to the server:
<html>
<body>
<form
action="multiValue.php" method="post">
<h2>
<label>Enter Your Name: </label></h2>
<input type="text"
name="Name" id="Name" /></br>
<h2>What
whould like to eat?</h2>
<label>Apple</label>
<input
type="checkbox" name="fruit[]" value="Apple"
/>
<label>Banana</label>
<input
type="checkbox" name="fruit[]" value="Banana"
/>
<label>Jackfruit</label>
<input
type="checkbox" name="fruit[]" value="Jackfruit"
/>
<label>Orange</label>
<input
type="checkbox" name="fruit[]" value="orange"
/>
<label>Mango</label>
<input
type="checkbox" name="fruit[]" value="Mango"
/>
<h2>What
are your favorite soft drink?</h2>
<select
name="favor[]" size = "4" multiple =
"multiple">
<option
value="coke">Coke</option>
<option
value="sprite">Sprite</option>
<option value="orange
juice">Orange Juice</option>
<option value="apple juice">Apple
Juice</option>
<option
value="water">Water</option>
</select>
<p>Note
that hold a <b>ctrl</b> key to choose more than one item.</p>
<input
type="submit" name="submit" id="moveRight"
value="Submit" />
<input
type="reset" name="reset" value="Reset" style="margin-left:
20px;display:inline;" />
</form>
</body>
</html>
Php
script to process multiple values:
<html>
<body>
<?php
$fruitlist=$_POST["fruit"];
//assign an array to a local array
$favorlist=$_POST["favor"];
$name=$_POST["Name"];
echo
$name." Your favorite drink from
checkboxes are <br />";
foreach($fruitlist
as $fruit)
echo $fruit . "<br /> ";
echo
"<br />";
echo
$name." Your favorite drink from
pull-down menu are <br /> ";
foreach($favorlist
as $favor)
echo $favor. "<br />";
?>
</body>
</html>
2.3
Generating File uploaded form
move_uploaded_file() : Moves an
uploaded file to a new location.
syntax:
move_uploaded_file (
string $filename , string $destination )
This function checks
to ensure that the file designated by filename is a valid upload file (meaning
that it was uploaded via PHP's HTTP POST upload mechanism). If the file is
valid, it will be moved to the filename given by destination.
formtoup.html
<form enctype="multipart/form-data" action="formtoup.php" method="POST">
<input type="hidden" name="MAX_FILE_SIZE"
value="100000" />
Choose a file to upload: <input name="uploadedfile"
type="file" /><br />
<input type="submit" value="Upload File"
/>
</form>
formtoup.php
<?php
$target_path = "d:/uploads/";
$target_path = $target_path . basename(
$_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'],
$target_path)) {
echo "The file ". basename(
$_FILES['uploadedfile']['name']).
" has been uploaded";
} else{
echo "</br>There was an error uploading
the file, please try again!";
}
?>
Uploading Files with PHP
In this tutorial we will learn how to upload files on remote server using a Simple HTML form and PHP. You can upload any kind of file like images, videos, ZIP files, Microsoft Office documents, PDFs, as well as executables files and a wide range of other file types.
Step 1: Creating an HTML form to upload the
file
The
following example will create a simple HTML form that can be used to upload
files.
<html>
<head>
<title>File Upload Form</title>
</head>
<body>
<form action="upmanager.php" method="post" enctype="multipart/form-data">
<h2>Upload File</h2>
<label for="fileSelect">Filename:</label>
<input type="file" name="photo" id="fileSelect">
<input type="submit" name="submit" value="Upload">
<p><strong>Note:</strong> Only .jpg, .jpeg, .gif, .png formats allowed to a max size of 5 MB.</p>
</form>
</body>
</html>
<head>
<title>File Upload Form</title>
</head>
<body>
<form action="upmanager.php" method="post" enctype="multipart/form-data">
<h2>Upload File</h2>
<label for="fileSelect">Filename:</label>
<input type="file" name="photo" id="fileSelect">
<input type="submit" name="submit" value="Upload">
<p><strong>Note:</strong> Only .jpg, .jpeg, .gif, .png formats allowed to a max size of 5 MB.</p>
</form>
</body>
</html>
Note: In
addition to a file-select field the upload form must use the HTTP post method and must contain
an enctype="multipart/form-data" attribute. This attribute
ensures that the form data is encoded as mulitpart MIME data — which is
required for uploading the large quantities of binary data such as image,
audio, video, etc
Step 2: Processing the uploaded file
Here's
the complete code of our "upload-manager.php" file. It will store the
uploaded file in a "upload" folder on permanent basis as well as
implement some basic security check like file type and file size to ensure that
users upload the correct file type and within the allowed limit.
<?php
// Check if the form was submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Check if file was uploaded without errors
if(isset($_FILES["photo"]) && $_FILES["photo"]["error"] == 0){
$allowed = array("jpg" => "image/jpg", "jpeg" => "image/jpeg", "gif" => "image/gif", "png" => "image/png");
$filename = $_FILES["photo"]["name"];
$filetype = $_FILES["photo"]["type"];
$filesize = $_FILES["photo"]["size"];
// Verify file extension
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if(!array_key_exists($ext, $allowed)) die("Error: Please select a valid file format.");
// Verify file size - 5MB maximum
$maxsize = 5 * 1024 * 1024;
if($filesize > $maxsize) die("Error: File size is larger than the allowed limit.");
// Verify MYME type of the file
if(in_array($filetype, $allowed)){
// Check whether file exists before uploading it
if(file_exists("upload/" . $filename)){
echo $filename . " is already exists.";
} else{
move_uploaded_file($_FILES["photo"]["tmp_name"], "d:/uploads/" . $filename);
echo "Your file was uploaded successfully.";
}
} else{
echo "Error: There was a problem uploading your file. Please try again.";
}
} else{
echo "Error: " . $_FILES["photo"]["error"];
}
}
?>
// Check if the form was submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Check if file was uploaded without errors
if(isset($_FILES["photo"]) && $_FILES["photo"]["error"] == 0){
$allowed = array("jpg" => "image/jpg", "jpeg" => "image/jpeg", "gif" => "image/gif", "png" => "image/png");
$filename = $_FILES["photo"]["name"];
$filetype = $_FILES["photo"]["type"];
$filesize = $_FILES["photo"]["size"];
// Verify file extension
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if(!array_key_exists($ext, $allowed)) die("Error: Please select a valid file format.");
// Verify file size - 5MB maximum
$maxsize = 5 * 1024 * 1024;
if($filesize > $maxsize) die("Error: File size is larger than the allowed limit.");
// Verify MYME type of the file
if(in_array($filetype, $allowed)){
// Check whether file exists before uploading it
if(file_exists("upload/" . $filename)){
echo $filename . " is already exists.";
} else{
move_uploaded_file($_FILES["photo"]["tmp_name"], "d:/uploads/" . $filename);
echo "Your file was uploaded successfully.";
}
} else{
echo "Error: There was a problem uploading your file. Please try again.";
}
} else{
echo "Error: " . $_FILES["photo"]["error"];
}
}
?>
Note: The above script prevents uploading a file with the
same name as an existing file in the same folder. However, if you want to allow
this just prepend the file name with a random string or timestamp,
like $filename = time() . '_' . $_FILES["photo"]["name"];
You
might be wondering what this code was all about. Well, let's go through each
part of this example code one by one for a better understanding of this
process.
Explanation of Code
Once
the form is submitted information about the uploaded file can be accessed via
PHP superglobal array called $_FILES. For example, our upload form
contains a file select field called photo (i.e. name="photo"),
if any user uploaded a file using this field, we can obtains its details like
the name, type, size, temporary name or any error occurred while attempting the
upload via the $_FILES["photo"] associative array, like
this:
$_FILES["photo"]["name"] —
This array value specifies the original name of the file, including the file
extension. It doesn't include the file path.
$_FILES["photo"]["type"] —
This array value specifies the MIME type of the file.
$_FILES["photo"]["size"] —
This array value specifies the file size, in bytes.
$_FILES["photo"]["tmp_name"] —
This array value specifies the temporary name including full path that is
assigned to the file once it has been uploaded to the server.
$_FILES["photo"]["error"] —
This array value specifies error or status code associated with the file
upload, e.g. it will be 0, if there is no error.
2.4 Redirecting a
form after submission
URL redirection is often used within form handling code.
Normally when you run a PHP script — whether by typing its URL,
following a link, or submitting a form — the script does its thing, displays
some sort of response as a Web page, and exits.
However, by sending a special HTTP header back to the browser from
the PHP script, you can cause the browser to jump to a new URL after the script
has run.
This is commonly used within a form handler script to redirect the
users to a thank - you page after they ’ ve submitted the form.
This means that you can keep your thank - you page separate from
your PHP script, which makes the page easier to edit and update.
Another good thing about redirecting to a new URL after a form has
been submitted is that it prevents users from accidentally resubmitting the
form by clicking their browser ’ s Reload or Refresh button.
Redirection is as simple as outputting a Location: HTTP header,
including the URL you want to
redirect to. You output HTTP headers in PHP using the built - in
header() function. So here ’ s how to redirect to a page called thanks.html :
header( “Location: thanks.html” );
The only thing to watch out for is that you don’t output any
content to the browser — whether via echo() or print() , or by including HTML
markup outside the < ?php ... ?> tags — before calling
header() . This is because the moment you send content to the
browser, the PHP engine automatically sends the default HTTP headers — which
won’t include your Location: header — and you can send headers only once per
request.
Here’s a quick example of a form handler script that redirects to a
thank - you page:
<?php
if ( isset(
$_POST["submitButton"] ) ) {
// (deal with the submitted fields here)
header( "Location: thanks.html"
);
exit;
} else {
displayForm();
}
function displayForm() {
?>
<html>
<head>
<title>Membership Form</title>
</head>
<body>
<h1>Membership Form</h1>
<form action="redirect.php"
method="post">
<div style="width: 30em;">
<label
for="firstName">First name</label>
<input type="text"
name="firstName" id="firstName" value=""
/></br>
<label for="lastName">Last
name</label>
<input type="text"
name="lastName" id="lastName" value="" />
<div style="clear: both;">
<input type="submit"
name="submitButton" id="submitButton" value=
"Send Details" />
</div>
</div>
</form>
</body>
</html>
<?php
}
?>
Notice that the
script doesn’t output anything to the browser until either the header()
function is called, or until the membership form is displayed. Also notice that
the script terminates with the exit statement after calling header() to avoid
sending any further output to the browser.
It’s interesting Post.
ReplyDeletePython Online Training