PHP Form
Form handling is a common task in web development, and PHP provides several built-in functions and features for working with HTML forms. Here's a basic example of how to handle a form submission in PHP:
<!-- HTML form -->
<form method="post" action="process.php">
<label for="name">Name:</label>
<input type="text" name="name" id="name">
<label for="email">Email:</label>
<input type="email" name="email" id="email">
<button type="submit">Submit</button>
</form>
<!-- process.php -->
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// Get form data
$name = $_POST['name'];
$email = $_POST['email'];
// Do something with the data, e.g. save to a database
//...
// Redirect to a thank-you page
header('Location: thank-you.php');
exit;
}
?>
In the example above, the HTML form sends the form data to a PHP script called process.php using the HTTP POST method. When the form is submitted, the PHP script checks if the request method is POST (to prevent the script from being accessed directly), retrieves the form data using the $_POST superglobal variable, processes the data (e.g. saves it to a database), and then redirects the user to a thank-you page using the header() function.
PHP provides several other superglobal variables for working with form data, including $_GET (for GET requests), $_REQUEST (which includes both GET and POST data), and $_FILES (for handling file uploads).
In addition to retrieving form data, PHP also provides functions for validating and sanitizing user input to prevent security vulnerabilities such as SQL injection and cross-site scripting (XSS) attacks. Some common functions for sanitizing input include filter_var() and htmlspecialchars(), while functions for validating input include preg_match() and ctype_*() functions. It's important to always validate and sanitize user input to ensure the security and reliability of your web application.
Tags:
PHP