Roger
Roger

Reputation: 1459

try {inet_ntop($row['ip'])...} catch{gracefully} in PHP

I am working on table that prints addresses from a MySQL database. I'm not sure I understand try/catch blocks very well. Old records have no IP address but new records do have an IP address in the table. The new records (with an IP address) print out fine, but only if I put it in a try catch like below:

try {
   echo inet_ntop($row['ip']);
}
catch (Exception $e){
  //echo 'Exception caught: ',  $e->getMessage(), "\n";
            echo "n/a";
}

The records that don't have an IP in the IP field print out an ugly error. As show above, I commented out the error, but it prints an error anyway. How can I properly print a table full of the present IP addresses (or lack 0f) without having to look at all of these errors:

Warning: inet_ntop() [function.inet-ntop]: Invalid in_addr value in/home/zp/public_html/example.COM/example.php on line 57

Upvotes: 0

Views: 916

Answers (3)

RobertPitt
RobertPitt

Reputation: 57268

inet_ntop does not throw an exception you can catch, for example:

try
{
    test_function();
}
catch(Exception $e)
{
    //Relax
}

function test_function()
{
    throw new Exception("Something went wrong");
}

Will catch as expected, what you should be doing is preventing errors by doing sufficient checking:

try
{
    $is_valid = filter_var($row['ip'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) || filter_var($row['ip'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV6);
    if(!$is_valid)
    {
        throw new Exception('Invalid IP Address');
    }

    echo inet_ntop($row['ip']);
}
catch(Exception $e)
{
     echo 'n/A';
}

Upvotes: 2

Cyclone
Cyclone

Reputation: 18295

You can suppress the warning like this, though RobertPitt's answer is far better:

echo(@inet_ntop($row['ip']));

Upvotes: 0

deceze
deceze

Reputation: 522135

Warnings are not catchable. try..catch blocks work on Exceptions only. Warnings are a different error reporting mechanism entirely. To suppress warnings, you can use the error control operator:

$ip = @inet_ntop($row['ip']);
echo $ip ? $ip : 'n/a';

Of course, you should avoid warnings altogether by validating the values you pass into inet_ntop first. At the very least:

echo $row['ip'] ? inet_ntop($row['ip']) : 'n/a;

Upvotes: 3

Related Questions