1

When I use a valid URL like the following, file_get_contents will return html code

$html = file_get_contents("http://www.google.com/");

but if the URL was invalid:

$html = file_get_contents("http://www.go1235ogle.com/"); //Invalid URL. This line give Error Message

my code will output an error message Notice: Trying to get property of non-object

if file_get_contents can't open a given URL, I want to hide the error message it's outputting and skip the code bellow it with an if else statement.

if (FALSE === $html) 
{
  //skip the code in here ?
}

but the code above doesn't help. Can you please tell me how can I correct this problem?

Learner_51
  • 1,075
  • 3
  • 22
  • 38

4 Answers4

7

You can hide the error by adding a @

$html = @file_get_contents("http://www.google.com/");
if ($html === FALSE){
  // Error
}
else {
  // No errors
}

Source: https://stackoverflow.com/a/272377/1907875

Community
  • 1
  • 1
Bart Langelaan
  • 529
  • 4
  • 10
1
if (FALSE === $html) 
{
  // TODO: handle the case when file_get_contents fails
} else {
  // TODO: handle the case when file_get_contents succeeds
}

To get rid of the Notice: Trying to get property of non-object, either turn off outputting error messages completely by turning display_errors off (recommended in a production environment), or set error_reporting to a lower level.

However, the code you posted should not produce a Notice: Trying to get property of non-object.

Oswald
  • 31,254
  • 3
  • 43
  • 68
  • Thank you all for your answers. It helped a lot. – Learner_51 Apr 20 '13 at 09:42
  • 3
    Yeah, hiding those annoying error messages is always better than fixing the code ;-P – Álvaro González Apr 20 '13 at 19:47
  • @ÁlvaroG.Vicario Exactly my point. However, if you intend to fix the code instead, that's what the code fragment at the top of my answer is intended for. – Oswald Apr 20 '13 at 23:36
  • @ÁlvaroG.Vicario Some PHP functions print warnings even if it is unapropriate. In my opinion, a warning is unapropriate if the programmer can do nothing to prevent the warning. Take fopen for example. It emits a warning if you try to open a HTTP stream of a host that is currently down. This makes it necessary for PHP programmers, to know how to supress notices, warnings and error messages. – Oswald Apr 20 '13 at 23:47
0

You want to execute the code, unless the value is false, so put the code in a if (false !== $html) block

Maxim Krizhanovsky
  • 26,265
  • 5
  • 59
  • 89
0

That line doesn't produce an error, you need to check the rest of your code as you've probably used $html later on.

Glitch Desire
  • 14,632
  • 7
  • 43
  • 55