Web студия "GrandView"
  Главная   Написать Контакты
   
   
О проекте
Руководство php
 

fwrite

(PHP 3, PHP 4, PHP 5)

fwrite -- Бинарно-безопасная запись в файл

Описание

int fwrite ( resource handle, string string [, int length] )

fwrite() записывает содержимое string в файловый поток handle. Если передан аргумент length, запись остановится после того, как length байтов будут записаны или будет достигнут конец строки string, смотря что произойдёт первым.

fwrite() возвращает количество записанных байтов или FALSE в случае ошибки.

Обратите внимание, что если аргумент length указан, то конфигурационная опция magic_quotes_runtime будет проигнорирована и строка string не будет очищена от слешей.

Замечание: В системах, различающих двоичные и текстовые файлы (к примеру, Windows), файл должен быть открыт используя флаг 'b' в конце аргумента mode функции fopen().

Пример 1. Простой пример использования fwrite

<?php
$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;
    }
   
    echo
"Ура! Записали ($somecontent) в файл ($filename)";
   
   
fclose($handle);

} else {
    echo
"Файл $filename недоступен для записи";
}
?>

См. также описание функций fread(), fopen(), fsockopen(), popen() и file_put_contents().



glob> <ftruncate
Last updated: Sat, 27 Jan 2007
 
add a note add a note User Contributed Notes
fwrite
chad 0x40 herballure 0x2e com
05-Sep-2007 10:13
Remember to check the return value of fwrite(). In particular, writing into a socket can return fewer bytes than requested, and you'll have to try again with the remainder of your data.
chaobreederxl at gmail dot com
29-Mar-2007 12:52
This is a simple function I wrote that uses the fopen and fwrite functions to log the actions of users... very useful for tracking your members on your site.

 <?php
 
function loguser($reason,$ext = "db"){
  if(!
is_dir("logs")):
  
mkdir("logs","0493");
 endif;
 
$fp = fopen("logs/".date("m-d-y").".".$ext, "a+");
  
fwrite($fp, "<strong>".date("g:i:s A")."</strong>: ".$reason."<br/>");
 }
?>

To use this, just call the function like so:

<? loguser($_SERVER["REMOTE_ADDR"]." attempted to create another account.","html"); ?>

The second parameter can be changed to anything that would support HTML. If you leave out the second extension, then it automatically uses the .db extension, which works excellent for me.

Hope this helps.

Paul
cutmaster at fearlesss dot com
09-Mar-2007 03:09
For those who, like me, lost a lot of minutes (hours) to understand why fwrite doesn't create a real utf-8 file, here's the explanation I've found :

I tried to do something like this :
<?php
$myString
= utf8_encode("Test with accents
Новости
11 июля 2007
Сайт запущен
© 2007 info@grandviewstudio.com

Deprecated: Function set_magic_quotes_runtime() is deprecated in /home/sites/grandviewstudiocom/www/65f67d67a94ad980786580ae69e11c07/sape.php on line 324

Deprecated: Function set_magic_quotes_runtime() is deprecated in /home/sites/grandviewstudiocom/www/65f67d67a94ad980786580ae69e11c07/sape.php on line 330
Z058440144362 Z348613067571