What is fputs in PHP?

PHP offers many functions for file manipulation. The fputs function in PHP writes content to an already open file; it is similar to the fwrite function.

Syntax

The syntax for the fputs function is shown below:

fputs(resource file, string str, int length)

Parameters

The fputs function can take three parameters:

  • file: This is a required parameter. file is the pointer of the file stream that points to an already open file. The string will be written to this file.
  • str: This is a required parameter. str is the string we want to write to the open file.
  • length: This is an optional parameter. The length parameter specifies the number of bytes to write to the file.

Return value

Upon successful execution, the fputs function returns the number of bytes written to the file. Upon failure or error, it returns false.

The fputs function writes a string to a file

Code

The following code shows how we can use the fputs function. The function writes the text "Hello World!" to the file and displays the number of characters written.

main.php
test.txt
<?php
$file = fopen("test.txt","w");
echo fwrite($file,"Hello, World!");
fclose($file);
?>
Copyright ©2024 Educative, Inc. All rights reserved