Open
Description
Description
isReadable and isWriteable only consider the file system permissions but that isn't actually reflective of the state of the object because read and write methods also consider the resource mode so if you trust them you can can run into unexpected bugs as demonstrated in the example below.
Specifically
1 . Streams don't look readable?
2. Resources that are opened write only look readable.
The following code:
<?php
function showFile(\SplFileObject $file) {
var_dump($file->isReadable());
if ($file->isReadable()) {
var_dump($file->fread($file->getSize()));
}
echo str_repeat('=', 80) . PHP_EOL;
}
showFile(new SplFileObject(__FILE__));
$f = new SplFileObject('php://temp', 'r+');
$f->fwrite('content');
showFile($f);
showFile(new SplFileObject(__FILE__, 'a'));
Resulted in this output:
bool(true)
string(376) "<?php
function showFile(\SplFileObject $file) {
var_dump($file->isReadable());
if ($file->isReadable()) {
var_dump($file->fread($file->getSize()));
}
echo str_repeat('=', 80) . PHP_EOL;
}
showFile(new SplFileObject(__FILE__));
$f = new SplFileObject('php://temp', 'r+');
$f->fwrite('content');
showFile($f);
showFile(new SplFileObject(__FILE__, 'a'));
"
================================================================================
bool(false)
================================================================================
bool(true)
PHP Notice: SplFileObject::fread(): Read of 8192 bytes failed with errno=9 Bad file descriptor in /tmp/tmp.php on line 6
bool(false)
================================================================================
But I expected this output instead:
bool(true)
string(376) "<?php
function showFile(\SplFileObject $file) {
var_dump($file->isReadable());
if ($file->isReadable()) {
var_dump($file->fread($file->getSize()));
}
echo str_repeat('=', 80) . PHP_EOL;
}
showFile(new SplFileObject(__FILE__));
$f = new SplFileObject('php://temp', 'r+');
$f->fwrite('content');
showFile($f);
showFile(new SplFileObject(__FILE__, 'a'));
"
================================================================================
bool(true)
string(7) "content"
================================================================================
bool(false)
PHP Version
all
Operating System
No response