| > Can I now get EEXISTS and such out of fopen()? Looking at the docs it still just returns false and emits an uncatchable E_WARNING that can't be examined programmatically. Sure, the most straightforward way is to first use the "x" flag for write-only, and "x+" for read/write access. $fp = fopen('file.txt', 'x+');
From the PHP docs:"If the file already exists, the fopen() call will fail by returning false and generating an error of level E_WARNING. If the file does not exist, attempt to create it. This is equivalent to specifying O_EXCL|O_CREAT flags for the underlying open(2) system call." And finally to convert E_WARNING errors to exceptions, use you can use set_error_handler() to throw an exception (and even write business logic to filter them): https://www.php.net/manual/en/language.exceptions.php They're not unhandleable. But if you want a single function that throws a specific exception when a file exists, specific to the behavior you want, I got you: <?php
declare(strict_types=1);
namespace Argp242;
use function fopen as php_fopen;
function fopen(
string $filename,
string $mode,
bool $use_include_path = false,
$context = null
) {
if (file_exists($filename)) {
throw new \RuntimeException('E_EXISTS');
}
return php_fopen($filename, $mode, $use_include_path, $context);
}
To run this code from outside a namespace, simply: try {
$fp = Argp242\fopen($filename, $mode);
} catch (RuntimeException $ex) {
// Handle $ex
}
Throw it in a library somewhere, having written it once, and now you can just use that whenever you want that behavior in your PHP code. |