while($rowForStateList = #mysql_fetch_array($resForStateList))
{
$sid[$i] = $rowForStateList['state_auto_id'];
$sname[$i] = $rowForStateList['state_name'];
$spid[$i] = $rowForStateList['country_auto_id'];
$i++;
}
AND
while($rowForStateList = mysql_fetch_array($resForStateList))
{
$sid[$i] = $rowForStateList['state_auto_id'];
$sname[$i] = $rowForStateList['state_name'];
$spid[$i] = $rowForStateList['country_auto_id'];
$i++;
}
The difference is that #mysql_fetch_array in first code sample fetches the array suppressing any errors, while mysql_fetch_array do the same but not suppressing errors. Actually, the second one is more correct way.
The evil of using # is in that it comlicates debugging a lot. With this suppression, in case of error you'll end up with empty arrays, so it will look just like query used to get $resForStateList have returned empty result. But, you actually might have broken query, refused database connection and whatever else. And with # you will never know that something goes wrong.
So, don't use #. Instead, use error handling functions. And the best way is to check if something could cause error, e.g. mysql_query returns false in case of any error, so you might want to check it like
$result = nysql_query("qwerty");
if (!$result){
echo mysql_error();
}
The difference is that the former will mask any errors that occur in mysql_fetch_array(), making debugging more difficult.
The # in the first version basically means "If this function triggers an error, just hide it, don't log or display it".
Don't ever use the # error suppression operator! Not only does it make for a debugging nightmare, but it also harms application performance. Use error_reporting, log_errors and display_errors to set proper error message behaviour instead.
Don't use the # operator in this case. mysql_fetch_array will only throw an error if the resource is not valid. You should have checked this before, after you got this resource.
The difference is the error reporting.
If you set a # before mysql_fetch_array, any errors will be ignored.
see php errorcontrol
the only difference is that the # in front of the mysql_fetch_array in the first code will supress any error from being displayed on the screen.
the first one suppresses errors: http://davidwalsh.name/suppress-php-errors-warnings
They are identical. The first mysql_fetch_array() will not produce error messages due to the suppression operator #.
The first one will silently ignore any error. The second one will display any error or exceptions thrown the mysql_fetch_array (for example, connection problem). The magic comes from the # sign.
#mysql_fetch_array($resForStateList))
doesn't show up any message in case of an error.
That's all.
The # is an operator thet suppresses errors. Your statement will not throw errors when the # is added. You can read more here: http://thesmithfam.org/blog/2006/05/07/php-the-operator/
When you prepend '#' to an expression, any error messages that might be generated will be ignored (ie. no error output will be generated). Anyway if the track_errors feature is enabled, any error message generated by the expression will be saved (and overwritten on each error) in the variable $php_errormsg.
Check PHP Error Control for more details.
Actually, I prefer to use expression widthout '#' and handle all exceptions with a function that log all message in a file with error_log(). Something like:
function error_handler($errno, $errstr, $errfile=null, $errline=null, $errcontext=null) {
error_log($errstr, 3, 'debug.log');
}
set_error_handler('error_handler', ERROR_REPORTING);
Related
in my code is usually use if(!isset()) for set default value if the variable is empty
ex :
if(isset($_POST['noreg']))
{
$noreg = $_POST['noreg'];
}
else
{
$noreg = 'empty';
}
my friend suggest me to use elvis operator with error handling, and it looks shorten than before,
$noreg = #$_POST['noreg'] ?: 'empty';
it works fine like my old code
but is it safe or it has any risk if i use it?
can anyone help me for this?
thanks
The # operator suppresses error reporting. That means there's still an error being produced, but it's being silenced. That's problematic for three reasons:
It's probably slower to raise and then discard an error than an isset check would be.
If you have a custom error handler, that handler may ignore # and still produce an error.
You have no idea what other kinds of errors you may be suppressing that you're not expecting.
Particularly, what if you accidentally write #$_PSOT['noreg']? PHP's error reporting won't be alerting you to this mistake and you're in the dark. If you'd use filter_input(INPUT_POST, 'noreg') or array_key_exists('noreg', $_POST), such mistakes could not be made.
(This example may be a bit contrived since isset() will suppress the same error, but it's to illustrate the pitfalls of using error suppression and why one must be very conscious of it.)
If you use it for simple variable initialization then it's ok. It will work on any expression & when preceding it, it will suppress the error.
Straight from documentation http://php.net/manual/en/language.operators.errorcontrol.php
PHP supports one error control operator: the at sign (#). When
prepended to an expression in PHP, any error messages that might be
generated by that expression will be ignored.
If you have set a custom error handler function with
set_error_handler() then it will still get called, but this custom
error handler can (and should) call error_reporting() which will
return 0 when the call that triggered the error was preceded by an #.
Currently the "#" error-control operator prefix will even disable
error reporting for critical errors that will terminate script
execution. Among other things, this means that if you use "#" to
suppress errors from a certain function and either it isn't available
or has been mistyped, the script will die right there with no
indication as to why.
In some conditions, may I use an # character instead of using the longer isset() function?
If not, why not?
I like to use this because in a lot cases I can save several quotation marks, brackets and dots.
I assume you're talking about the error suppression operator when you say # character, but that isn't a replacement for isset().
isset() is used to determine whether or not a given variable already exists within a program, to determine if it's safe to use that variable.
What I suspect you're doing is trying to use the variable regardless of its existance, but supressing any errors that may come from that. Using the # operator at the beginning of a line tells PHP to ignore any errors and not to report it.
The # operator is shorthand for "temporarily set error_reporting(0) for this expression". isset() is a completely different construct.
You shouldn't just use an #. The # suppresses warnings. It doesn't mean the code is correct, and warnings might still get added to your log file depending on your settings. It is much better to use isset to do the check.
As far as I know # is no substitution for isset(). Its an error suppression operator which prevents displaying errors in case they do exist in the script. Its also a pretty bad habit if used in PHP code.
It technically works, but there are a few reasons why I prefer the explicit isset solution when creating output, which I assume is what you're doing:
If I'm a new developer working on your old code, I recognize the isset idiom. I know what you're trying to do. With #, it's not so easy to figure out your intention.
Suppose you want to check if an object's property is set, like $user->name. If you just use error suppression to see if name is set, you will never be notified if $user is undefined. Instead, it's better to run isset($user->name) and be explicit, so that, if $user is undefined, you will be notified of the error.
Error suppression is a bad habit overall. Error notices are good, and you should make it as easy as possible to be notified of errors. Suppressing them when it's not necessary leads to problems in the future.
It depends on what you are trying to do. For instance, if you are performing a var_dump() or other debugging and know that sometimes your value will not be set I'd say in this situation it is ok.
var_dump(#$_REQUEST['sometimesIamSet']);
If you are using it in this case:
if(#$_REQUEST['something']){
// do something
}
else{
// do something else
}
I would strongly advise against it. You should write your code to do explicitly what you want to do.
if(isset($_REQUEST['something'])){
// Hurray I know exactly what is going on!
}
else{
// Not set!
}
The only instance in production I can think about using # is when you want to throw your own error. For example
$database_connection = #db_connect_function();
if($database_connection === false){
throw new Exception("DB connection could not be made");
}
Also, look at PaulPRO's answer. If what he is saying is indeed true, your log files could also be logging warnings that you don't know about. This would result in your log files being less helpful during debugging after release.
If for no other reason, don't use # as a substitute for isset because of this:
Look at this code:
echo (#$test) ?: 'default';
If $test is 'something' then you'll get 'something'.
If $test is empty, null or doesn't exist, then you'll get 'default';
Now here's where the problem comes in:
Suppose '0' or FALSE are valid answers?
If $test is '0' or FALSE then you'll get 'default' NOT '0' as you would want.
The long-format ternary is what you should use:
echo (isset($test)) ? $test : 'default';
Not much more coding, and more reliable when it comes to dealing with arguments that can evaluate as boolean false.
the # operator also makes your code run slower, as pointed out here:
http://php.net/manual/en/language.operators.errorcontrol.php
But as it's been pointed out, the code only runs measurably slower if an error occurs. In that case, code using isset instead of # operator is much faster, as explained here:
http://seanmonstar.com/post/909029460/php-error-suppression-performance
I've seen code samples that use an # before fopen as in
$fh = #fopen($myFile, 'w');
What's the significance of this #?
It suppresses errors an expression may display.
You can read more about it here.
Example:
file_get_contents('file_does_not_exist'); //this shows an error
#file_get_contents('file_does_not_exist'); //this does not
Its PHP's error control char.
PHP supports one error control operator: the at sign (#). When prepended to an expression in PHP, any error messages that might be generated by that expression will be ignored.
More here.
Using # is always bad practice. It will suppress an error message if occurrs, while error messages are extremely useful for the programmer and suppressing it is suicide. PHP's fate is to be used mostly not by programmers but by casual users who have no clue. You've got this code from one of that latter kind. So, better to get rid of all #, so, you'll be able to see what happened and correct a mistake.
Note that every error message has it's particular meaning and explain what the problem is.
For example there can be filesystem permissions problem or PHP OPEN_BASEDIR setting to prevent file from open. So, an error message will tell you what to do. Error messages is good and # is evil.
What is the difference between these two function calls in PHP?
init_get($somevariable);
#init_get($somevariable);
the "#" will silence any php errors your function could raise.
It silences errors and warnings. See Error Control Operators.
As already answered the # will stop the error (if any) from showing up.
In terms of performance this is not recommended.
What php is doing is:
reading the error display state
setting the error display to show no errors
running your function
setting the error display to it's previous state
If you don't want any errors showing up use error_reporting(0);.
Or just write bug free code :P
http://www.faqts.com/knowledge_base/view.phtml/aid/18068/fid/38
All PHP expressions can be called with the "#" prefix, which turns off
error reporting for that particular expression.
As everyone said, it stops the output of errors for that particular function. However, this decreases performance greatly since it has to change the error display setting twice. I would recommend NOT ignoring warnings or errors and fixing the code instead.
I am currently refactoring some code for work and I have come across some function calls prefixed by the "#" symbol. As I understand it, this is intended to escape PHP error reporting if the call fails.
Is this type of thing good practice? I understand the rationale in a development environment but when the site is pushed to production shouldn't all errors be handled properly rather than just escaped?
The use of this symbol would therefore mean that the developer has to sort through the code at a later stage to remove all error reporting escapes.
I am unsure whether to remove these symbols and just find a better way to handle potential errors or not.
For clarity, the function this was used on was the native PHP fsockopen() function.
That's probably among the worst practices you can come across in php code. It basically tells the interpreter to suppress errors and just try to do whatever the code asks it to do regardless of the outcome.
A great way to drag yourself and fellow teammates into all-nighter phantom bug hunts once the app has grown substantially.
Try-catch with custom exception handling is the way to go.
I think it is sometimes understandable to use # for calling functions like fsockopen(), because when they fail they will raise a warning as well as returning false.
There may be cases where you expect these calls to fail regularly and therefore do not want a warning to be raised. Obviously you shouldn't be displaying warnings in production and should be logging them instead, but you might still want to use the # operator to stop your logs getting full. You could stop warnings getting reported at all by changing the error_reporting setting but that is not ideal.
That's called the error control operator, and is generally a very scary thing to consider using. A warning from the manual (the emboldening is mine):
Currently the "#" error-control
operator prefix will even disable
error reporting for critical errors
that will terminate script execution.
Among other things, this means that if
you use "#" to suppress errors from a
certain function and either it isn't
available or has been mistyped, the
script will die right there with no
indication as to why.
Using the "#" operator is very useful when you know that the function call can fail, like, for example, the fsockopen call. Best practice is to use this only when the function you are calling often fails and is a valid case in your application. Also, you should definitely check the return value of the function after calling it:
$fp = #fsockopen($hostname, $port);
if ($fp === false) {
// handle connection failure
}
else {
// handle connection success
}
You should avoid two things:
Not checking the return value;
Using the "#" operator where you don't expect an error -- for example when opening a local file or sending headers. When opening a local file fails, that is an error and it should be handled properly.
Note: you might also want to look at set_error_handler()
if you use your custom error-handlers, the # operator will not help you,
you will always get error-events from situations where your are handling the "Warning" in your code ... like at fsockopen etc.
so you can simple suppress effectively the warning this way:
function renameWithOutExpectedAndSelfHandledErrors( ... ) {
set_error_handler(function(){}); // deactivate all errors
$result = rename('not existing','blafussel');
restore_error_handler(); // restore old error-situation
return $result;
}