- Writing data to file in php
- fwrite
- Parameters
- Return Values
- Errors/Exceptions
- Changelog
- Examples
- Notes
- See Also
- User Contributed Notes 33 notes
- PHP File Create/Write
- PHP Create File — fopen()
- Example
- PHP File Permissions
- PHP Write to File — fwrite()
- Example
- PHP Overwriting
- Example
- PHP Append Text
- Example
- Complete PHP Filesystem Reference
Writing data to file in php
- Different ways to write a PHP code
- How to write comments in PHP ?
- Introduction to Codeignitor (PHP)
- How to echo HTML in PHP ?
- Error handling in PHP
- How to show All Errors in PHP ?
- How to Start and Stop a Timer in PHP ?
- How to create default function parameter in PHP?
- How to check if mod_rewrite is enabled in PHP ?
- Web Scraping in PHP Using Simple HTML DOM Parser
- How to pass form variables from one page to other page in PHP ?
- How to display logged in user information in PHP ?
- How to find out where a function is defined using PHP ?
- How to Get $_POST from multiple check-boxes ?
- How to Secure hash and salt for PHP passwords ?
- Program to Insert new item in array on any position in PHP
- PHP append one array to another
- How to delete an Element From an Array in PHP ?
- How to print all the values of an array in PHP ?
- How to perform Array Delete by Value Not Key in PHP ?
- Removing Array Element and Re-Indexing in PHP
- How to count all array elements in PHP ?
- How to insert an item at the beginning of an array in PHP ?
- PHP Check if two arrays contain same elements
- Merge two arrays keeping original keys in PHP
- PHP program to find the maximum and the minimum in array
- How to check a key exists in an array in PHP ?
- PHP | Second most frequent element in an array
- Sort array of objects by object fields in PHP
- PHP | Sort array of strings in natural and standard orders
- How to pass PHP Variables by reference ?
- How to format Phone Numbers in PHP ?
- How to use php serialize() and unserialize() Function
- Implementing callback in PHP
- PHP | Merging two or more arrays using array_merge()
- PHP program to print an arithmetic progression series using inbuilt functions
- How to prevent SQL Injection in PHP ?
- How to extract the user name from the email ID using PHP ?
- How to count rows in MySQL table in PHP ?
- How to parse a CSV File in PHP ?
- How to generate simple random password from a given string using PHP ?
- How to upload images in MySQL using PHP PDO ?
- How to check foreach Loop Key Value in PHP ?
- How to properly Format a Number With Leading Zeros in PHP ?
- How to get a File Extension in PHP ?
- How to get the current Date and Time in PHP ?
- PHP program to change date format
- How to convert DateTime to String using PHP ?
- How to get Time Difference in Minutes in PHP ?
- Return all dates between two dates in an array in PHP
- Sort an array of dates in PHP
- How to get the time of the last modification of the current page in PHP?
- How to convert a Date into Timestamp using PHP ?
- How to add 24 hours to a unix timestamp in php?
- Sort a multidimensional array by date element in PHP
- Convert timestamp to readable date/time in PHP
- PHP | Number of week days between two dates
- PHP | Converting string to Date and DateTime
- How to get last day of a month from date in PHP ?
- PHP | Change strings in an array to uppercase
- How to convert first character of all the words uppercase using PHP ?
- How to get the last character of a string in PHP ?
- How to convert uppercase string to lowercase using PHP ?
- How to extract Numbers From a String in PHP ?
- How to replace String in PHP ?
- How to Encrypt and Decrypt a PHP String ?
- How to display string values within a table using PHP ?
- How to write Multi-Line Strings in PHP ?
- How to check if a String Contains a Substring in PHP ?
- How to append a string in PHP ?
- How to remove white spaces only beginning/end of a string using PHP ?
- How to Remove Special Character from String in PHP ?
- How to create a string by joining the array elements using PHP ?
- How to prepend a string in PHP ?
fwrite
fwrite() writes the contents of data to the file stream pointed to by stream .
Parameters
A file system pointer resource that is typically created using fopen() .
The string that is to be written.
If length is an int , writing will stop after length bytes have been written or the end of data is reached, whichever comes first.
Return Values
fwrite() returns the number of bytes written, or false on failure.
Errors/Exceptions
fwrite() raises E_WARNING on failure.
Changelog
Examples
Example #1 A simple fwrite() example
$filename = ‘test.txt’ ;
$somecontent = «Add this to the file\n» ;
?php
// Let’s make sure the file exists and is writable first.
if ( is_writable ( $filename ))
// In our example we’re opening $filename in append mode.
// The file pointer is at the bottom of the file hence
// that’s where $somecontent will go when we fwrite() it.
if (! $fp = fopen ( $filename , ‘a’ )) echo «Cannot open file ( $filename )» ;
exit;
>
// Write $somecontent to our opened file.
if ( fwrite ( $fp , $somecontent ) === FALSE ) echo «Cannot write to file ( $filename )» ;
exit;
>
echo «Success, wrote ( $somecontent ) to file ( $filename )» ;
> else echo «The file $filename is not writable» ;
>
?>
Notes
Note:
Writing to a network stream may end before the whole string is written. Return value of fwrite() may be checked:
function fwrite_stream ( $fp , $string ) for ( $written = 0 ; $written < strlen ( $string ); $written += $fwrite ) $fwrite = fwrite ( $fp , substr ( $string , $written ));
if ( $fwrite === false ) return $written ;
>
>
return $written ;
>
?>?php
Note:
On systems which differentiate between binary and text files (i.e. Windows) the file must be opened with ‘b’ included in fopen() mode parameter.
Note:
If stream was fopen() ed in append mode, fwrite() s are atomic (unless the size of data exceeds the filesystem’s block size, on some platforms, and as long as the file is on a local filesystem). That is, there is no need to flock() a resource before calling fwrite() ; all of the data will be written without interruption.
Note:
If writing twice to the file pointer, then the data will be appended to the end of the file content:
$fp = fopen ( ‘data.txt’ , ‘w’ );
fwrite ( $fp , ‘1’ );
fwrite ( $fp , ’23’ );
fclose ( $fp );
?php
// the content of ‘data.txt’ is now 123 and not 23!
?>
See Also
- fread() — Binary-safe file read
- fopen() — Opens file or URL
- fsockopen() — Open Internet or Unix domain socket connection
- popen() — Opens process file pointer
- file_get_contents() — Reads entire file into a string
- pack() — Pack data into binary string
User Contributed Notes 33 notes
After having problems with fwrite() returning 0 in cases where one would fully expect a return value of false, I took a look at the source code for php’s fwrite() itself. The function will only return false if you pass in invalid arguments. Any other error, just as a broken pipe or closed connection, will result in a return value of less than strlen($string), in most cases 0.
Therefore, looping with repeated calls to fwrite() until the sum of number of bytes written equals the strlen() of the full value or expecting false on error will result in an infinite loop if the connection is lost.
This means the example fwrite_stream() code from the docs, as well as all the «helper» functions posted by others in the comments are all broken. You *must* check for a return value of 0 and either abort immediately or track a maximum number of retries.
Below is the example from the docs. This code is BAD, as a broken pipe will result in fwrite() infinitely looping with a return value of 0. Since the loop only breaks if fwrite() returns false or successfully writes all bytes, an infinite loop will occur on failure.
// BROKEN function — infinite loop when fwrite() returns 0s
function fwrite_stream ( $fp , $string ) <
for ( $written = 0 ; $written < strlen ( $string ); $written += $fwrite ) <
$fwrite = fwrite ( $fp , substr ( $string , $written ));
if ( $fwrite === false ) <
return $written ;
>
>
return $written ;
>
?>
$handles can also be used to output in console like below example
fwrite(STDOUT, «Console Output»);
PHP File Create/Write
In this chapter we will teach you how to create and write to a file on the server.
PHP Create File — fopen()
The fopen() function is also used to create a file. Maybe a little confusing, but in PHP, a file is created using the same function used to open files.
If you use fopen() on a file that does not exist, it will create it, given that the file is opened for writing (w) or appending (a).
The example below creates a new file called «testfile.txt». The file will be created in the same directory where the PHP code resides:
Example
PHP File Permissions
If you are having errors when trying to get this code to run, check that you have granted your PHP file access to write information to the hard drive.
PHP Write to File — fwrite()
The fwrite() function is used to write to a file.
The first parameter of fwrite() contains the name of the file to write to and the second parameter is the string to be written.
The example below writes a couple of names into a new file called «newfile.txt»:
Example
$myfile = fopen(«newfile.txt», «w») or die(«Unable to open file!»);
$txt = «John Doe\n»;
fwrite($myfile, $txt);
$txt = «Jane Doe\n»;
fwrite($myfile, $txt);
fclose($myfile);
?>?php
Notice that we wrote to the file «newfile.txt» twice. Each time we wrote to the file we sent the string $txt that first contained «John Doe» and second contained «Jane Doe». After we finished writing, we closed the file using the fclose() function.
If we open the «newfile.txt» file it would look like this:
PHP Overwriting
Now that «newfile.txt» contains some data we can show what happens when we open an existing file for writing. All the existing data will be ERASED and we start with an empty file.
In the example below we open our existing file «newfile.txt», and write some new data into it:
Example
$myfile = fopen(«newfile.txt», «w») or die(«Unable to open file!»);
$txt = «Mickey Mouse\n»;
fwrite($myfile, $txt);
$txt = «Minnie Mouse\n»;
fwrite($myfile, $txt);
fclose($myfile);
?>?php
If we now open the «newfile.txt» file, both John and Jane have vanished, and only the data we just wrote is present:
PHP Append Text
You can append data to a file by using the «a» mode. The «a» mode appends text to the end of the file, while the «w» mode overrides (and erases) the old content of the file.
In the example below we open our existing file «newfile.txt», and append some text to it:
Example
$myfile = fopen(«newfile.txt», «a») or die(«Unable to open file!»);
$txt = «Donald Duck\n»;
fwrite($myfile, $txt);
$txt = «Goofy Goof\n»;
fwrite($myfile, $txt);
fclose($myfile);
?>?php
If we now open the «newfile.txt» file, we will see that Donald Duck and Goofy Goof is appended to the end of the file:
Complete PHP Filesystem Reference
For a complete reference of filesystem functions, go to our complete PHP Filesystem Reference.