Php write to file stream

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» ;

// 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 ;
>
?>

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 );

Читайте также:  Отправляем JSON-данные на сервер

// 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 ;
>
?>

if you need a function that writes all data, maybe try

/**
* writes all data or throws
*
* @param mixed $handle
* @param string $data
* @throws \RuntimeException when fwrite returned * @return void
*/
/*private static*/ function fwrite_all ( $handle , string $data ): void
$original_len = strlen ( $data );
if ( $original_len > 0 ) $len = $original_len ;
$written_total = 0 ;
for (;;) $written_now = fwrite ( $handle , $data );
if ( $written_now === $len ) return;
>
if ( $written_now < 1 ) throw new \ RuntimeException ( "could only write < $written_total >/ < $original_len >bytes!» );
>
$written_total += $written_now ;
$data = substr ( $data , $written_now );
$len -= $written_now ;
// assert($len > 0);
// assert($len === strlen($data));
>
>
>

Читайте также:  Python fix circular imports

$handles can also be used to output in console like below example

fwrite(STDOUT, «Console Output»);

Источник

PHP write to file — How to write to a text file using PHP

Posted on Jul 28, 2022

  • Use the file_put_contents() function
  • Use the fopen() , fwrite() , and fclose() functions

This tutorial will help you learn how to use both methods to write data to a file in PHP.

Let’s start with using the file_put_contents() function

PHP write to file with file_put_contents()

The file_put_contents() function is a built-in PHP function used for writing data to a file.

The syntax of the function is as follows:

The $filename and $data parameters are required while $flags and $context are optional.

The function returns the int number of bytes written to the file. When the write operation fails, it returns false or falsy numbers.

The code example below shows how to write a text to the example.txt file:

 The code above will produce the following result:

PHP write to file with file_put_contents

The file_put_contents() function will look for the file you passed as the $filename parameter.

When the file isn’t found, PHP will create the file. It will then write the data you passed as its $data parameter.

Once the write operation is finished, the function will automatically close the file from access.

  • FILE_USE_INCLUDE_PATH — Search for the file in the include path, which is set from the PHP configuration
  • FILE_APPEND — Append data to an existing file instead of overwriting it
  • LOCK_EX — Lock the file while you access it so others can’t edit

The flags can be joined with the binary OR operator ( | ) as follows:

 By default, file_put_contents() will overwrite the file data on write.

The FILE_APPEND flag will cause the function to append the data instead of overwriting it.

The $context flag is used to add a stream context for the operation. It’s can be useful when you’re writing to a remote file using an FTP connection.

And that’s how you use the file_put_contents() function to write data to a file in PHP.

Using fopen(), fwrite(), fclose() functions

The PHP fopen() , fwrite() , and fclose() functions are used to write data to a file.

Under the hood, these functions are similar to calling the file_put_contents() function, only in three separate steps:

Step #1 — Open the file using fopen()

  • The $filename for the file name
  • The $mode to specify the access mode to the file. Pass w for write and a for append

The code example below will cause PHP to look for the test.txt file:

The function returns a resource stream that you can use to write data into.

Step #2 — Write to the file using fwrite() and close it with fclose()

The fwrite() function is used to write to a file in PHP.

Here’s an example of writing to the stream:

   When your text has multiple lines, you can add the \n symbol to create a line break in your text.

Although PHP will close the file before exiting, you should close it manually using the fclose() function.

Closing a file using fclose() is considered good practice to avoid corrupting a file.

You can also crash the server when you open many files without closing them.

Conclusion

Now you’ve learned how to write data to a file in PHP.

You can use either file_put_contents() or the combination of fopen() , fwrite() , and fclose() depending on your requirements.

Thanks for reading! May this tutorial be useful for you 🙏

Take your skills to the next level ⚡️

I’m sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I’ll send new stuff straight into your inbox!

About

Hello! This website is dedicated to help you learn tech and data science skills with its step-by-step, beginner-friendly tutorials.
Learn statistics, JavaScript and other programming languages using clear examples written for people.

Type the keyword below and hit enter

Tags

Click to see all tutorials tagged with:

Источник

Оцените статью