Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Get a Webpage's contents without CURL?

Tags:

php

stream

curl

I need to get webpage's content ,I cant use Curl as it is not enabled.I tried the below code But it is not working.

$opts = array(
  'http'=>array(
    'method'=>"GET",
    'header'=>"Accept-language: en\r\n" .
              "Cookie: foo=bar\r\n"
  )
);

$context = stream_context_create($opts);   

$fp = fopen($_GET['url'], 'r', false, $context);
if($fp)
fpassthru($fp);
fclose($fp);
exit;

The code produce an error

Warning: fopen(http://www.google.com/search?&q=site:www.myspace.com+-intitle:MySpaceTV+%22Todd Terje%22) [function.fopen]: failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request 
like image 770
Arshdeep Avatar asked Dec 29 '22 15:12

Arshdeep


1 Answers

you can use old-fashioned code, like:

$CRLF = "\r\n";
$hostname = "www.something.com";

$headers[] = "GET ".$_GET['url']." HTTP/1.1";
$headers[] = "Host: ".$hostname;
$headers[] = "Accept-language: en";
$headers[] = "Cookie: foo=bar";
$headers[] = "";

$remote = fsockopen($hostname, 80, $errno, $errstr, 5);
// a pinch of error handling here

fwrite($remote, implode($CRLF, $headers).$CRLF);

$response = '';

while ( ! feof($remote))
{
    // Get 1K from buffer
    $response .= fread($remote, 1024);
}

fclose($remote);

Update: Good thing about this solution is that it doesn't rely on fopen wrappers.

like image 77
mr.b Avatar answered Jan 09 '23 01:01

mr.b