Write text into a text file with PHP
I have created a PHP file named “text.php” and an empty text file named “atextfile.txt”. Both files have uploaded into the same directory.
To be able to write into the text file “atextfile.txt”, we have to set the file permission of “atextfile.txt” to “777″ in order for it to be writable. This process can be done with most of the FTP softwares.
Now here are the codes of the “text.php” file:
First we create a PHP variable to store the full name of the text file:
$tempfile="atextfile.txt";
We now use the PHP function fopen() to open the text file and make it ready to write, “w” is to set the text file to write only.
$fileprocess=fopen($tempfile,"w");
We then create the text which we like to write it into the text file. We use a PHP variable to store the text.
$temptext = "hello world!";
Here we use the the PHP function fwrite() to write the text into the text file:
fwrite($fileprocess,$temptext);
At last we close the file:
fclose($fileprocess);
All together we have:
1 2 3 4 5 6 7 | <?php $tempfile="atextfile.txt"; $fileprocess=fopen($tempfile,"w"); $temptext = "hello world!"; fwrite($fileprocess,$temptext); fclose($fileprocess); ?> |
In this example, we can only write a line of text into the text file.
All text within the text file will be overwritten.
Similar Posts:
- Read one line of text from a text file with PHP
- Insert all array elements into MySQL database table’s different fields
- Join all elements of an array together and become a string
- MD5 – insert an encrypted string or password to the MySQL database with HTML form and PHP
- Fetch the data from a HTML form with PHP





Add A Comment