Php дописать в конец файла
fwrite() записывает содержимое string в файловый поток handle .
Содержание
Возвращаемые значения
Функция возвращает количество записанных байт в файл, или false в случае возникновения ошибки.
Эта функция может возвращать как логическое значение false , так и значение не типа boolean, которое приводится к false . За более подробной информацией обратитесь к разделу Булев тип. Используйте оператор === для проверки значения, возвращаемого этой функцией.
Примеры
$file = 'people.txt' ;
// Открываем файл для получения существующего содержимого
$current = file_get_contents ( $file );
// Добавляем нового человека в файл
$current .= "John Smith\n" ;
// Пишем содержимое обратно в файл
file_put_contents ( $file , $current );
?>?php
$file = 'people.txt' ;
// Новый человек, которого нужно добавить в файл
$person = "John Smith\n" ;
// Пишем содержимое в файл,
// используя флаг FILE_APPEND flag для дописывания содержимого в конец файла
// и флаг LOCK_EX для предотвращения записи данного файла кем-нибудь другим в данное время
file_put_contents ( $file , $person , FILE_APPEND | LOCK_EX );
?>?php
Примеры
$filename = 'test.txt' ;
$somecontent = "Добавить это к файлу\n" ;
// Вначале давайте убедимся, что файл существует и доступен для записи.
if ( is_writable ( $filename ))
// В нашем примере мы открываем $filename в режиме "записи в конец".
// Таким образом, смещение установлено в конец файла и
// наш $somecontent допишется в конец при использовании fwrite().
if (! $fp = fopen ( $filename , 'a' )) echo "Не могу открыть файл ( $filename )" ;
exit;
>
// Записываем $somecontent в наш открытый файл.
if ( fwrite ( $fp , $somecontent ) === FALSE ) echo "Не могу произвести запись в файл ( $filename )" ;
exit;
>
echo "Ура! Записали ( $somecontent ) в файл ( $filename )" ;
> else echo "Файл $filename недоступен для записи" ;
>
?>
Примеры
$file = 'people.txt' ;
// Открываем файл для получения существующего содержимого
$current = file_get_contents ( $file );
// Добавляем нового человека в файл
$current .= "John Smith\n" ;
// Пишем содержимое обратно в файл
file_put_contents ( $file , $current );
?>?php
$file = 'people.txt' ;
// Новый человек, которого нужно добавить в файл
$person = "John Smith\n" ;
// Пишем содержимое в файл,
// используя флаг FILE_APPEND для дописывания содержимого в конец файла
// и флаг LOCK_EX для предотвращения записи данного файла кем-нибудь другим в данное время
file_put_contents ( $file , $person , FILE_APPEND | LOCK_EX );
?>?php
Список параметров
Путь к записываемому файлу.
Записываемые данные. Может быть 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() .
Возвращаемые значения
fwrite() возвращает количество записанных байт или FALSE в случае ошибки.
User Contributed Notes 8 notes
I just learned that, to specify file names in a portable manner, you DON'T need 'DIRECTORY_SEPARATOR' - just use '/'. This really surprised and shocked me, as until now I typed about a zillion times 'DIRECTORY_SEPARATOR' to stay platform independent - unnecessary. Don't make the same mistake.
You have an array of directories (straightforward list of directories):
$array = array(
'/home/drapeko/var' ,
'/home/drapeko/var/y' ,
'/home/drapeko' ,
'/home' ,
'/var/libexec'
);
);
?>
And you would like to transform this array to hierarchy of directories:
$array = array (
'home' => array (
'drapeko' => array (
'var' => array (
'y' => array()
)
)
),
'var' => array(
'libexec' => array()
)
);
?>
How can you do it?
First of all the below function will help us.
/**
* This function converts real filesystem path to the string array representation.
*
* for example,
* '/home/drapeko/var/y will be converted to $result_array['home']['drapeko']['var']['y']
* '/home/drapeko/var/y/file.txt will be converted to $result_array['home']['drapeko']['var']['y']
*
* @param $path realpath of the directory
* @return string string array representation of the path
*/
function pathToArrayStr ( $path ) <
// TODO constants/configs?
$res_path = str_replace (array( ':/' , ':\\' , '/' , '\\' , DIRECTORY_SEPARATOR ), '/' , $path );
// if the first or last symbol is '/' delete it (e.g. for linux)
$res_path = preg_replace (array( "/^\//" , "/\/$/" ), '' , $res_path );
// create string
$res_path = '[\'' . str_replace ( '/' , '\'][\'' , $res_path ). '\']' ;
return $res_path ;
>
?>
It simply converts the real path of the file to array string representation.
How can you use this function? I know it looks like a little confusing. But it's quite simple. Consider the example below:
$result = array();
$check = array();
foreach( $array as $val ) <
$str = pathToArrayStr ( $val , 'result' );
foreach( $check as $ck ) <
if ( strpos ( $ck , $str ) !== false ) <
continue 2 ;
>
>
$check [] = $str ;
eval( '$result' . $str . ' = array();' );
>
print_r ( $result );
?>
Heh, how do you find it? This approach has helped me very much. I hope you will find it useful. :)
I made this function to search and/or display files by extension or for a string occurance in the filename. Any comments or enhancements are welcome offcourse. I'll update this function soon.
usage: list_files([string], [string], [int 1 | 0], [int 1 | 0]);
search for extension: list_files([string], [string], [0], [int 1 | 0]);
returns array: $myArray = list_files([string], [string], [0], [0]);
echo result: list_files([string], [string], [0], [1]);
search for string occurance: list_files([string], [string], [1], [int 1 | 0]);
returns array: $myArray = list_files([string], [string], [1], [0]);
echo result: list_files([string], [string], [1], [1]);
function list_files ( $directory , $stringSearch , $searchHandler , $outputHandler ) $errorHandler = false ;
$result = array();
if (! $directoryHandler = @ opendir ( $directory )) echo ( "
\nerror: directory \" $directory \" doesn't exist!\n\n" );
return $errorHandler = true ;
>
if ( $searchHandler === 0 ) while ( false !== ( $fileName = @ readdir ( $directoryHandler ))) if(@ substr ( $fileName , - @ strlen ( $stringSearch )) === $stringSearch ) @ array_push ( $result , $fileName );
>
>
>
if ( $searchHandler === 1 ) while( false !== ( $fileName = @ readdir ( $directoryHandler ))) if(@ substr_count ( $fileName , $stringSearch ) > 0 ) @ array_push ( $result , $fileName );
>
>
>
if (( $errorHandler === true ) && (@ count ( $result ) === 0 )) echo ( "
\nerror: no filetype \" $fileExtension \" found!\n\n" );
>
else sort ( $result );
if ( $outputHandler === 0 ) return $result ;
>
if ( $outputHandler === 1 ) echo ( "
\n" );\n" );
print_r ( $result );
echo ( "
>
>
>
This function searches a directory and returns an array of all files whose filename matches the specified regular expression. It's similar in concept to the Unix find program.
function findfile($location='',$fileregex='') if (!$location or !is_dir($location) or !$fileregex) return false;
>
$all = opendir($location);
while ($file = readdir($all)) if (is_dir($location.'/'.$file) and $file <> ".." and $file <> ".") $subdir_matches = findfile($location.'/'.$file,$fileregex);
$matchedfiles = array_merge($matchedfiles,$subdir_matches);
unset($file);
>
elseif (!is_dir($location.'/'.$file)) if (preg_match($fileregex,$file)) array_push($matchedfiles,$location.'/'.$file);
>
>
>
closedir($all);
unset($all);
return $matchedfiles;
>
ini_set ( 'auto_detect_line_endings' , true );
$contents = file ( 'unknowntype.txt' );
ini_set ( 'auto_detect_line_endings' , false );
$content2 = file ( 'unixfile.txt' );
?>
Note, with PHP 4.3 anytime Mac files are read using fgets or file you'll need to auto_detect_line_endings since \n is otherwise assumed. However, with PHP 5.0, stream_get_line() will allow you to specify what line ending character to read up to.
\\ Read a line from a MAC file
stream_get_line($fp, 4096, "\r");
\\ Read a line from a UNIX file
stream_get_line($fp, 4096, "\n");
\\ Read a line from a DOS file
stream_get_line($fp, 4096, "\r\n");
\\ Read a line up to any filesystem line ending
ini_set('auto_detect_line_endings', true); fgets($fp);
\\ You can also make up your own line ending characters:
\\ Read up to the first instance of ":"
stream_get_line($fp, 4096, ":");
This is a function I use to determine if a file contains Binary information. I use this for my search engine so that it doesn't try to index files like .zip or .mp3 or any other file that doesn't contain readable information. It makes use of the Character Type Extension if it's loaded, if it's not then it uses Regular Expressions.
function is_binary($link)
$tmpStr = '';
@$fp = fopen($link, 'rb');
@$tmpStr = fread($fp, 256);
@fclose($fp);
if($tmpStr != '')
$tmpStr = str_replace(chr(10), '', $tmpStr);
$tmpStr = str_replace(chr(13), '', $tmpStr);
a function based on "tunnelareaten at gmail dot com"s idea to search for files in a given directory by a searchstring or by fileextension.
I added support to search recursively through all sub-directories an to determine weather the filepath should be returned or not.
// recursive function to get contents of given folder by searchterm or fileextension
// (does not show folders)
// standards: Foldername: string
// Searchterm: string
// Searchtype: ext/search (file-extension or searchterm within filename)
// SaveCompletePath: true/1
// usage: array FileSearch_r($Folder,$Search[,$SearchType,$SavePath])
function FileSearch_r ( $Dir , $Search , $SearchType = "search" , $SavePath = 1 ) $Array =array();
$D = dir ( $Dir );
while ( false !==( $Entry = $D -> read ()))
if ( $Entry != '.' && $Entry != '..' ) $Entry = $Dir . $Entry ;
if ( is_dir ( $Entry )) $Array = array_merge ( $Array , FileSearch_r ( $Entry . '/' , $Search , $SearchType , $SavePath ));
else
if ( $SearchType == "search"
? substr_count ( $Entry , $Search )> 0
:( $SearchType == "ext"
? substr ( $Entry ,- strlen ( $Search ))=== $Search
: true ))
$Array []= $Entry ;
>
$D -> close ();
sort ( $Array , SORT_STRING );
if(!(bool) $SavePath ) $Array = str_replace ( $Dir , "" , array_values ( $Array ));
return $Array ;
>
?>
Here is a useful function if you're having trouble writing raw bytes into a file.
It receives an integer and returns an array containing the ASCII values of the bytes on each index of the array.
function int2bytes($number) $byte = $number;
$i=0;
do $dec_tmp = $byte;
$byte = bcdiv($byte,256,0);
$resto = $dec_tmp - (256 * $byte);
$return[] = $resto;
> while($byte >= 256);
if($byte) $return[] = $byte;
return array_reverse($return);
>
$arr will contain the following values:
Array
(
[0] => 1
[1] => 40
[2] => 56
)
Now, to write this data to the file, just use a fputs() with chr(), just like this:
Функция идентична последовательным успешным вызовам функций fopen() , fwrite() и fclose() .
Если filename не существует, файл будет создан. Иначе, существующий файл будет перезаписан, за исключением случая, если указан флаг FILE_APPEND .
Список параметров
Путь к записываемому файлу.
Записываемые данные. Может быть типа string , array или ресурсом потока.
Если 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 | Получить эксклюзивную блокировку на файл на время записи. Другими словами, между вызовами fopen() и fwrite() произойдёт вызов функции flock() . Это не одно и то же, что вызов fopen() с флагом "x". |
Корректный ресурс контекста, созданный с помощью функции stream_context_create() .
Список изменений
Версия | Описание |
---|---|
8.0.0 | Параметр length теперь допускает значение null . |
Примечания
Замечание: Эта функция безопасна для обработки данных в двоичной форме.
Для этой функции вы можете использовать URL в качестве имени файла, если была включена опция fopen wrappers. Смотрите более подробную информацию об определении имени файла в описании функции fopen() . Смотрите также список поддерживаемых оберток URL, их возможности, замечания по использованию и список предопределенных констант в Поддерживаемые протоколы и обработчики (wrappers).
Возвращаемые значения
fwrite() возвращает количество записанных байт или false в случае возникновения ошибки.
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));
>
>
>
Описание родственных функций вы сможете найти в разделах Каталоги и Выполнение программ.
За списком обёрток URL для работы с удалёнными файлами и пояснениями обращайтесь к главе Поддерживаемые протоколы и обёртки.
Смотрите также
- fread() - Бинарно-безопасное чтение файла
- fopen() - Открывает файл или URL
- fsockopen() - Открывает соединение с интернет-сокетом или доменным сокетом Unix
- popen() - Открывает файловый указатель процесса
- file_get_contents() - Читает содержимое файла в строку
- pack() - Упаковать данные в бинарную строку
Список параметров
Указатель ( resource ) на файл, обычно создаваемый с помощью функции fopen() .
Если передан аргумент length , запись остановится после того, как length байтов будут записаны или будет достигнут конец строки string , смотря что произойдёт первым.
Учтите, что если указан аргумент length , то директива magic_quotes_runtime будет проигнорирована и строка string не будет очищена от слешей.
User Contributed Notes 37 notes
File put contents fails if you try to put a file in a directory that doesn't exist. This creates the directory.
function file_force_contents ( $dir , $contents ) $parts = explode ( '/' , $dir );
$file = array_pop ( $parts );
$dir = '' ;
foreach( $parts as $part )
if(! is_dir ( $dir .= "/ $part " )) mkdir ( $dir );
file_put_contents ( " $dir / $file " , $contents );
>
?>
It should be obvious that this should only be used if you're making one write, if you are writing multiple times to the same file you should handle it yourself with fopen and fwrite, the fclose when you are done writing.
file_put_contents() for 1,000,000 writes - average of 3 benchmarks:
real 0m3.932s
user 0m2.487s
sys 0m1.437s
fopen() fwrite() for 1,000,000 writes, fclose() - average of 3 benchmarks:
real 0m2.265s
user 0m1.819s
sys 0m0.445s
function file_force_contents ( $fullPath , $contents , $flags = 0 ) $parts = explode ( '/' , $fullPath );
array_pop ( $parts );
$dir = implode ( '/' , $parts );
if( ! is_dir ( $dir ) )
mkdir ( $dir , 0777 , true );
file_put_contents ( $fullPath , $contents , $flags );
>
file_force_contents ( ROOT . '/newpath/file.txt' , 'message' , LOCK_EX );
?>
Please note that when saving using an FTP host, an additional stream context must be passed through telling PHP to overwrite the file.
/* set the FTP hostname */
$user = "test" ;
$pass = "myFTP" ;
$host = "example.com" ;
$file = "test.txt" ;
$hostname = $user . ":" . $pass . "@" . $host . "/" . $file ;
/* the file content */
$content = "this is just a test." ;
/* create a stream context telling PHP to overwrite the file */
$options = array( 'ftp' => array( 'overwrite' => true ));
$stream = stream_context_create ( $options );
/* and finally, put the contents */
file_put_contents ( $hostname , $content , 0 , $stream );
?>
It's important to understand that LOCK_EX will not prevent reading the file unless you also explicitly acquire a read lock (shared locked) with the PHP 'flock' function.
i.e. in concurrent scenarios file_get_contents may return empty if you don't wrap it like this:
$myfile = fopen ( 'test.txt' , 'rt' );
flock ( $myfile , LOCK_SH );
$read = file_get_contents ( 'test.txt' );
fclose ( $myfile );
?>
If you have code that does a file_get_contents on a file, changes the string, then re-saves using file_put_contents, you better be sure to do this correctly or your file will randomly wipe itself out.
Make sure not to corrupt anything in case of failure.
function file_put_contents_atomically ( $filename , $data , $flags = 0 , $context = null ) if ( file_put_contents ( $filename . "~" , $data , $flags , $context ) === strlen ( $contents )) return rename ( $filename . "~" , $filename , $context );
>
@ unlink ( $filename . "~" , $context );
return FALSE ;
>
This functionality is now implemented in the PEAR package PHP_Compat.
More information about using this function without upgrading your version of PHP can be found on the below link:
It's worth noting that you must make sure to use the correct path when working with this function. I was using it to help with logging in an error handler and sometimes it would work - while other times it wouldn't. In the end it was because sometimes it was called from different paths resulting in a failure to write to the log file.
__DIR__ is your friend.
File put contents fails if you try to put a file in a directory that doesn't exist. This function creates the directory.
file_force_contents ( 'test1.txt' , 'test1 content' ); // test1.txt created
file_force_contents ( 'test2/test2.txt' , 'test2 content' );
// test2/test2.txt created "test2" folder.
file_force_contents ( '~/test3/test3.txt' , 'test3 content' );
// /path/to/user/directory/test3/test3.txt created "test3" folder in user directory (check on linux "ll ~/ | grep test3").
?>
In reply to the previous note:
If you want to emulate this function in PHP4, you need to return the bytes written as well as support for arrays, flags.
I can only figure out the FILE_APPEND flag and array support. If I could figure out "resource context" and the other flags, I would include those too.
define('FILE_APPEND', 1);
function file_put_contents($n, $d, $flag = false) $mode = ($flag == FILE_APPEND || strtoupper($flag) == 'FILE_APPEND') ? 'a' : 'w';
$f = @fopen($n, $mode);
if ($f === false) return 0;
> else if (is_array($d)) $d = implode($d);
$bytes_written = fwrite($f, $d);
fclose($f);
return $bytes_written;
>
>
To upload file from your localhost to any FTP server.
pease note 'ftp_chdir' has been used instead of putting direct remote file path. in ftp_put . remoth file should be only file name
$host = '*****' ;
$usr = '*****' ;
$pwd = '**********' ;
$local_file = './orderXML/order200.xml' ;
$ftp_path = 'order200.xml' ;
$conn_id = ftp_connect ( $host , 21 ) or die ( "Cannot connect to host" );
ftp_pasv ( $resource , true );
ftp_login ( $conn_id , $usr , $pwd ) or die( "Cannot login" );
// perform file upload
ftp_chdir ( $conn_id , '/public_html/abc/' );
$upload = ftp_put ( $conn_id , $ftp_path , $local_file , FTP_ASCII );
if( $upload ) < $ftpsucc = 1 ; >else < $ftpsucc = 0 ; >
// check upload status:
print (! $upload ) ? 'Cannot upload' : 'Upload complete' ;
print "\n" ;
// close the FTP stream
ftp_close ( $conn_id );
?>
A more simplified version of the method that creates subdirectories:
function path_put_contents($filePath, $contents, $flags = 0)
if (! is_dir($dir = implode('/', explode('/', $filePath, -1))))
mkdir($dir, 0777, true);
file_put_contents($filePath, $contents, $flags);
>
I suggest to expand file_force_contents() function of TrentTompkins at gmail dot com by adding verification if patch is like: "../foo/bar/file"
if (strpos($dir, "../") === 0)
$dir = str_replace("..", substr(__DIR__, 0, strrpos(__DIR__, "/")), $dir);
file_put_contents does not issue an error message if file name is incorrect(for example has improper symbols on the end of it /n,/t)
that is why use trim() for file name.
$name=trim($name);
file_put_contents($name,$content);
I had some troubles using file_put_contents with an absolute but no canonicalized path (eg. w:/htdocs/pri/../test/log.txt): on windows environment php was unable to create the file also using the realpath function .
I had to use fopen and frwite functions to write the data.
I wrote this script implementing the file_put_contents() and file_get_contents() functions to be compatible with both php4.* and php 5.*. It is a PHP Command line interface script which searches and replaces a specific word recursively through all files in the supplied directory hierarchy.
Usage from a Linux command line: ./scriptname specifieddirectory searchString replaceString
if( $argc != 4 )
echo "This command replaces a search string with a replacement string\n for the contents of all files in a directory hierachy\n" ;
echo "command usage: $argv [ 0 ] directory searchString replaceString\n" ;
echo "\n" ;
exit;
>
?>
if (! function_exists ( 'file_put_contents' )) function file_put_contents ( $filename , $data ) $f = @ fopen ( $filename , 'w' );
if (! $f ) return false ;
> else $bytes = fwrite ( $f , $data );
fclose ( $f );
return $bytes ;
>
>
>
function get_file_contents ( $filename )
/* Returns the contents of file name passed
*/
if (! function_exists ( 'file_get_contents' ))
$fhandle = fopen ( $filename , "r" );
$fcontents = fread ( $fhandle , filesize ( $filename ));
fclose ( $fhandle );
>
else
$fcontents = file_get_contents ( $filename );
>
return $fcontents ;
>
?>
function openFileSearchAndReplace ( $parentDirectory , $searchFor , $replaceWith )
//echo "debug here- line 1a\n";
//echo "$parentDirectory\n";
//echo "$searchFor\n";
//echo "$replaceWith\n";
if ( $handle = opendir ( " $parentDirectory " )) while ( false !== ( $file = readdir ( $handle ))) if (( $file != "." && $file != ".." ) && ! is_dir ( $file )) chdir ( " $parentDirectory " ); //to make sure you are always in right directory
// echo "$file\n";
$holdcontents = file_get_contents ( $file );
$holdcontents2 = str_replace ( $searchFor , $replaceWith , $holdcontents );
file_put_contents ( $file , $holdcontents2 );
// echo "debug here- line 1\n";
// echo "$file\n";
>
if( is_dir ( $file ) && ( $file != "." && $file != ".." ))
$holdpwd = getcwd ();
//echo "holdpwd = $holdpwd \n";
$newdir = " $holdpwd " . "/ $file " ;
//echo "newdir = $newdir \n"; //for recursive call
openFileSearchAndReplace ( $newdir , $searchFor , $replaceWith );
//echo "debug here- line 2\n";
//echo "$file\n";
>
>
closedir ( $handle );
>
>
$parentDirectory2 = $argv [ 1 ];
$searchFor2 = $argv [ 2 ];
$replaceWith2 = $argv [ 3 ];
//Please do not edit below to keep the rights to this script
//Free license, if contents below this line is not edited
echo "REPLACED\n' $searchFor2 ' with ' $replaceWith2 ' recursively through directory listed below\nFor all files that current user has write permissions for\nDIRECTORY: ' $parentDirectory2 '\n" ;
echo "command written by Kolapo Akande :) all rights reserved :)\n" ;
$holdpwd = getcwd ();
//echo "$holdpwd\n";
chdir ( $parentDirectory2 );
openFileSearchAndReplace ( $parentDirectory2 , $searchFor2 , $replaceWith2 );
exit;
?>
fwrite() записывает содержимое data в файловый поток stream .
Примечания
Замечание:
Запись в сетевой поток может прекратиться до того, как будут записаны все данные. Это можно контролировать с помощью проверки возвращаемого значения функции fwrite() :
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
Замечание:
В системах, различающих двоичные и текстовые файлы (к примеру, Windows), файл должен быть открыт используя флаг 'b' в конце аргумента mode функции fopen() .
Замечание:
Если дескриптор stream был открыт функцией fopen() в режиме "добавление в конец", то вызовы fwrite() будут атомарными (за исключением случая, если размер data превысит размер блока файловой системы, на некоторых платформах, и пока файл хранится на локальной файловой системе). То есть нет необходимости блокировать ресурс с помощью flock() перед вызовом fwrite() , и все данные будут записаны без прерываний.
Замечание:
При повторной записи в файловый указатель, данные будут добавлены в конец содержимого файла:
$fp = fopen ( 'data.txt' , 'w' );
fwrite ( $fp , '1' );
fwrite ( $fp , '23' );
fclose ( $fp );
// содержимое 'data.txt' теперь 123, а не 23!
?>
Возвращаемые значения
Функция возвращает количество записанных байт в файл, или FALSE в случае ошибки.
Эта функция может возвращать как boolean FALSE , так и не-boolean значение, которое приводится к FALSE . За более подробной информацией обратитесь к разделу Булев тип. Используйте оператор === для проверки значения, возвращаемого этой функцией.
Список параметров
Указатель ( resource ) на файл, обычно создаваемый с помощью функции fopen() .
Если параметр length является целым числом ( int ), запись остановится после того, как length байтов будут записаны или будет достигнут конец строки data , смотря что произойдёт раньше.
Примечания
Замечание:
Запись в сетевой поток может прекратиться до того, как будут записаны все данные. Это можно контролировать с помощью проверки возвращаемого значения функции fwrite() :
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
Замечание:
В системах, различающих двоичные и текстовые файлы (к примеру, Windows), файл должен быть открыт используя флаг 'b' в конце аргумента mode функции fopen() .
Замечание:
Если дескриптор handle был открыт функцией fopen() в режиме "записи в конец", то вызовы fwrite() будут атомарными (за исключением случая, если string размер блока файловой системы, на некоторых платформах, и пока файл хранится на локальной файловой системе). Т.е. нет необходимости блокировать ресурс с помощью flock() перед вызовом fwrite() - все данные будут записаны без прерываний.
Замечание:
При повторной записи в файловый указатель данные будут добавлены в конец содержимого файла:
$fp = fopen ( 'data.txt' , 'w' );
fwrite ( $fp , '1' );
fwrite ( $fp , '23' );
fclose ( $fp );
// содержимое 'data.txt' теперь 123, а не 23!
?>
Примеры
$filename = 'test.txt' ;
$somecontent = "Добавить это к файлу\n" ;
// Вначале давайте убедимся, что файл существует и доступен для записи.
if ( is_writable ( $filename ))
// В нашем примере мы открываем $filename в режиме "записи в конец".
// Таким образом, смещение установлено в конец файла и
// наш $somecontent допишется в конец при использовании fwrite().
if (! $handle = fopen ( $filename , 'a' )) echo "Не могу открыть файл ( $filename )" ;
exit;
>
// Записываем $somecontent в наш открытый файл.
if ( fwrite ( $handle , $somecontent ) === FALSE ) echo "Не могу произвести запись в файл ( $filename )" ;
exit;
>
Функция идентична последовательным успешным вызовам функций fopen() , fwrite() и fclose() .
Если filename не существует, файл будет создан. Иначе, существующий файл будет перезаписан, за исключением случая, если указан флаг FILE_APPEND .
Смотрите также
- fopen() - Открывает файл или URL
- fwrite() - Бинарно-безопасная запись в файл
- file_get_contents() - Читает содержимое файла в строку
- stream_context_create() - Создаёт контекст потока
Список изменений
Версия | Описание |
---|---|
5.1.0 | Добавлена поддержка LOCK_EX и возможность передачи потокового ресурса в параметр data |
Список параметров
Указатель ( resource ) на файл, обычно создаваемый с помощью функции fopen() .
Если передан аргумент length , запись остановится после того, как length байтов будут записаны или будет достигнут конец строки string , смотря что произойдёт первым.
Учтите, что если указан аргумент length , то директива magic_quotes_runtime будет проигнорирована и строка string не будет очищена от слешей.
Примечания
Замечание: Эта функция безопасна для обработки данных в двоичной форме.
Для этой функции вы можете использовать URL в качестве имени файла, если была включена опция fopen wrappers. Смотрите более подробную информацию об определении имени файла в описании функции fopen() . Смотрите также список поддерживаемых обёрток URL, их возможности, замечания по использованию и список предопределённых констант в разделе Поддерживаемые протоколы и обёртки.
Читайте также: