- 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
- fwrite
- Parameters
- Return Values
- Errors/Exceptions
- Changelog
- Examples
- Notes
- See Also
- User Contributed Notes 33 notes
- file_put_contents
- Список параметров
- Возвращаемые значения
- Примеры
- Список изменений
- Примечания
- Смотрите также
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.
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 ;
>
?>
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));
>
>
>
$handles can also be used to output in console like below example
fwrite(STDOUT, «Console Output»);
file_put_contents
Функция идентична последовательным успешным вызовам функций fopen() , fwrite() и fclose() .
Если filename не существует, файл будет создан. Иначе, существующий файл будет перезаписан, за исключением случая, если указан флаг FILE_APPEND .
Список параметров
Путь к записываемому файлу.
Записываемые данные. Может быть string , array или ресурсом stream .
Если data является ресурсом stream , оставшийся буфер этого потока будет скопирован в указанный файл. Это похоже на использование функции stream_copy_to_stream() .
Также вы можете передать одномерный массив в качестве параметра data . Это будет эквивалентно вызову file_put_contents($filename, implode(», $array)).
Значением параметра flags может быть любая комбинация следующих флагов, соединенных бинарным оператором ИЛИ (|).
Флаг | Описание |
---|---|
FILE_USE_INCLUDE_PATH | Ищет filename в подключаемых директориях. Подробнее смотрите директиву include_path. |
FILE_APPEND | Если файл filename уже существует, данные будут дописаны в конец файла вместо того, чтобы его перезаписать. |
LOCK_EX | Получить эксклюзивную блокировку на файл на время записи. |
Корректный ресурс контекста, созданный с помощью функции stream_context_create() .
Возвращаемые значения
Функция возвращает количество записанных байт в файл, или FALSE в случае ошибки.
Эта функция может возвращать как boolean FALSE , так и не-boolean значение, которое приводится к FALSE . За более подробной информацией обратитесь к разделу Булев тип. Используйте оператор === для проверки значения, возвращаемого этой функцией.
Примеры
Пример #1 Пример простого использования
$file = ‘people.txt’ ;
// Открываем файл для получения существующего содержимого
$current = file_get_contents ( $file );
// Добавляем нового человека в файл
$current .= «John Smith\n» ;
// Пишем содержимое обратно в файл
file_put_contents ( $file , $current );
?>?php
Пример #2 Использование флагов
$file = ‘people.txt’ ;
// Новый человек, которого нужно добавить в файл
$person = «John Smith\n» ;
// Пишем содержимое в файл,
// используя флаг FILE_APPEND flag для дописывания содержимого в конец файла
// и флаг LOCK_EX для предотвращения записи данного файла кем-нибудь другим в данное время
file_put_contents ( $file , $person , FILE_APPEND | LOCK_EX );
?>?php
Список изменений
Версия | Описание |
---|---|
5.1.0 | Добавлена поддержка LOCK_EX и возможность передачи потокового ресурса в параметр data |
Примечания
Замечание: Эта функция безопасна для обработки данных в двоичной форме.
Для этой функции вы можете использовать URL в качестве имени файла, если была включена опция fopen wrappers. Смотрите более подробную информацию об определении имени файла в описании функции fopen() . Смотрите также список поддерживаемых оберток URL, их возможности, замечания по использованию и список предопределенных констант в Поддерживаемые протоколы и обработчики (wrappers).
Смотрите также
- fopen() — Открывает файл или URL
- fwrite() — Бинарно-безопасная запись в файл
- file_get_contents() — Читает содержимое файла в строку
- stream_context_create() — Создаёт контекст потока