0

I am parsing webpage data using ` PHP function. But problem with this is it gives error when url starts fromwww.`

( ! ) Warning: file_get_contents(www.iiit.ac.in): failed to open stream: No such file or directory in F:\wamp\www\test.php on line 63

Here is the demo for this code: Link to DEMO

<?php
$url= 'www.facebook.com';
$data = file_get_contents($url);
echo $data;

echo "<br/>Using http";

$url= 'https://www.facebook.com';
$data = file_get_contents($url);
echo $data;

?>
user123
  • 5,269
  • 16
  • 73
  • 121

4 Answers4

2

As a solution to your problem please try executing the following alternative source code snippet

<?php
 $url= 'http://www.facebook.com';
 $ch = curl_init();
 curl_setopt($ch, CURLOPT_URL, $url);
 curl_setopt($ch, CURLOPT_HEADER, 0);
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
 $result=curl_exec($ch);
 curl_close($ch); 
 echo $result;  
?>
Rubin Porwal
  • 3,736
  • 1
  • 23
  • 26
  • it gives error ` Fatal error: Call to undefined function curl_init() on line 3 ` P.S. http://codepad.org/nXwKSnSn – user123 Nov 26 '13 at 06:04
  • please try executing the above code snippet into your local server and also enable curl extension in php.ini – Rubin Porwal Nov 26 '13 at 06:06
1

You need to use the protocol. PHP won't assume a protocol.

If you don't control these strings, check for a protocol when they're entered to validate. Either that or add http:// if they're not present.

alex
  • 479,566
  • 201
  • 878
  • 984
  • Thanks! but we cant control users. They make query with `www.` always. So there is not scope to deal with such query directly in above case, right? How to append `http://` before url if not present? – user123 Nov 26 '13 at 05:44
1

Facebook probably wants a user agent, see PHP file_get_contents() and headers

Validate the url with a regex, see PHP validation/regex for URL

Or this, might be better for your situation:

How to add http:// if it's not exists in the URL?

Community
  • 1
  • 1
flcoder
  • 713
  • 4
  • 14
0

You could simply check it the url starts with http:// or https:// with below.

$url = 'www.facebok.com';
if (substr($url, 0, 7) !== 'http://' && substr($url, 0, 8) !== 'https://') {
   $url = 'http://' . $url;
}
echo $url;

above would return http://www.facebook.com hope this helps.

TURTLE
  • 3,728
  • 4
  • 49
  • 50