Thursday, April 21, 2011

how to handle php function error

How do i form an if/else statement for a php function failing? I want it to define $results one way if it works, and another if it doesnt. I simply dont want to show an error, or kill the error message if it fails though.

currently, i have;

if(file_get_contents("http://www.address.com")){
    $results = "it worked";}
else {
    $results = "it didnt";}
return $results
From stackoverflow
  • you want PHP's try/catch functions.

    it goes something like:

    try {
        // your functions
    }
    catch (Exception e){
        //fail gracefully
    }
    
    x3ro : I think try/catch only works in PHP5 and with exceptions thrown using throw. Not sure though...
    simonrjones : x3ro is right, I'm afraid try/catch only works with exceptions which are only thrown by PHP's new OO style functionality such as PDO. So not inbuilt functions like file_get_contents() which raises a warning error if the file doesn't exist. You can throw an exception from anywhere, however, and I think it is possible to send normal fatal errors to an exception via the ErrorException class. See http://www.php.net/manual/en/language.exceptions.php and http://www.php.net/manual/en/class.errorexception.php
  • if(@file_get_contents("http://www.address.com");){
        $results = "it worked";}
    else {
        $results = "it didnt";}
    return $results
    

    By prepending an @ to a function, you can surpress its error message.

  • As contagious said, a try/catch function works well if the function throws an exception. But, I think what you are looking for is a good way to handle the result of a function returns your expected result, and not necessarily if it throws an exception. I don't think file_get_contents will throw an exception, but rather just return false.

    Your code would work fine, but I noticed an extra ; in the first line of your if statement.

    if (file_get_contents("http://www.address.com")) {
        $results = "it worked";
    } else {
        $results = "it didnt";
    }
    return $results;
    

    Also, you can store the result of a function call into a variable so you can use it later.

    $result = file_get_contents("http://www.address.com");
    if ($result) {
        // parse your results using $result
    } else {
        // the url content could not be fetched, fail gracefully
    }
    

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.