how to download a file from the server using php code


hi all....
please help me..... i want to download the files from server using php code.

any help tnx in advnc........



Do you mean from other server to your server?, or from server to your computer?


You can use Curl to download file from web using php

function curl_get_file_contents($URL) {
    $c = curl_init();
    curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($c, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($c, CURLOPT_URL, $URL);
    $contents = curl_exec($c);
    $err  = curl_getinfo($c,CURLINFO_HTTP_CODE);
    if ($contents) return $contents;
    else return FALSE;

pass url to this function and download contents. alternatively you can use file reader/writer

 private function downloadFile ($url, $path) {

      $newfname = $path;
      $file = fopen ($url, "rb");
      if ($file) {
        $newf = fopen ($newfname, "wb");

        if ($newf)
        while(!feof($file)) {
          fwrite($newf, fread($file, 1024 * 8 ), 1024 * 8 );

      if ($file) {

      if ($newf) {

I hope so that it was helped solve your problem.


tnx 4 ur reply veedeoo...
i mean from the server to my computer...

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('');

Hope this helps you!!


tnx.... veedeoo & allenhill99 for helping me....
finally i got a simple trick for that.. and it works for me....
here given is what i got....
<a href="<?php echo stripslashes($row['resume']); ?>"> Download Resume </a>

like this it is easy to download the document files.... once again tnx 2 all...


thanks for all. it works

Question Answered as of 2 Years Ago by veedeoo, Vincentas, allenhill99 and 1 other
This question has already been solved: Start a new discussion instead
Start New Discussion
View similar articles that have also been tagged: