how can I prevent PHP from returning an Undefined variable error every time I try to check a variable if it has contents and that certain variable hasn\'t b
Most likely it's not an error, but a Warning. You can set PHP not to display errors/warnings if you want. Just add this to the begining of your code:
ini_set('display_errors', 0);
Altough, I recommend you not to be lazy and have your code not display any errors, warnings, notices whatsoever, better safe than sorry.
And the preferred way to do what you want to do is
<?php
if (isset($_POST['info'])) {
// do some stuff
}
?>
<form method="post">
<input type="text" name="info" />
<input type="submit" />
</form>
If you want to set $_POST vars, having a whole lot of these statements really clutters your code:
if (isset($_POST['info']))
$info = $_POST['info'];
... etc....
How about this?
function setPostVar( &$v ) {
$trace = debug_backtrace();
$vLine = file( __FILE__ );
$fLine = $vLine[ $trace[0]['line'] - 1 ];
preg_match( "#\\$(\w+)#", $fLine, $match );
eval("\$v = isset(\$_POST[\"$match[1]\"])?\$_POST[\"$match[1]\"]:'';");
}
Now, as long as you are happy naming variables similar to your POST vars
ie. $Foo = $_POST['Foo'];
you can just do this:
setPostVar($Foo); // equivalent to if(isset($_POST['Foo']) $Foo = $_POST['Foo'];
setPostVar($Bar); // ditto
setPostVar($Baz); // ditto
I have sometimes done the following to do a comparison and avoid the warning about an unset variable:
if( @$_POST['variable'] == 'value' )
{
...
}
Although PHP would still call custom error handlers, so perhaps I need to reconsider this strategy.
You could use the empty function, which returns true if the variable is either unset or empty (i.e. a zero-length string, 0, NULL, FALSE and so on):
if(!empty($_POST['variable'])){
/* ... */
}
This is pretty much the same test as the one you're doing now, except that it will also return false (not run the block), without warnings, when the variable is unset.
Are you using your own Server? If so you can change the error_reporting via PHP.INI. Above the line
"error_reporting = E_ALL;" (might not be E_ALL) There will be a small documentation explaining which type of errors you can show.
If you're using a shared server from a webhosting company, I believe some may offer quick PHP management under your Webhosting account CP.
I hope I helped ;/
ps- If you do have your own server, you'll have to restart Apache. I'm not sure how it's done in Ubunto (if that's what you're using) but for CentOS it's:
/sbin/service httpd restart
The variable will be always SET as long as you sent the form
.
So its better to check of the variable is not empty
.
if(!empty($_POST['var']))