fputs() function in PHP


Write to an open file using the fpus() function in PHP. It is an alias of fwrite(). The fputs() function returns the number of bytes written on success. It returns FALSE on failure.

The fputs() function halts at the end of the file or when it reaches the specified length whichever comes first.

Syntax

fputs(file_pointer, string, length)

Parameters

  • file_pointer − A file pointer created using fopen(). Required.

  • string − A string to be written. Required.

  • length − Maximum bytes to write. Optional.

Return

The fputs() function returns the number of bytes written on success. It returns FALSE on failure.

Example

<?php
   $file_pointer = fopen("new.txt","w");
   echo fputs($file,"This is demo text!");
   fclose($file_pointer);
?>

The following is the output. It returns the number of bytes written.

Output

18

Let us see another example which writes a specified number of bytes to the file. The content is also read and displayed.

Example

<?php
   $file_pointer = fopen("new.txt","w");
   echo fputs($file,"This is demo text!",4);
   fclose($file_pointer);
   fopen("new.txt", "r");
   echo fread($file_pointer, filesize("new.txt"));
   fclose($file_pointer);
?>

Output

4

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 24-Jun-2020

666 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements