0% found this document useful (0 votes)
11 views11 pages

Unit Vi

The document outlines common form elements such as checkboxes, radio buttons, and input fields, along with their functions. It explains the GET and POST methods for sending data to a server, highlighting their differences in data visibility and size limitations. Additionally, it covers form validation techniques using PHP, including regular expressions for email validation and file uploading procedures.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views11 pages

Unit Vi

The document outlines common form elements such as checkboxes, radio buttons, and input fields, along with their functions. It explains the GET and POST methods for sending data to a server, highlighting their differences in data visibility and size limitations. Additionally, it covers form validation techniques using PHP, including regular expressions for email validation and file uploading procedures.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

UNIT VI

COMMON FORM ELEMENTS & ISSUES:

 List : it is an selection box with multiple selected options.


 Checkbox: it is a small box that can be used for checking during the selection.
 Radio: it is a small button that can be used for selecting an option.
 Select :it is a drop down box that can contain multiple options.
 Text input: it is a simple text box.
 Password input: it is a simple text box that will hide character’s entered in it.
 Hidden input: it is afield on the form that hides data contained in it.
 Text area: it is a large box contains text up to a paragraph.
 File:it is an element that lets you to browse component in search of a file.
 Reset :it is a button that resets the form in to its original state.
 Submit :it is a button clicking on which the form is submitted.

GET & POST METHODS:


There are two ways the browser client can send information to the web server.
The GET Method
The POST Method
Before the browser sends the information, it encodes it using a scheme called URL encoding. In this
scheme, name/value pairs are joined with equal signs and different pairs are separated by the ampersand.
name1=value1&name2=value2&name3=value3
Spaces are removed and replaced with the + character and any other no alphanumeric characters are replaced
with a hexadecimal values. After the information is encoded it is sent to the server.

The GET Method


The GET method sends the encoded user information appended to the page request. The page and the
encoded information are separated by the ? character.
http://www.test.com/index.htm?name1=value1&name2=value2
 The GET method produces a long string that appears in your server logs, in the browser's Location: box.
 The GET method is restricted to send upto 1024 characters only.
 Never use GET method if you have password or other sensitive information to be sent to the server.
 GET can't be used to send binary data, like images or word documents, to the server.
 The data sent by GET method can be accessed using QUERY_STRING environment variable.
 The PHP provides $_GET associative array to access all the sent information using GET method.

The POST Method


The POST method transfers information via HTTP h
eaders. The information is encoded as described in case of GET method and put into a header called
QUERY_STRING.

 The POST method does not have any restriction on data size to be sent.
 The POST method can be used to send ASCII as well as binary data.
 The data sent by POST method goes through HTTP header so security depends on HTTP protocol. By using
Secure HTTP you can make sure that your information is secure.
 The PHP provides $_POST associative array to access all the sent information using POST method.

GET vs. POST


Both GET and POST create an array (e.g. array( key => value, key2 => value2, key3 => value3, ...)). This
array holds key/value pairs, where keys are the names of the form controls and values are the input data from the
user.

Both GET and POST are treated as $_GET and $_POST. These 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.

$_GET is an array of variables passed to the current script via the URL parameters.
$_POST is an array of variables passed to the current script via the HTTP POST method.

When we can use GET?


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 1024
characters. However, because the variables are displayed in the URL, it is possible to bookmark the page. This can
be useful in some cases.
GET may be used for sending non-sensitive data.

When we can use POST?


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.

How post and get works:

A simple HTML form

<html>
<body>
<form action="action.php" method="post">
<p>Your name: <input type="text" name="name" /></p>
<p>Your age: <input type="text" name="age" /></p>
<p><input type="submit" /></p>
</form>
</body>
</html>
When the user fills in this form and hits the submit button, the action.php page is called. The form data is
sent with the HTTP POST method.

action.php looks like this:


<html>
<body>
Hi <?php echo htmlspecialchars($_POST['name']); ?>.
You are <?php echo (int)$_POST['age']; ?> years old.
</body>
</html>

htmlspecialchars() makes sure any characters that are special in html are properly encoded so
people can't inject HTML tags or Javascript into your page. For the age field, since we know it is a
number, we can just convert it to an integer which will automatically get rid of any stray characters. You
can also have PHP do this for you automatically by using the filter extension.

<html>
<body>
<form action="action_get.php" method="post">
<p>Your name: <input type="text" name="name" /></p>
<p>Your age: <input type="text" name="age" /></p>
<p><input type="submit" /></p>
</form>
</body>
</html>

Action_get.php looks like this:


<html>
<body>
Hi <?php echo htmlspecialchars($_POST['name']); ?>.
You are <?php echo (int)$_POST['age']; ?> years old.
</body>
</html>

The code above is quite simple. However, the most important thing is missing. You need to validate form
data to protect your script from malicious code.
VALIDATION OF A FORM:

<html>

<body>

<h2>php form validation example</h2><BR>

* REQUIRED FIELD.

<?php

$nameerror=$emailerror=$gendererror=$websiteerror=$commenterror=$name=$email=$gender=$comment=
$website="";

if($_SERVER["REQUEST_METHOD"]=="POST")

if(empty($_POST["name"]))

$nameerror="Name is required";
}

else

$name=test_input($_POST["name"]);

if(!preg_match("/^[a-zA-Z]+$/",$name))

$nameerror="invalid name";

$name="";

if(empty($_POST["email"]))

$emailerror="email is required";

else

$email=test_input($_POST["email"]);

if(empty($_POST["website"]))

$websiterror="website is required";

else

$website=test_input($_POST["website"]);

if(empty($_POST["comment"]))

$commenterror="comment is required";

else

{
$comment=test_input($_POST["comment"]);

if(empty($_POST["gender"]))

$gendererror="Gender is required";

else

$gender=test_input($_POST["gender"]);

function test_input($data)

$data=trim($data);

$data=stripslashes($data);

$data=htmlspecialchars($data);

return $data;

?>

<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">

Name:<input type="text" name="name"> *<?php echo $nameerror;?> <BR>

Email:<input type="text" name="email"> *<?php echo $emailerror;?> <BR>

Website:<input type="text" name="website"> *<?php echo $websiteerror;?> <BR>

comment:<input type="text" name="comment"> *<?php echo $commenterror;?> <BR>

Gender:<input type="radio" name="gender" value="female">female <input type="radio"


name="gender" value="male">male *<?php echo $gendererror;?> <BR>

<input type="submit" name="submit" value="submit">

</form>

<?php

echo"<h2>your given input:</h2>";

echo $name;

echo"<br>";

echo $email;
echo "<br>";

echo $website;

echo "<br>";

echo $comment;

echo "<br>";

echo $gender;

?>

</body>

</html>

OUTPUT:

php form validation example

* REQUIRED FIELD.
CSE
Name: *
YITS@GMAIL.
Email: *
WWW.YITS.CO
Website: *
GOOD
comment: *
Gender: female male *
submit

your given input:


CSE
YITS@GMAIL.COM
WWW.YITS.COM
GOOD
MALE……

PREG MATCH FUNCTION:

preg_match()
To validate a form field for an email address, we’d use preg_match():

1 <?php
2 if (preg_match('/^[A-Za-z0-9-_.+%]+@[A-Za-z0-9-.]+.[A-Za-z]{2,4}$/',
3 $_POST["emailAddy"])) {
4 echo "Email address accepted";
5 }
6 else {
7 echo "Email address is all broke.";
8 }
If a match is found, preg_match() returns 1, otherwise 0. Notice that we added slashes to the beginning
and end of the regex. These are used as delimiters to show the function where the regular expression
begins and ends. You may ask, “But Jason, isn’t that what the quotes are for?” Let me assure you that
there is more to it, as I will explain shortly.

preg_replace()
To find an email address and add formating, we would use preg_replace():

1 <?php
2 $formattedBlock = preg_replace(
3 '/([A-Za-z0-9-_.+%]+@[A-Za-z0-9-.]+.[A-Za-z]{2,4})/U',
4 "<b>\1</b>", $blockOText);
Here’s that explanation that was promised: we’ve placed a U after the ending delimiter as a flag that
modifies how the regex matches. We’ve seen how regex matches are greedy, gobbling up as many
characters as it can and only backtracking if it has to. U makes the regex “un-greedy.” Without it, the
string tweedle@dee.com-and-tweedle@dum.com would match as one. But by making it un-greedy, we tell
it to find the shortest matching pattern… just tweedle@dee.com.

Did you notice we also wrapped the the whole expression in parentheses? This causes the regex engine
to capture a copy of the text that matches the expression between the parenthesis which we can
reference with a back-reference (1). The second argument to preg_replace() is telling the function to
replace the text with an opening bold tag, whatever matched the pattern between the first set of
parenthesis, and a closing bold tag. If there were other sets of parenthesis, they could be referenced
with 2, 3, etc. depending on their position.

preg_match_all()
To scan some text and extract an array of all the email addresses found in it, preg_match_all() is our best
choice:

1 <?php
2 $matchesFound = preg_match_all(
3 '/([a-z0-9-_.+%]+@[a-z0-9-.]+.[a-z]{2,4})/Ui',
4 $articleWithEmailAddys, $listOfEmails);
5 if ($matchesFound) {
6 foreach ($listOfEmails[0] as $foundEmail) {
7 echo $foundEmail . "<br>";
8 }
9 }
preg_match_all() returns how many matches it found, and sticks those matches into the variable
reference we supplied as the third argument. It actually creates a multi-dimensional array in which the
matches we’re looking for are found at index 0.

In addition to the U modifier, we provided i which instructs the regex engine we want the pattern to be
applied in a case-insensitive manner. That is, /a/i would match both a lower-case A and an upper-case A
(or /A/i would work equally well for that matter since the modifier is asking the engine to be case-
agnostic). This allows us to write things like [a-z0-9] in our expression now instead of[A-Za-z0-9] which
makes it a little shorter and easier to grok.

Well that about wraps things up. While there is a lot more you can do using regular expressions
involving look-ahead, look-behind, and more intricate examples of back-references, all of which you can
find in PHP’s online documentation, hopefully you have plenty to work with that will serve you for many
scripts just from this article.

SUBMISSION OF MULTIPLE FORMS:

Preventing multiple submissions of a form


PHP File Uploading:-
A PHP script can be used with a HTML form to allow users to upload files to the server.
Initially files are uploaded into a temporary directory and then relocated to a target
destination by a PHP script.
Information in the phpinfo.php page describes the temporary directory that is used for file
uploads as upload_tmp_dir and the maximum permitted size of files that can be uploaded is
stated as upload_max_filesize. These parameters are set into PHP configuration file php.ini
The process of uploading a file follows these steps
 The user opens the page containing a HTML form featuring a text files, a browse button
and a submit button.
 The user clicks the browse button and selects a file to upload from the local PC.
 The full path to the selected file appears in the text filed then the user clicks the submit
button.
 The selected file is sent to the temporary directory on the server.
 The PHP script that was specified as the form handler in the form's action attribute
checks that the file has arrived and then copies the file into an intended directory.
 The PHP script confirms the success to the user.

As usual when writing files it is necessary for both temporary and final locations to have
permissions set that enable file writing. If either is set to be read-only then process will fail.
An uploaded file could be a text file or image file or any document.
Creating an upload form:
The following HTM code below creates an uploader form. This form is having method
attribute set to post and enctype attribute is set to multipart/form-data
<html>
<head>
<title>File Uploading Form</title>
</head>
<body>
<h3>File Upload:</h3>
Select a file to upload: <br />
<form action="/php/file_uploader.php" method="post" enctype="multipart/form-data">
<input type="file" name="file" size="50" />
<br />
<input type="submit" value="Upload File" />
</form></body></html>
This will display following result:
File Upload:
Select a file to upload:

Choose..

Upl
oa
d
File

Creating an upload script:


There is one global PHP variable called $_FILES. This variable is an associate double dimension
array and keeps all the information related to uploaded file. So if the value assigned to the
input's name attribute in uploading form was file, then PHP would create following five
variables:
 $_FILES['file']['tmp_name']- the uploaded file in the temporary directory on the web
server.
 $_FILES['file']['name'] - the actual name of the uploaded file.
 $_FILES['file']['size'] - the size in bytes of the uploaded file.
 $_FILES['file']['type'] - the MIME type of the uploaded file.
 $_FILES['file']['error'] - the error code associated with this file upload.

The following example below attempts to copy a file uploaded by the HTML Form listed in
previous section page to /var/www/html directory which is document root of your PHP server
and it will display all the file's detail upon completion. Please note that if you are going to
display uploaded file then don't try with binary files like images or word document.
Here is the code of uploader.php script which will take care of uploading a file
<?php
if( $_FILES['file']['name'] != "" )
{
copy( $_FILES['file']['name'], "/var/www/html" ) or
die( "Could not copy file!");
}
else
{
die("No file specified!");
}
?>
<html>
<head>
<title>Uploading Complete</title>
</head>
<body>
<h2>Uploaded File Info:</h2>
<ul>
<li>Sent file: <?php echo $_FILES['file']['name']; ?>
<li>File size: <?php echo $_FILES['file']['size']; ?> bytes
<li>File type: <?php echo $_FILES['file']['type']; ?>
</ul>
</body>
</html>
When you will upload a file using upload form and upload script, it will display following
result:
Uploaded File Info:
 Sent file: uploadedfile.txt
 File size: 2003 bytes
 File type: image/jpg

You might also like