Writecoder
Writecoder

Reputation: 613

Php error handling

I have now a function like this

function checkInput($content, $emptyMessage = ""){
    if(isset($content)){ 
       return sanitize($content);
    }else{
       return $emptyMessage;
    }
 }

And I use it like this:

/* First get all data out of key and put it in array*/

//now check the input if user has set certain fields
$email = checkInput($user["email"],"No email address given");

echo $email;

Now I get: Uncaught ErrorOrWarningException. I can think of two solutions:

Turning off errors > dont like that one.

Do manually for every field like

if(isset($user["email"])){ 
     $email = sanitize($user["email"]);
}else{
     $email =  "No email address given";
}
echo $email;

That sucks for readibility. Another way would be to try / catch but thats almost the same length to type

Upvotes: 0

Views: 140

Answers (3)

Chuck
Chuck

Reputation: 4892

What about something like this:

function checkInput( $var, $emptyMessage = '' )
  if ( isset( $$var ) ) {
    return sanitize( $$var );
  } else {
    return $emptyMessage;
  }
}

or, similarly,

function checkInput( $var, $key, $emptyMessage = '' )
  if ( isset( $var[$key] ) {
    return sanitize( $var[$key] );
  } else {
    return $emptyMessage;
  }
}

Upvotes: 0

deceze
deceze

Reputation: 521994

When declaring a function with parameters, the parameter will always be set inside the function.

function checkInput($content, $emptyMessage = "") {
    // $content is always "set" here, no need for isset()

You're getting a warning if you're trying to access a non-existent variable here:

checkInput($user["email"], "No email address given");
  //       ^^^^^^^^^^^^^^
  // if 'email' is not set, a warning is thrown here

You'll always need to make sure the "email" key is set before trying to pass its value into a function.

Having said that, that's probably not the cause of your ErrorOrWarningException. I have no idea where that comes from, it's not standard PHP. I suppose your sanitize function is throwing it. If so, you'll need to try and catch inside your checkInput function.

Upvotes: 1

Trott
Trott

Reputation: 70055

If you don't want to use a try/catch, you can do something like this earlier in your code:

function exception_handler($exception) {
    //Insert whatever you want to do when an exception is raised outside of a try/catch
} 

set_exception_handler('exception_handler');

Upvotes: 0

Related Questions