开发者

Downloading File from remote server using php script without fopen

Scenario : I have a c# .net web page. I want the user to be able to download a file placed on a remote server from a link on my page. However while downloading there should be minimum load on my server. Hence i tried creating a HttpWebRequest instance, passed the download.php path

e.g. HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create("http://servername/download.php");

myHttpWebRequest.Headers.Add ("Content-disposition", "attachment;filename=XXX.pdf"); myHttpWebRequest.ContentType = "application/pdf";

Passed the httprequest object开发者_StackOverflow in the session; however while reading the httpwebresponse on another page the contenttype is reset to "text/html".

Also the php file readers the headers and uses a readfile command to download the file. It gives the following error. Warning: readfile() [function.readfile]: URL file-access is disabled in the server configuration in


I don't entirely understand the scenario, but on PHP side, if fopen() URL access is disabled, your next port of call should be the curl family of functions. (Or, of course, activate URL access using the allow_url_fopen php.ini option but it sounds like you can't do that.)

The text/html header is probably due to the download failing.

A very rudimentary example:

 $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); // $result will contain the contents of the request
 curl_close($ch);
 ?>


You can get around allow_url_fopen restrictions by using fsockopen. Here's a (rudimentary) implementation:

function fsock_get_contents($url) {
    $fp = fsockopen($url, 80, $errno, $errstr, 20);
    if (!$fp) {
        echo "$errstr ($errno)<br />\n";
        return false;
    } else {
        $out = "GET / HTTP/1.1\r\n";
        $out .= "Host: " . parse_url($url, PHP_URL_HOST) . "\r\n";
        $out .= "Connection: Close\r\n\r\n";

        $contents = '';
        fwrite($fp, $out);
        while (!feof($fp)) {
            $contents .= fgets($fp, 128);
        } fclose($fp);
        return $contents;
    }
}

echo fsock_get_contents('www.google.com');
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜