Jump to content

Form that accepts and Saves to a file...


adam1984

Recommended Posts

So what I would like to do is create a form that accepts a user's first and last name. And create a script that saves this data to a file.

 

I know how to write to a file, in the below example I would have saved my user input to variables in order to write them to a new file.

-----------------------------------------------------

$fp = fopen(people_processed.txt, "w" ) or die("Couldn't open file");

fwrite($fp, $firstname $lastname);

fclose($fp);

-----------------------------------------------------

 

I am just lost on where to put this code. Would it go somewhere within my submit button? ???

Link to comment
https://forums.phpfreaks.com/topic/160985-form-that-accepts-and-saves-to-a-file/
Share on other sites

You can put it at the top of the page or in a seperate page. You will need a basic <form></form> tag for the html side of it and based on the names you provided for the fields, those will be the variable names.

 

For example if you gave your field name name="firstname" then your variable for $firstname would look like this:

 

$firstname = $_POST['firstname'];

 

or $_GET whichever one you decide to use.

9three got it bang on, here's a quick example though just to give you a bit more of a helping hand:

 

 

<?php

// Check if the form's been submitted
if($_POST['submit']){

//Make sure the values aren't empty
if(!empty($_POST['firstname'])&&!empty($_POST['lastname'])){

// Make a body string
$body = $_POST['firstname'].$_POST['lastname']."\n";

// Handle the file
$fp = fopen(people_processed.txt, "w" ) or die("Couldn't open file");
fwrite($fp, $body);
fclose($fp);

} else {
// If there's form errors, set a variable...
$error = "You didn't enter a required field";
}
}

?>

// HTML of the page

<?php 
// ... and tell the user
echo $error; 
?>
<form method="post" action="">
<input type="text" name="firstname" id="firstname" />
<input type="text" name="lastname" id="lastname" />
<input type="submit" name="submit" id="submit" />
</form>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.