PHP Form Handling

Form handling in PHP involves processing data submitted through HTML forms. This process typically includes gathering user input, validating and sanitizing the input, and then using the data (e.g., storing it in a database, sending an email, or generating output).


PHP allows you to handle form data submitted through both the GET and POST methods.


1. Simple HTML Form Example


Create a simple HTML form for user input:

Example
<!DOCTYPE html>
<html>
<body>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
Name: <input type="text" name="fname">
<input type="submit">
</form>
<?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>

Try it yourself

The $_SERVER['PHP_SELF'] variable is a PHP superglobal that contains the current script's file path. It is often used in forms to set the action attribute, allowing the form to submit to the same script for processing. Here's an explanation of its use, particularly in the context of the POST method.


GET Method Form Handling

Example
<!DOCTYPE html>
<html>
<head>
<title>Form Handling</title>
</head>
<body>
<form method="get" action="">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required><br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>

Try it yourself

When action="", the form submits to the same page that displays the form.


GET Vs POST

Feature

GET

POST

Data Location

Appended to URL as query parameters

Sent in the request body

Visibility

Visible in the URL

Hidden from the URL

Security

Less secure (data in URL)

More secure (data hidden)

Data Length

Limited (based on URL length)

Virtually unlimited

Caching

Can be cached by browsers

Cannot be cached

Use Cases

Non-sensitive data, search queries

Sensitive data, large data submissions

When to Use


  • Use GET:
  • When the data is not sensitive.
  • When data should be bookmarkable or shareable.
  • Use POST:
  • When sending sensitive or confidential data.
  • When the data size exceeds the URL length limit.

Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.