Question

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
Was it helpful?

Solution

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.

OTHER TIPS

you want PHP's try/catch functions.

it goes something like:

try {
    // your functions
}
catch (Exception e){
    //fail gracefully
}

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
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top