Reputation: 28104
Is there some url/stream that fopen
will successfully open on most PHP installations? /dev/null
is not available or openable on some systems. Something like php://temp
should be a fairly safe bet, right?
The application for this code that guarantees a file resource, instead of the mixed filetype of bool|resource
you have with fopen
:
/**
* @return resource
*/
function openFileWithResourceGuarantee() {
$fh = @fopen('/write/protected/location.txt', 'w');
if ( $fh === false ) {
error_log('Could not open /write/protected/location.txt');
$fh = fopen('php://temp');
}
return $fh;
}
In PHP 7 with strict types, the above function should guarantee a resource and avoid bools. I know that resources are not official types, but still want to be as type-safe as possible.
Upvotes: 2
Views: 202
Reputation: 19386
If you need a stream for writing errors to why are you not writing to php://stderr
?
Example from the docs:
When logging to apache on windows, both error_log and also trigger_error result in an apache status of error on the front of the message. This is bad if all you want to do is log information. However you can simply log to stderr however you will have to do all message assembly:
LogToApache($Message) { $stderr = fopen('php://stderr', 'w'); fwrite($stderr,$Message); fclose($stderr); }
Note: php://stderr
is sometimes the same as php://stdout
, but not always.
For streams see: http://php.net/manual/en/wrappers.php.php
Something like
php://temp
should be a fairly safe bet, right?
As @weirdan already pointed out php://memory
is probably safer as it does not even need to create any file. Memory access MUST be possible. From the docs:
php://memory
andphp://temp
are read-write streams that allow temporary data to be stored in a file-like wrapper. The only difference between the two is thatphp://memory
will always store its data in memory, whereasphp://temp
will use a temporary file once the amount of data stored hits a predefined limit (the default is 2 MB). The location of this temporary file is determined in the same way as thesys_get_temp_dir()
function.
Not sure if this answers your question completely but does it lead you into the right direction?
Upvotes: 0