Using PHP fputs() to Write Data to Files
The article explains PHP's fputs() function, detailing its syntax, parameters, return values, and provides a complete example showing how to open a file with fopen(), write a string, handle the result, and close the file with fclose() to ensure proper resource management.
In PHP, the fputs() function is used to write data to a file.
Syntax:
fputs ( resource $handle , string $string [, int $length ] ) : int|boolParameters:
$handle : file resource handle, typically obtained via fopen() .
$string : the string to be written.
$length (optional): maximum number of bytes to write; defaults to the length of $string .
Return value:
Returns the number of bytes written on success, or false on failure.
Example:
The script opens demo.txt for writing, writes the string “Hello, World!”, checks the result, and closes the file to release the resource.
Note that the file must be opened in a writable mode (e.g., using fopen() with the “w” flag) before calling fputs() , and you should always close the handle with fclose() after writing.
Summary
The fputs() function provides a straightforward way to write strings to files in PHP, but proper opening modes and closing of file handles are essential for correct operation.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.