Thursday, October 23, 2025
HomeLanguagesPHP | fputs( ) Function

PHP | fputs( ) Function

The fputs() function in PHP is an inbuilt function which is used to write to an open file.
The fputs() function stops at the end of the file or when it reaches the specified length passed as a parameter, whichever comes first.
The file, string and the length which has to be written are sent as parameters to the fputs() function and it returns the number of bytes written on success, or FALSE on failure.
The fputs() function is an alias of the fwrite() function.

Syntax:

fputs(file, string, length)

Parameters Used:
The fputs() function in PHP accepts three parameters.

  1. file: It is a mandatory parameter which specifies the file.
  2. string : It is a mandatory parameter which specifies the string to be written.
  3. length : It is an optional parameter which specifies the maximum number of bytes to be written.

Return Value:
It returns the number of bytes written on success, or False on failure.

Exceptions

  1. Both binary data, like images and character data can be written with this function since fputs() is binary-safe.
  2. fputs() function without the length parameter writes all data up to the end but it does not include the first 0th byte it encounters.

Examples:

Input : $myfile = fopen("gfg.txt", "w");
        echo fputs($myfile, "Geeksforneveropen is a portal of neveropen!");
        fclose($myfile);
Output : 35

Input : $myfile = fopen("gfg.txt", "w");
        echo fputs($myfile, "Geeksforneveropen is a portal of neveropen!", 13);
        fclose($myfile);
        fopen("gfg.txt", "r");
        echo fread($myfile, filesize("gfg.txt"));
        fclose($myfile);
Output : Geeksforneveropen

Below programs illustrate the fputs() function:

Program 1




<?php
// Opening a file
$myfile = fopen("gfg.txt", "w");
  
// writing content to a file using fputs
echo fputs($myfile, "Geeksforneveropen is a portal of neveropen!");
  
// closing the file
fclose($myfile);
?>


Output:

35

Program 2




<?php
// Opening a file
$myfile = fopen("gfg.txt", "w");
  
// writing content to a file with a specified string length using fputs
echo fputs($myfile, "Geeksforneveropen is a portal of neveropen!", 13);
  
// closing the file
fclose($myfile);
  
//opening the same file to read its contents        
fopen("gfg.txt", "r");
echo fread($myfile, filesize("gfg.txt"));
  
// closing the file
fclose($myfile);
?>


Output:

Geeksforneveropen

Reference :
http://php.net/manual/en/function.fputs.php

RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS