0

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 doesn't. I don't want to simply show an error or kill the error message if it fails.

Currently, I have:

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

3 Answers 3

2

you want PHP's try/catch functions.

it goes something like:

try {
    // your functions
}
catch (Exception e){
    //fail gracefully
}
Sign up to request clarification or add additional context in comments.

2 Comments

I think try/catch only works in PHP5 and with exceptions thrown using throw. Not sure though...
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 php.net/manual/en/language.exceptions.php and php.net/manual/en/class.errorexception.php
1
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.

Comments

0

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.