Две вещи, используемые вместе, должны лучше всего служить вам:
error_reporting()
ini_set( 'display_errors', (boolean)showInBrowser )
Используйте error_reporting()
, чтобы установить соответствующий уровень детализации для предупреждающих сообщений. обратите внимание, что указывается только то, какие предупреждения, уведомления и / или ошибки регистрируются, а не отображаются ли они.
В вашем случае, вероятно, "error_reporting( E_ERROR | E_USER_ERROR )
;" который регистрирует что-то, только если это действительно ошибка, а не просто уведомление или предупреждение, которое ничего не нарушает.
В общем, это хорошая идея сделать что-то вроде этого:
if (getenv('PHP_DEBUG')=='1')
{
error_reporting( E_ERROR | E_USER_ERROR );
ini_set( 'display_errors', true );
}
else
{
error_reporting( E_ERROR | E_USER_ERROR );
ini_set( 'display_errors', false );
}
И тогда на сервере разработки вы можете иметь следующую строку в вашей директиве .htaccess или VirtualHost:
SetEnv PHP_DEBUG=1
Нет необходимости устанавливать его вообще в производстве, так как не установлено ≠ 1.
Кстати, я лично предпочитаю, чтобы мой error_reporting был установлен на
error_reporting( E_ALL | E_STRICT );
, который вы могли бы прочитать по-английски как «предупреждать обо всем, что я, возможно, сделал неправильно, чтобы заставить меня делать лучшую работу», потому что я чувствую, что если я смогу опередить каждое уведомление и предупреждение, просто проверив некоторые вещи перед их использованием и при правильной инициализации переменных конечный результат, вероятно, будет, по крайней мере, немного более безопасным.
edit : некоторые пояснения:
Поскольку Ариф не просил убедиться, что операция прошла успешно, просто чтобы не получить сообщение. Который я интерпретировал как "все равно, сработала ли операция". Конечно, лучший способ сделать это - сделать что-то вроде вашей библиотеки функций:
/**
* @author: Kris
* @license: see http://sam.zoy.org/wtfpl/
*
* PLEASE NOTE THAT THE FOLLOWING CODE IS TESTED BY ME, NOT QUALITY ASSURANCE
*/
/**
* Move a file
*
* If uses filename from $source if $destination is a directory
*
* @param string $source
* @param string $destination
* @param bool $overwrite
* @return bool
*/
function my_move_file( $source, $destination, $overwrite = false )
{
return _internal_my_move_or_copy_file( $source, $destination, true, $overwrite );
}
/**
* Copy a file
*
* If uses filename from $source if $destination is a directory
*
* @param string $source
* @param string $destination
* @param bool $overwrite
* @return bool
*/
function my_copy_file( $source, $destination, $overwrite = false )
{
return _internal_my_move_or_copy_file( $source, $destination, false, $overwrite );
}
define( '__internal_my_move_or_copy_file_e_error', E_USER_ERROR ); // change to E_USER_NOTICE if not meant to be fatal
define( '__internal_my_move_or_copy_file_e_notice', E_USER_NOTICE );
/**
* Should not be called by userland code, use my_move_file or my_copy_file instead
*
* one function to implement both move and copy because almost all of the required validations is identical.
*
* @param string $source
* @param string $destination
* @param bool $is_move
* @param bool $overwrite
* @return bool
*/
function _internal_my_move_or_copy_file( $source, $destination, $is_move, $overwrite )
{
// what we'll be returning
$result = false;
// input sanity checks
if ( !is_string( $source ) || !is_callable( $source, '__toString' ) )
{
trigger_error(
"_internal_my_move_or_copy_file: expects \$source to be a string.",
__internal_my_move_or_copy_file_e_error );
return false;
}
elseif ( !is_string( $destination ) || !is_callable( $destination, '__toString' ) )
{
trigger_error(
"_internal_my_move_or_copy_file: expects \$destination to be a string.",
__internal_my_move_or_copy_file_e_error );
return false;
}
elseif ( ! is_bool( $is_move ) )
{
trigger_error(
"_internal_my_move_or_copy_file: expects \$is_move to be a bool.",
__internal_my_move_or_copy_file_e_error );
return false;
}
elseif ( ! is_bool( $overwrite ) )
{
trigger_error(
"_internal_my_move_or_copy_file: expects \$overwrite to be a bool.",
__internal_my_move_or_copy_file_e_error );
return false;
}
$action_word = $is_move ? 'move' : 'copy';
if ( file_exists( $source ) && is_readable( $source ) )
{
$to = preg_split( '/\//', $destination, -1, PREG_SPLIT_NO_EMPTY );
$destination = '/'.implode( '/', $to );
if ( is_dir( $destination ) )
{
// make sure we don't accidentally allow ../ etc
if ( in_array( '..', $to ) || in_array( '.', $to ) )
{
trigger_error( "my_{$action_word}_file: \$destination does not allow path traversion using /../ or /./", $e_error_code );
}
// make sure we have a filename on $destination
if ( is_dir( $destination ) )
{
// user gave a directory but no filename so use the filename in $source
$to[] = basename( $source );
$destination = '/'.implode( '/', $to );
}
}
if ( file_exists( $destination ) && is_writable( $destination ) )
{
if ( ! $overwrite )
{
trigger_error(
"my_{$action_word}_file: \$destination already exists and I am instructed not to overwrite.",
__internal_my_move_or_copy_file_e_notice );
return false;
}
}
elseif ( is_dir( dirname( $destination ) ) || is_writable( dirname( $destination ) ) )
{
// we can write
}
else // all allowable situations are already passed
{
trigger_error(
"my_{$action_word}_file: $destination directory does not exist or cannot be written to.",
__internal_my_move_or_copy_file_e_error );
}
if ( $is_move )
{
// if we are going to move a file the source also needs to be writable
if ( ! is_writable( $source ) )
{
trigger_error(
"my_{$action_word}_file: Cannot {$action_word} \$source because it cannot be written.",
__internal_my_move_or_copy_file_e_error );
}
$result = rename( $source, $destination );
}
else
{
$result = copy( $source, $destination );
}
// see if what php's built in function gave us is acceptible
if ( $result === false )
{
trigger_error(
"my_{$action_word}_file: unexpected failure to {$action_word} \$source to \$destination.",
__internal_my_move_or_copy_file_e_error );
}
// postflight check if the work we did was successful
if ( !file_exists( $destination ) )
{
trigger_error(
"my_{$action_word}_file: unexpected failure to {$action_word} \$destination does not exist after {$action_word} operation.",
__internal_my_move_or_copy_file_e_error );
}
}
else // file does not exists or is unreadable
{
trigger_error(
"my_{$action_word}_file: \$source \"$source\" does not exist or cannot be read.",
__internal_my_move_or_copy_file_e_error );
}
return $result;
}