PHP Form to Text File: the Basics

This is a basic tutorial on the application of PHP to get text information from a web form and write it to a text file.

This article will illustrate a number of features to be included in this application which are useful in actual project implementations, such as:

  • Restriction of user input to text while blocking unwanted and malicious form inputs.
  • Limiting the number of words of input that can be written to the file.
  • Allowing users to download the written file after text input.
  • Setting a forced download after clicking the download link.

Basic Code Implementation

Before discussing the application features in detail, let’s start with the most basic implementation, which does not contain the four additional functions listed above. The basic job is limited to:

1. Show web form to the user.

2. Get posted values from the web form and validate user inputs as to whether or not they’re empty.

3. Write text to file (.txt).

Showing the web form if it has not already been submitted 

<?php

 

//Check if the web form is NOT submitted

if (!$_POST['submit'])

 

{

 

//Form is not submitted, display web form

 to the browser

?>

 

<h2>Enter any text below to write to a text file(limited to 200 words)</h2>

 

<form action="<?php echo $SERVER['PHP_SELF']; ?>"

 

method="post">

 

<br />

 

<textarea name="textinputs" rows="25" cols="60"></textarea>

 

<br />

 

<input type="submit" name="submit" value="Write this text to a text file">

 

</form>

 

<a href="/phpformtotextfilebasic">Click here to reset or clear this form</a>

 

<br />

 

<br />

This is what the web form will look on the browser:

 

 

{mospagebreak title=Processing inputs from submitted form and writing the text to a file} 

 

<?php

 

}

 

else

 

{

 

//Form submitted, grab the data from POST

$textinputs =trim($_POST['textinputs']);

 

//Test if it contains some data.

 

if (!isset($textinputs) || trim($textinputs) == "")

 

{

 

//Feedback to user that it contains no data

 

die (‘ERROR: Enter your text. <a href="/phpformtotextfilebasic">Click here to proceed.</a>’);

 

}

 

else

 

{

 

//Set file and the path to write

$filepath=’/opt/lampp/htdocs/phpformtotextfilebasic/textfolder/writethistextfile.txt';

 

//Open file in writing mode

$filehandler= fopen($filepath, ‘w’) or die(‘ERROR: Could not open file!’);

 

//Write text to file

 

fwrite($filehandler,$textinputs) or die(‘ERROR: Could not write to file’);

 

//Close file

fclose($filehandler);

 

echo ‘Your text has been written to the file successfully.<br />';

 

echo ‘<a href="/phpformtotextfilebasic">Enter another text.</a>';

 

}

 

}

 

?>

 

{mospagebreak title=Code discussion}

The actual file writing procedures do not necessarily call the fwrite function right away. Instead, the file path should be declared first: 

$filepath=’/opt/lampp/htdocs/phpformtotextfilebasic/textfolder/
writethistextfile.txt';

This should be relative to the root directory. or else the error “Could not open file!” will be displayed. This is also the output of: 

<?php

echo $_SERVER['SCRIPT_FILENAME'];

?> 

If you do not know the full relative path with respect to the root, create a PHP file, name it path.php and upload it to the directory where you need to determine the path. After that, view path.php in the web browser and there will be revealed the full path relative to the root.

In Linux web hosting, it might look like this: /home/www/php-developer.org/formtotextproject/textfolder/writethistextfile.txt 

If you use (not a full path):  $filepath=’/phpformtotextfilebasic/textfolder/writethistextfile.txt';  

It will display an error that says fopen could not open the file. Also, be careful with the spelling of the path name, as any error wil also lead to the “Could not open the file” error. 

Now that the path has been set, you are ready to open a file using a file handler:

$filehandler= fopen($filepath, ‘w’) or die(‘ERROR: Could not open file!’);  

Since this is a file writing tasks, ‘w’ is used to signify the “writing” mode. By default, if writethistextfile.txt is not yet created, fopen will create and prepare this file for writing.

Finally, now that the file has been opened and is ready for writing, the actual text contents from the web form will be written to the file using the command:

fwrite($filehandler,$textinputs) or die(‘ERROR: Could not write to file’);  

The file handler can be closed after the writing tasks:

fclose($filehandler);  

You can download the complete script discussed above here

If you would like to test this, you can enter any text you like and then click the  “Write this text to a text file” button. 

Go to the textfolder directory and open the file; you should see the text you have just submitted.

Sample screen shot:

{mospagebreak title=Adding Four Features to the Basic Web Application} 

Now that you understand how to create the basic web form to text file application, you are ready to add the four features mentioned at the start of this tutorial.

The process flow will be:

 

The green areas in the flow chart are features to be added to the basic implementation discussed previously.  

Feature 1. Sanitizing User inputs in $_POST  

If you are planning to deploy this in your website, you need to sanitize to avoid unwanted inputs. This can prevent any malicious form of input from entering your application. 

Acunetix, one of the website security experts, recommends the use of the following PHP built in functions to further sanitize the input: 

1. strip_tags() =

http://php.net/manual/en/function.strip-tags.php; this will remove the scripting tags in the text input if you are allowing only pure text input to pass through the form.  

An example of scripting tags that will be removed are the <?php ?> tags as well as JavaScript tags and other HTML tags.  

2. nl2br() =

http://php.net/manual/en/function.nl2br.php; this will convert line break to <br />. This will ensure that the line breaks are intended for text formatting reasons.  

3. htmlspecialchars() =

  htt p://php.net/manual/en/function.htmlspecialchars.php; this will convert HTML special characters to HTML entities.  

4. escapeshellarg() =

http://php.net/manual/en/function.escapeshellarg.php ;this will prevent malicious execution of code that is contained in the user input.

To add this set of functions to sanitize user input, call these functions just after parsing the $_POST and assigning it to the $textinputs variable:

$textinputs =trim($_POST['textinputs']);

 

//Functions to sanitize the input

$textinputs= strip_tags($textinputs);

 

$textinputs =nl2br($textinputs);

 

$textinputs =htmlspecialchars($textinputs);

 

$textinputs =escapeshellarg($textinputs); 

But using these functions will add a quote at the beginning and end of the text written to the file. For example:  

‘The quick brown fox jumps over the lazy dog.’  

To correct this problem, just add:  

$textinputs =substr($textinputs,1,-1); 

And place it immediately after:

$textinputs =escapeshellarg($textinputs); 

{mospagebreak title=Adding features, continued}

Feature 2. Limiting the number of words that can be written to the file. 

Say that you are using this application for a 500 word essay. To limit the number of words, simply add these lines:  

$count = count(explode(" ", $textinputs));

If ($count>500) {

 

die(‘ERROR: Your text should be less than 500 words.’);

 

}

 

You will need to insert this after the validation of the user inputs are completed.  

Example (added lines in blue font):  

<?php

 

}

 

else

 

{

 

//Form submitted, grab the data from POST

 

$textinputs =trim($_POST['textinputs']);

 

//If you need to sanitize user input

 

$textinputs= strip_tags($textinputs);

 

$textinputs =nl2br($textinputs);

 

$textinputs =htmlspecialchars($textinputs);

 

$textinputs =escapeshellarg($textinputs);

 

$textinputs =substr($textinputs,1,-1);

 

//Test if it contains some data.

 

if (!isset($textinputs) || trim($textinputs) == "")

 

{

 

//Feedback to user that it contains no data

 

die (‘ERROR: Enter your text. <a href="/phpformtotextfile">Click here to proceed.</a>’);

 

}

 

else

 

{

 

//User input validation Completed

 

//Count the number of words in the text

 

$count = count(explode(" ", $textinputs));

 

If ($count>500) {

 

die(‘ERROR: Your text should be less than 500 words.’);

 

}

 

Features 3 and 4. Allowing users to download the written file after submission and then setting force download after clicking the download link.  

To implement this, you will need to add the download link code:  

echo ‘Click <a href="/phpformtotextfile/textfolder/writethistextfile.txt">here</a> to download this file.<br />';

 

echo ‘<a href="/phpformtotextfile">Enter another text.</a>';  

And place that after this line:  

echo ‘Your text has been written to the file successfully.<br />';  

The above download link, when displayed on the browser, still does not “force download” the text file. You need to use .htaccess to force download the text file inside the textfolder directory.  

To do this:  

1. Open a text editor.

2. Copy and paste the code below:

 

<Files *.txt>

 

ForceType application/octet-stream

 

Header set Content-Disposition attachment

 

</Files>

 

3. Save it as .htaccess

4. Upload the .htaccess to your textfolder directory.  

When the user clicks the download link, instead of opening the text file and displaying it on the browser, it will display the force download dialog:

 

 

To download the file, the user will click the “save” option in the download dialog box.  

You can download the modified and final “PHP form to text file PHP scripthere 

IMPORTANT: Do not forget to change the $filepath to reflect your own exact path.

[gp-comments width="770" linklove="off" ]

chat