In PHP, the fputs() function is used to write a string to an open file. The basic syntax is as follows:
<span class="fun">fputs(resource $handle, string $string[, int $length]) : int|bool</span>
The function returns the number of bytes written if successful, or false on failure.
<?php
$file = fopen("demo.txt", "w");
<p>if ($file) {<br>
$content = "Hello, World!";<br>
$length = fputs($file, $content);</p>
echo "Write successful, a total of " . $length . " bytes written.";
} else {
echo "Write failed.";
}
fclose($file);
}
?>
The example above opens a file named demo.txt and writes the string "Hello, World!" into it. If successful, it returns the number of bytes written, or false on failure.
When using fputs() to write to a file, make sure the file is opened in a writable mode. In the example, we used fopen() with the write mode ("w") to open the file. After writing, we used fclose() to close the file and release resources.
The fputs() function is a commonly used function in PHP for writing content to files. Understanding its parameters and return values helps in performing efficient file operations and data storage.