PHP fputs() Function
The PHP fputs() function writes the specified string to the specified file stream. If the length argument is provided, writing will stop after length bytes have been written or the end of string is reached, whichever comes first.
This function is an alias of fwrite() function.
Syntax
fputs(stream string, length)
Parameters
stream |
Required. Specify the file pointer to write to. It must be valid, and must point to a file successfully opened by fopen() or fsockopen(). |
string |
Required. Specify the string that is to be written. |
length |
Optional. Specify the maximum number of bytes to write. |
Return Value
Returns the number of bytes written, or false on error.
Example: Writing to a file using write mode
Lets assume that we have a file called test.txt. This file contains following content:
This is a test file. It contains dummy content.
In the example below, the file is opened using 'w' mode. This places the file pointer at the beginning of the file and deletes its previous content. Hence, fputs() writes from the start of the file.
<?php //open the file in write mode $fp = fopen("test.txt", "w"); //write some content to it fputs($fp, 'A fresh content is added.'); //close the file fclose($fp); //open the file in read mode $fp = fopen("test.txt", "r") or die("Unable to open file!"); //reading the file line by line //and displaying the read content while(!feof($fp)) { echo fgets($fp); } //close the file fclose($fp); ?>
The output of the above code will be:
A fresh content is added.
Example: Writing multiple times using write mode
If this function is used multiple times, then the data will be appended to the end of the file content.
<?php //open the file in write mode $fp = fopen("test.txt", "w"); //write to the file multiple times fputs($fp, 'A fresh content is added.'); fputs($fp, ' More content is added.'); //close the file fclose($fp); //open the file in read mode $fp = fopen("test.txt", "r") or die("Unable to open file!"); //reading the file line by line //and displaying the read content while(!feof($fp)) { echo fgets($fp); } //close the file fclose($fp); ?>
The output of the above code will be:
A fresh content is added. More content is added.
Example: Writing to a file using append mode
When the file is opened using 'a' mode, the file pointer is placed at the end of the file. Hence, fputs() writes to the end of the file.
<?php //open the file in append mode $fp = fopen("test.txt", "a") or die("Unable to open file!"); //append third line to the file fputs($fp, PHP_EOL.'Third line is added.'); //close the file fclose($fp); //open the file in read mode $fp = fopen("test.txt", "r") or die("Unable to open file!"); //reading the file line by line //and displaying the read content while(!feof($fp)) { echo fgets($fp); } //close the file fclose($fp); ?>
The output of the above code will be:
This is a test file. It contains dummy content. Third line is added.
❮ PHP Filesystem Reference