Hank
Hank

Reputation: 33

PHP: Download a file from web to local machine

I have searched the web for 2 days and can not find the answer.

I am trying to create a routine which displays the files on a site I control, and allows the user to download a selected file to a local drive.

I am using the code below. When I uncomment the echo statements, it displays the correct source and destination directories, the correct file size and the echo after the fclose displays TRUE.

When I echo the source file ($data), it displays the correct content.

The $FileName variable contains the correct filename, which is either .doc/.docx or .pdf. I have tested both and neither saves anything into the destination directory, or anywhere else on my machine.

The source path ($path) is behind a login, but I am already logged in.

Any thoughts on why this is failing to write the file?

Thanks, Hank

Code:

$path = "https://.../Reports/ReportDetails/$FileName";
/* echo "Downloading: $path"; */
$data = file_get_contents($path); /* echo "$data"; */
$dest = "C:\MyScans\\".$FileName; /* echo "<br />$dest"; */
$fp = fopen($dest,'wb');
if ( $fp === FALSE ) echo "<br />Error in fopen";
$result = fwrite($fp,$data);
if ( $result === FALSE ) echo "<br />Can not write to $dest";
/* else echo "<br />$result bytes written"; */
$result = fclose($fp); /* echo "<br />Close: $result"; */

Upvotes: 3

Views: 24319

Answers (2)

Nadav S.
Nadav S.

Reputation: 2459

I think (!) that you're a bit confused.

You mentioned

allows the user to download a selected file to a local drive.

But the path "C:\MyScans\\".$FileName is is the path on the webserver, not the path on the user's own computer.

After you do whatever to retrieve the desired file from the remote website:

  1. Create a file from it and redirect the user to the file by using header('Location: /path/to/file.txt');

  2. Insert the following header:

    header('Content-disposition: attachment; filename=path/to/file.txt');

It forces the user to download the file. And that's probably what you want to do

Note: I have used the extension txt, but you can use any extension

Upvotes: 2

atmon3r
atmon3r

Reputation: 1980

you can use php Curl:

<?php
    $url  = 'http://www.example.com/a-large-file.zip';
    $path = '/path/to/a-large-file.zip';

    $fp = fopen($path, 'w');

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_FILE, $fp);

    $data = curl_exec($ch);

    curl_close($ch);
    fclose($fp);

Upvotes: 1

Related Questions