save php output as a new html file - php

I worked out a form to fill out on a simple php site, how can I set up a script to put that information in a html/php file and finally save it on the server (file name should be the same name as the $name)
$name = $email = $friendcode = "";
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$name = test_input($_POST["name"]);
$email = test_input($_POST["email"]);
$friendcode = test_input($_POST["friendcode"]);
}
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name"><?php echo $nameErr;?>
<br><br>
E-mail: <input type="text" name="email"><?php echo $emailErr;?>
<br><br>
Friendcode: <input type="text" name="friendcode"><?php echo $friendcodeErr;?>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>

You can use the fopen(), fwrite() and fclose() functions provided by PHP.
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$name = test_input($_POST["name"]);
$email = test_input($_POST["email"]);
$friendcode = test_input($_POST["friendcode"]);
$file=fopen($name,"a") or die("can't open file");
fwrite($file,$email." ".$friendcode);
fclose($file);
}
This will result in a simple text file, but you can also fwrite() any HTML/PHP code you like.

Try to create a file using fopen,
$save_str = '<p>Name :'.$name.'<br/>e-mail:'.$email.'<br/>friend code'.$friendcode.'</p>';
$handle = fopen($name.'.html','c');
fwrite ($handle, $save_str);
fclose ($handle);
more about fwrite

Related

How Form handling works in PHP?

I am learning PHP through w3schools. I am little bit confused of the execution flow of the page. I will attach a code example from w3schools.
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";
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"]);
}
if (empty($_POST["website"])) {
$website = "";
} else {
$website = test_input($_POST["website"]);
}
if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}
if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
$gender = test_input($_POST["gender"]);
}
}
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">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
E-mail: <input type="text" name="email">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Website: <input type="text" name="website">
<span class="error"><?php echo $websiteErr;?></span>
<br><br>
Comment: <textarea name="comment" rows="5" cols="40"></textarea>
<br><br>
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<input type="radio" name="gender" value="other">Other
<span class="error">* <?php echo $genderErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>
</body>
</html>
Can anyone explain how the execution flow goes on this form handling. Browser can't run the php script. In this example superglobal $_SERVER["PHP_SELF"] used to refer the same html page. when we try to submit the page with empty field it shows the error message in screen. This is happening due to the fact php variable got its error value after submission. I think that after triggering the submit button. This page makes a request to the same page in the server using POST method and in the server we access the same form value using superglobal $_POST["name"],["email"] etc.. and finally the server throws the new html page. Am i right? or this validation is happening entirely in the frontend.
In php the validation is happening entirely in the server ..
The frontend only validate things when JavaScript involved or you add field attributes like required , min , max.
I think w3 is good source to check small code snippets. but it's not good source to learn

Submit form data and go to next page on one click

Right now I have code that submits form data and gets put into a text file and then after I click a button to go to the next page. I want to be able to submit the form data and go to the next page on the same click. I'm using PHP and HTML right now. Is there anyway to successfully do this?? I tried an onclick like I have for my next button but it doesn't seem to work with the input type function.
<h2>Please enter your name.</h2>
<form method="post" action="<?php echo
htmlspecialchars($_SERVER["PHP_SELF"]);?>">
First Name: <input type="text" name="fName">
<br><br>
Middle Initial: <input type="text" name="mInitial">
<br><br>
Last Name: <input type="text" name="lName">
<br><br>
<input type="submit" name="submit" value="Submit">
<button type="button" name="submit" value="Submit"
onclick="location.href='county.php'">Next</button>
</form>
<?php
if($_SERVER['REQUEST_METHOD'] == "POST" and isset($_POST['submit']))
{
replace();
}
function replace() {
$myFile = "freewill.doc";
$fh = fopen($myFile, 'a') or die("can't open file");
$fName = $_POST["fName"];
$mInitial = $_POST["mInitial"];
$lName = $_POST["lName"];
$placeholders = array('fin', 'min', 'lana');
$namevals = array($fName,$mInitial,$lName);
$path_to_file = 'freewill.doc';
$file_contents = file_get_contents($path_to_file);
$file_contents = str_replace($placeholders,$namevals,$file_contents);
file_put_contents($path_to_file,$file_contents);
fclose($fh);
}
?>
Change below line
<button type="button" name="submit" value="Submit"
onclick="location.href='county.php'">Next</button>
to
<input type="submit" name="submitform" value="Submit">Next</button>
and change PHP code to this
if($_SERVER['REQUEST_METHOD'] == "POST" and isset($_POST['submitform']))
{
$myFile = "freewill.doc";
$fh = fopen($myFile, 'a') or die("can't open file");
$fName = $_POST["fName"];
$mInitial = $_POST["mInitial"];
$lName = $_POST["lName"];
$placeholders = array('fin', 'min', 'lana');
$namevals = array($fName,$mInitial,$lName);
$path_to_file = 'freewill.doc';
$file_contents = file_get_contents($path_to_file);
$file_contents = str_replace($placeholders,$namevals,$file_contents);
file_put_contents($path_to_file,$file_contents);
fclose($fh);
header('Location: county.php');
}
Try setting an onSubmit method for your form instead.

PHP- Save input data into CSV file and display the entire file in another page

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>

PHP script not running inside a form tag

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>

fputcsv posts empty data to csv file

I have a html form which collects, name, place, email on submission it posts to csv file. But the php file creates a file without any data. Can any body help me in correcting the code. The full code is given below.
HTML form CODE:
<form method="post" name="excisedata" action="csv.php">
Enter Full Name: <br>
<input type="text" name="name"><br>
Enter Place /Location : <br>
<input type="text" name="place"><br>
Enter Valid Email :<br>
<input type="text" name="email"><br>
<input type="submit" name='submit' onclick="show_confirm()" value="SUBMIT">
</form>
PHP CODE
<?php
$name = $_GET["name"];
$place = $_GET["place"];
$email = $_GET["email"];
$list = array($name, $place, $email,);
$file = fopen("mylist.csv","a");
foreach ($list as $line) {
fputcsv($file,explode(',',$line)); }
fclose($file);
?>
first, i would add static values to your fputcsv function to make sure you have no file permissions problems.
fputcsv($file,'bird,dog,fish');
once you confirm that is ok, try this:
your form is posting data, your processor is looking for GET data.
change
$name = $_GET["name"];
$place = $_GET["place"];
$email = $_GET["email"];
to
$name = $_POST["name"];
$place = $_POST["place"];
$email = $_POST["email"];
<?php
$name = $_POST["name"];
$place = $_POST["place"];
$email = $_POST["email"];
$list = array($name, $place, $email,);
$file = fopen("mylist.csv","a+");
fputcsv($file,$list);
fclose($file);
?>

Categories