I have PHP code with HTML inline, yet I need them to be separate on two pages. A HTML page with a form and a PHP form with the process on it.
The bits with the PHP form verification I need on a PHP page and the form I need on a HTML sheet the rest of the website will be on
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php // define variables and set to empty values
$nameErr = $emailErr = "";
$name = $email = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if(empty($_POST["name"])) {$nameErr = "Name is required";}
else{$name = test_input($_POST["name"]);}
if(empty($_POST["email"])) {$emailErr = "Email is required";}
else{$email = test_input($_POST["email"]);}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>PHP Form Validation Example</h2>
<p><span class="error">* required field</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name" value="<?php echo $name;?>">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
E-mail: <input type="text" name="email" value="<?php echo $email;?>">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
?>
</body>
</html>
updated HTML code:
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<h2>PHP Form Validation Example</h2>
<p><span class="error">* required field</span></p>
<form method="post" action="<?php require 'php.php'; echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name" value="<?php require 'php.php'; echo $name;?>">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
E-mail: <input type="text" name="email" value="<?php require 'php.php'; echo $email;?>">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
You'd need to put your php code in an other file (for example form.php). In your html file you need to include your php script. If your php file is situated in the same directory as your html file, your include statement could look like this.
<?php include 'form.php';?>
I'd like to refer you to W3schools php include where they explain in detail how you can link your php file.
I am just giving you a basic example to separate form file and php file.
create a index.php file and write those code there
<form action="post.php" method="post">
<input type="text" name="txtName"/>
<input type="submit" name="btnSubmit"/>
</form>
Then create a post.php file and put below code there
<?php
if(isset($_POST['btnSubmit'])){
$val = $_POST['txtName'];
echo $val;
}
?>
Hope it will help.
So here you have all the code for html form in your file. Now create a new file for process the form like "process.php" and post your form on that file. place this new file on the same directory where the HTML file is being placed and give path of this file into your form action = " " like
<form method="post" action="process.php">
and in the process.php page you can process you form as you are doing.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST["name"];
$email = $_POST["email"];
}
Related
Pretty much in the title. I want to make a solution that saves the input data of a html form and display the entire csv file in a separate page that isn't connected. Here's the code I'm currently using that isn't saving the input data nor display the csv file.
Input Data Page:
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<h2>PHP Form Validation Example</h2>
<form method="post" name="test1" action="" onsubmit="required()">
Name: <input type="text" name="name">
<br><br>
E-mail: <input type="text" name="email">
<br><br>
Website: <input type="text" name="website">
<br><br>
Comment: <textarea name="comment" rows="5" cols="40"></textarea>
<br><br>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$web = $_POST['website'];
$comment = $_POST['comment'];
$csv =
array($_POST['name'],$_POST['email'],$_POST['website'],$_POST['comment']);
$file = fopen('form.csv', 'a');
foreach ($csv as $line)
{
fputcsv($file,explode(',',$line));
}
fclose($file);
?>
</html>
PHP:Display CSV file
<!DOCTYPE html>
<html>
<?php
echo "</br >";
echo '<table style="width=100%">';
// Print other student details here (minus the private stuff)
//The CSV file is read and printed on the page when using the 'r' value.
$myfile = fopen("form.csv" , "r") or die ("Unable to open file");
while(!feof($myfile)) {
echo fgets($myfile) . "<br>";
}
fclose($myfile);
echo "</table>";
?>
<body>
</body>
</html>
I just saw this codes from this website and thinking to implement it to my project however I cannot get my data on the next page. I am using the test.php as a index and submit.php as a page that will catch the post
here is the codes
test.php
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// Initialize variables and set to empty strings
$firstName=$lastName="";
$firstNameErr=$lastNameErr="";
// Validate input and sanitize
if ($_SERVER['REQUEST_METHOD']== "POST") {
$valid = true; //Your indicator for your condition, actually it depends on what you need. I am just used to this method.
if (empty($_POST["firstName"])) {
$firstNameErr = "First name is required";
$valid = false; //false
}
else {
$firstName = test_input($_POST["firstName"]);
}
if (empty($_POST["lastName"])) {
$lastNameErr = "Last name is required";
$valid = false;
}
else {
$lastName = test_input($_POST["lastName"]);
}
//if valid then redirect
if($valid){
header('Location: submit.php');
exit();
}
}
// Sanitize data
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>Find Customer</h2>
<p><span class="error">* required</span></p>
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>" method="post">
First Name: <input type="text" name="firstName" value="<?php echo $firstName; ?>"><span class="error">* <?php echo $firstNameErr; ?></span><br><br>
Last Name: <input type="text" name="lastName" value="<?php echo $lastName; ?>"><span class="error">* <?php echo $lastNameErr; ?><br><br>
<input type="submit">
</form>
</body>
</html>
submit.php
<?php
$test=$_POST['lastName'];
echo $test;
?>
Your form action should be the file where you want to get the form submitted values .
change this <form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>" method="post"> to <form action="submit.php" method="post">
I'm building a form, and I want that all the inserted values will be kept, in case of form submit failure. This is my code:
<?php
$error = "";
$name = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST["name"];
// Verify $_POST['name'] greater than 4 chars
if ( strlen($name) < 4 ){
$error= 'Name too short!';
}
}
?>
<html>
<head>
</head>
<body>
<form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" name="myForm" id="idForm">
<input type="text" placeholder="Name" id="name" name="name" value=""/>
<input type="submit" value="submit"/>
</form>
<?php
echo "<h2>Input:</h2>";
echo $name;
if($error) {
// No Update AND refresh page with $name in text field
echo "<br/>" . $error;
} else {
// Update name in DB
}
?>
</body>
</html>
I would like that name field keeps the inserted input text, after submit. I tried to do with php code in input value but doesn't work. Any ideas?
Solved. This is the solution that I was looking for.
I added in value tag of input the following:
<?php if (isset($_POST['name'])) echo $_POST['name']; ?>
Therefore input field would look like:
<input type="text" placeholder="Name" id="name" name="name" value="<?php if (isset($_POST['name'])) echo $_POST['name']; ?>"/>
Thanks for your responses, helped me.
<?php
$error = "";
$name = isset($_POST["name"])?$_POST["name"]:""; //Added condition
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST["name"];
// Verify $_POST['name'] greater than 4 chars
if ( strlen($name) < 4 ){
$error= 'Name too short!';
}
}
?>
<html>
<head>
</head>
<body>
<form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" name="myForm" id="idForm">
<input type="text" placeholder="Name" id="name" name="name" value="<?php echo $name; ?>"/>
<input type="submit" value="submit"/>
</form>
<?php
echo "<h2>Input:</h2>";
echo $name;
if($error) {
// No Update AND refresh page with $name in text field
echo "<br/>" . $error;
} else {
// Update name in DB
}
?>
</body>
</html>
You can just echo $_POST['name'] in the value attribute of the input.
Make sure you check POST values to avoid XSS.
I also put up the update DB function, as you don't need to show the form to the user if the name in longer the 4 chars!
<?php
$error = "";
$name = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (isset($_POST['name'])){ //change name content only if the post value is set!
$name = filter_input (INPUT_POST, 'name', FILTER_SANITIZE_STRING); //filter value
}
// Verify $_POST['name'] greater than 4 chars
if ( strlen($name) < 4 ){
$error= 'Name too short!';
} else {
// Update name in DB
// Redirect
}
}
?>
<html>
<head>
</head>
<body>
<form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" name="myForm" id="idForm">
<input type="text" placeholder="Name" id="name" name="name" value="<?php echo $name; ?>"/>
<input type="submit" value="submit"/>
</form>
<?php
echo "<h2>Input:</h2>";
echo $name;
if($error) {
// No Update AND refresh page with $name in text field
echo "<br/>" . $error;
};
?>
</body>
</html>
If you want to keep all values/inputs for further use you could achieve that with php session values.
Besides - you should use $_SERVER['SCRIPT_NAME'] instead of $_SERVER['PHP_SELF']
Mars
I have recently installed Apache 2.4.7 server, as well as, PHP 5.5.10. I'm just beginning to learn PHP. I'm currently working through the w3school's tutorial on form processing with PHP, but I can't get a particular example to work. Does anyone here see an error?
<!DOCTYPE html>
<html>
<head>
<title>PHP Test</title>
</head>
<body>
<?php
// define variables and set to empty values
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$name = test_input($_POST["name"]);
$email = test_input($_POST["email"]);
$website = test_input($_POST["website"]);
$comment = test_input($_POST["comment"]);
$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 $_SERVER["PHP_SELF"];?>">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
Website: <input type="text" name="website"><br>
Comment: <textarea name="comment" rows="5" cols="40"></textarea><br>
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male<br>
<input type="submit">
</form>
</body>
</html>
When I visit this website, I get a quote and a greater than sign before the input field name specifically: "> Name. When I submit the form, the URL shows as
http://127.0.0.1/%3C?php%20echo%20$_SERVER[
I can't enter the exact contents of the URL, because this website won't let me, but the %3C actually shows up as a less than sign. The %20 shows up as a space. So, the problem is that the php script inside the action tag does not run. The action variable is then filled with the php script instead of the location of the current page. Why is the PHP script not running inside my form tag?
Solution:
Thank you everyone for helping. Abhik Chakraborty your comment led me to the solution. No, I did not save my file with a .php extension. I changed the extension to .php and it worked perfectly. I would have posted this as a solution, but I have to wait eight hours because I don't have enough reputation points.
If you leave action tag undefined it will use current location.
somefile.php:
<form method="post">
will execute the same uri
Replace action="<?php echo $_SERVER["PHP_SELF"];?>" by action=""
Remove action tag in your form. bcoz action is not mandatory for current page.
if u given $_SERVER['PHP_SELF'] . concatinate to your full path.
Try this one, this should work
<?php echo "<form method='post' action='".$_SERVER["PHP_SELF"]."' >";
action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"
try this one this is the method posted on w3school to refer to self page at till now faced no problems with it.
you are not processing the data you can try this
<!DOCTYPE html>
<html>
<head>
<title>PHP Test</title>
</head>
<body>
<?php
// define variables and set to empty values
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$name = test_input($_POST["name"]);
$email = test_input($_POST["email"]);
$website = test_input($_POST["website"]);
$comment = test_input($_POST["comment"]);
$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 $_SERVER["PHP_SELF"];?>">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
Website: <input type="text" name="website"><br>
Comment: <textarea name="comment" rows="5" cols="40"></textarea><br>
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male<br>
<input type="submit">
</form>
Name: <?php echo $name?> <br />
Email: <?php echo $email?> <br />
Gender: <?php echo $gender?> <br />
Comment: <?php echo $comment?> <br />
Website: <?php echo $website?> <br />
</body>
</html>
In order to work properly my form needs to be set up to first check the validation and then post the data if the validation passes. This is fine but I am not sure how to combine the validation code with the post code in the form action. Example if the action is: action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> the form validates correctly but does not send anywhere! If I change the form action to action="contact-engine.php"> then the form is posted but without validation! With this in mind I need to combine into the action both the validation and then (once passed validation) the contact-engine.php problem is I simply do not know how to do this? I really am a learner in php and this is complicated for me! Any help is really appreciated I have been working on this from now for a few days! (N.B. both pages are .php) Full code is as follows:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Help!</title>
<style type="text/css">
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
$nameErr = $emailErr = "";
$name = $email = "";
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
//Name
if (empty($_POST["name"]))
{$nameErr = "Name is required";}
else
{
$name = test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z ]*$/",$name))
{
$nameErr = "Only letters and white space allowed";
}}
//Email
if (empty($_POST["email"]))
{$emailErr = "Email is required";}
else
{
$email = test_input($_POST["email"]);
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email))
{
$emailErr = "Invalid email format";
}}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<form method="post" id="form" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<p><span class="error">* required field.</span></p><br />
<div class="contact-font" style=" margin-top: 20px;">
<span class="asterix">* </span>Name:<br />
<input type="text" name="name" class="border" size="25" value="<?php if(isset($_POST['name'])) {echo $_POST['name']; } ?>">
<span class="error"><?php echo $nameErr;?></span>
</div>
<div class="contact-font" style=" margin-top: 20px;">
<span class="asterix">* </span>Email: (please double check enty)<br />
<input type="text" name="email" class="border" size="25" value="<?php if(isset($_POST['email'])) {echo $_POST['email']; } ?>"><span class="error">
<?php echo $emailErr;?></span>
</div>
<div>
<input type="submit" value="Send" id="submit">
</div>
</form>
</body>
</html>
And below is the contact-engine code:
<html>
<head>
<title>Contact Engine</title>
</head>
<body>
<br />Name:<?php echo htmlspecialchars($_POST['name']); ?><br />
<br />Email:<?php echo htmlspecialchars($_POST['email']); ?><br />
</body>
</html>
You can try this. This is a simple code below through which you can achieve this:
//sample index.php file
<?php
include 'submitted.php';
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF']?>" method="POST">
<input type="text" name="foo" />
<input type="submit" value="submit">
</form>
</body>
</html>
Here, I am submitting the form to the same page using post method. But, I have included another file which is include 'submitted.php'.
Here is the test script inside the submitted.php
//sample submitted.php
<?php
if(isset($_POST['foo']))
{
if(strlen($_POST['foo']) < 5){
echo "String length too small";
}
else
{
echo $_POST['foo'];
}
}
?>
For test, it simply checks if the length is more than five or not. If it is not, the error message is displayed on the same page where your page is present.
Test it yourself too.