0

在我的脚本中,我需要删除一个文件,该文件可能存在也可能不存在:

unlink($path);

与实际的 unlink(2) 一样,PHP 的 unlink()将取消链接条目,如果它存在的话。但是,如果不是,PHP 将在 E_WARNING 级别记录无用的(出于我的目的)消息...我想,这对某些人来说很好,但对我来说却不是 :(

用 C 编程,我可以检查 errno 并在这种情况下简单地忽略 ENOENT。在 PHP 中可以做什么——如何禁止记录这个警告?

在尝试取消链接之前,我宁愿不检查文件——这样做会添加另一个文件系统遍历,除了装饰之外没有其他原因:

if (file_exists($path))
    unlink($path);

有没有更好的办法?

4

2 回答 2

3

您可以在表达式前加上 @ 来禁止仅针对该表达式的警告(例如,@unlink($path);)。

于 2013-06-05T18:16:44.590 回答
1

php.ini 配置

我同意所有提到使用“@”来抑制错误的人。

您还可以更改 php.ini 文件中的一些设置,以使错误不会出现。

 ; Error Level Constants:
; E_ALL             - All errors and warnings (includes E_STRICT as of PHP 6.0.0)
; E_ERROR           - fatal run-time errors
; E_RECOVERABLE_ERROR  - almost fatal run-time errors
; E_WARNING         - run-time warnings (non-fatal errors)
; E_PARSE           - compile-time parse errors
; E_NOTICE          - run-time notices (these are warnings which often result
;                     from a bug in your code, but it's possible that it was
;                     intentional (e.g., using an uninitialized variable and
;                     relying on the fact it's automatically initialized to an
;                     empty string)
; E_STRICT          - run-time notices, enable to have PHP suggest changes
;                     to your code which will ensure the best interoperability
;                     and forward compatibility of your code
; E_CORE_ERROR      - fatal errors that occur during PHP's initial startup
; E_CORE_WARNING    - warnings (non-fatal errors) that occur during PHP's
;                     initial startup
; E_COMPILE_ERROR   - fatal compile-time errors
; E_COMPILE_WARNING - compile-time warnings (non-fatal errors)
; E_USER_ERROR      - user-generated error message
; E_USER_WARNING    - user-generated warning message
; E_USER_NOTICE     - user-generated notice message
; E_DEPRECATED      - warn about code that will not work in future versions
;                     of PHP
; E_USER_DEPRECATED - user-generated deprecation warnings
;
; Common Values:
;   E_ALL & ~E_NOTICE  (Show all errors, except for notices and coding standards warnings.)
;   E_ALL & ~E_NOTICE | E_STRICT  (Show all errors, except for notices)
;   E_COMPILE_ERROR|E_RECOVERABLE_ERROR|E_ERROR|E_CORE_ERROR  (Show only errors)
;   E_ALL | E_STRICT  (Show all errors, warnings and notices including coding standards.)
; Default Value: E_ALL & ~E_NOTICE
; Development Value: E_ALL | E_STRICT
; Production Value: E_ALL & ~E_DEPRECATED
; http://php.net/error-reporting
error_reporting = E_ALL 

最后一行 error_reporting 允许您准确更改要显示的错误。在你的情况下,E_WARNING错误是你试图避免的,所以我会使用E_ALL & ~E_WARNING.

我希望这有帮助。

于 2013-06-03T20:54:48.263 回答