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»);
is_writable
Возвращает TRUE , если файл filename существует и доступен для записи. Аргумент filename может быть именем директории, что позволяет вам проверять директории на доступность для записи.
Не забывайте, что PHP может обращаться к файлу от имени того пользователя, от которого запущен веб-сервер (обычно ‘nobody’). Ограничения безопасного режима не принимаются во внимание.
Список параметров
Возвращаемые значения
Возвращает TRUE , если filename существует и доступен для записи.
Примеры
Пример #1 Пример использования is_writable()
$filename = ‘test.txt’ ;
if ( is_writable ( $filename )) echo ‘Файл доступен для записи’ ;
> else echo ‘Файл недоступен для записи’ ;
>
?>?php
Ошибки
В случае неудачного завершения работы генерируется ошибка уровня E_WARNING .
Примечания
Замечание: Результаты этой функции кэшируются. Более подробную информацию смотрите в разделе clearstatcache() .
Начиная с PHP 5.0.0, эта функция также может быть использована с некоторыми обертками url. Список оберток, поддерживаемых семейством функций stat() , смотрите в Поддерживаемые протоколы и обработчики (wrappers).
Смотрите также
- is_readable() — Определяет существование файла и доступен ли он для чтения
- file_exists() — Проверяет наличие указанного файла или каталога
- fwrite() — Бинарно-безопасная запись в файл
is_writable
Returns true if the filename exists and is writable. The filename argument may be a directory name allowing you to check if a directory is writable.
Keep in mind that PHP may be accessing the file as the user id that the web server runs as (often ‘nobody’).
Parameters
The filename being checked.
Return Values
Returns true if the filename exists and is writable.
Errors/Exceptions
Upon failure, an E_WARNING is emitted.
Examples
Example #1 is_writable() example
$filename = ‘test.txt’ ;
if ( is_writable ( $filename )) echo ‘The file is writable’ ;
> else echo ‘The file is not writable’ ;
>
?>?php
Notes
Note: The results of this function are cached. See clearstatcache() for more details.
As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.
See Also
- is_readable() — Tells whether a file exists and is readable
- file_exists() — Checks whether a file or directory exists
- fwrite() — Binary-safe file write
User Contributed Notes 15 notes
Be warned, that is_writable returns false for non-existent files, although they can be written to the queried path.
To Darek and F Dot: About group permissions, there is this note in the php.ini file:
; By default, Safe Mode does a UID compare check when
; opening files. If you want to relax this to a GID compare,
; then turn on safe_mode_gid.
safe_mode_gid = Off
It appears that is_writable() does not check full permissions of a file to determine whether the current user can write to it. For example, with Apache running as user ‘www’, and a member of the group ‘wheel’, is_writable() returns false on a file like
-rwxrwxr-x root wheel /etc/some.file
Check director is writable recursively. to return true, all of directory contents must be writable
function is_writable_r ( $dir ) if ( is_dir ( $dir )) if( is_writable ( $dir )) $objects = scandir ( $dir );
foreach ( $objects as $object ) if ( $object != «.» && $object != «..» ) if (! is_writable_r ( $dir . «/» . $object )) return false ;
else continue;
>
>
return true ;
>else return false ;
>
>else if( file_exists ( $dir )) return ( is_writable ( $dir ));
This file_write() function will give $filename the write permission before writing $content to it.
Note that many servers do not allow file permissions to be changed by the PHP user.
function file_write ( $filename , & $content ) <
if (! is_writable ( $filename )) if (! chmod ( $filename , 0666 )) echo «Cannot change the mode of file ( $filename )» ;
exit;
>;
>
if (! $fp = @ fopen ( $filename , «w» )) echo «Cannot open file ( $filename )» ;
exit;
>
if ( fwrite ( $fp , $content ) === FALSE ) echo «Cannot write to file ( $filename )» ;
exit;
>
if (! fclose ( $fp )) echo «Cannot close file ( $filename )» ;
exit;
>
>
?>
Regarding you might recognize your files on your web contructed by your PHP-scripts are grouped as NOBODY you can avoid this problem by setting up an FTP-Connection («ftp_connect», «ftp_raw», etc.) and use methods like «ftp_fput» to create these [instead of giving out rights so you can use the usual «unsecure» way]. This will give the files created not the GROUP NOBODY — it will give out the GROUP your FTP-Connection via your FTP-Program uses, too.
Furthermore you might want to hash the password for the FTP-Connection — then check out:
http://dev.mysql.com/doc/mysql/en/Password_hashing.html
The results of this function seems to be not cached :
Tested on linux and windows
chmod ( $s_pathFichier , 0400 );
echo ‘
' ; var_dump ( is_writable ( $s_pathFichier ));echo '
‘ ;
chmod ( $s_pathFichier , 04600 );
echo ‘
' ; var_dump ( is_writable ( $s_pathFichier ));echo '
‘ ;
exit;
?>
This function returns always false on windows, when you check an network drive.
We have two servers: one running PHP 5.0.4 and Apache 1.3.33, the other running PHP 4.3.5 and Apache 1.3.27. The PHP 4 server exhibits the behavior you are describing, with is_writable() returning ‘false’ even though the www user is in the group that owns the file, but the PHP 5 server is returning ‘true.’
This is the latest version of is__writable() I could come up with.
It can accept files or folders, but folders should end with a trailing slash! The function attempts to actually write a file, so it will correctly return true when a file/folder can be written to when the user has ACL write access to it.
function is__writable ( $path ) //will work in despite of Windows ACLs bug
//NOTE: use a trailing slash for folders.
//see http://bugs.php.net/bug.php?id=27609
//see http://bugs.php.net/bug.php?id=30931
if ( $path < strlen ( $path )- 1 >== ‘/’ ) // recursively return a temporary file path
return is__writable ( $path . uniqid ( mt_rand ()). ‘.tmp’ );
else if ( is_dir ( $path ))
return is__writable ( $path . ‘/’ . uniqid ( mt_rand ()). ‘.tmp’ );
// check tmp file for read/write capabilities
$rm = file_exists ( $path );
$f = @ fopen ( $path , ‘a’ );
if ( $f === false )
return false ;
fclose ( $f );
if (! $rm )
unlink ( $path );
return true ;
>
?>
Since looks like the Windows ACLs bug «wont fix» (see http://bugs.php.net/bug.php?id=27609) I propose this alternative function:
function is__writable ( $path )
if ( $path < strlen ( $path )- 1 >== ‘/’ )
return is__writable ( $path . uniqid ( mt_rand ()). ‘.tmp’ );
if ( file_exists ( $path )) if (!( $f = @ fopen ( $path , ‘r+’ )))
return false ;
fclose ( $f );
return true ;
>
if (!( $f = @ fopen ( $path , ‘w’ )))
return false ;
fclose ( $f );
unlink ( $path );
return true ;
>
?>
It should work both on *nix and Windows
NOTE: you must use a trailing slash to identify a directory
function is_writable(‘ftp://user. ‘) always return false. I can create/delete files, but can check is writable. Is this bug or php feature :)?
I’d like to also clarify a point on this. Even if you see 777 permissions for the directly, you may need to check your ACL, since your server’s group might not have write permissions there.
Check if a directory is writable. Work also on mounted SMB shares: