How to take PHP Input Using Form
To take input in PHP using a form, you need to create an HTML form that collects data from users and submit it to a PHP script for processing. Here's a basic example of how you can create a form to take input in PHP:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>PHP Form Example</title>
</head>
<body>
<h2>PHP Form Example</h2>
<!-- HTML form with method="post" and action="process.php" -->
<form method="post" action="process.php">
<!-- Input field for the user's name -->
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<!-- Input field for the user's email -->
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<!-- Submit button to submit the form -->
<input type="submit" value="Submit">
</form>
</body>
</html>
In this example:
method
attribute of the form is set to "post," indicating that the form data should be sent using the HTTP POST method.action
attribute of the form is set to "process.php," indicating that the form data should be submitted to a PHP script named "process.php" for further processing.Now, in the PHP script (process.php
in this example), you can retrieve the input values submitted from the form. Here's a simple process.php
script:
<?php
// Check if the form is submitted using the POST method
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Retrieve form data using the $_POST superglobal
$name = $_POST['name'];
$email = $_POST['email'];
// Display the submitted data
echo "Name: $name <br>";
echo "Email: $email";
}
?>
This process.php
script checks if the form is submitted using the POST method ($_SERVER['REQUEST_METHOD'] === 'POST'
). It then retrieves the values of the "name" and "email" fields from the $_POST
superglobal array. Finally, it displays the submitted data.
Note: Always validate and sanitize user input to ensure security and prevent issues like SQL injection and cross-site scripting (XSS). Additionally, consider using prepared statements when interacting with databases. The example above focuses on the basics of form handling in PHP.
Thank you.