DEV Community

loading...
Cover image for PHP Tips: How to Read Remote Text File and Download to Local

PHP Tips: How to Read Remote Text File and Download to Local

sonyarianto profile image Sony AK ・2 min read

Who still use PHP? Raise your hand! Hahaha. OK, because of self-explanatory title, here is how to do it. We will use several functions on PHP for this purpose, such as fopen, feof, fgets, fwrite and fclose functions. Yes, that's lower level functions.

Scenario

Suppose we have remote text file stored on a website, let's called it

https://bolabanget.id/myfile.json
Enter fullscreen mode Exit fullscreen mode

We want to create a PHP script that download that file (myfile.json) to our local computer with name (myfile.local.json).

Here is the script.

The Code

File: download_file.php

<?php
// open the source file with read-only mode
$source = fopen('https://bolabanget.id/myfile.json', "r") or die("Unable to open file!");
// prepare local file with write mode (if not exists it will try to create one)
$target = fopen('myfile.local.json', 'w') or die("Unable to open file");

// prepare variable for content of the source file
$content = '';

// tests for end-of-file on a source file pointer
while(!feof($source)) {
  // fgets will get line from file pointer
  $content .= fgets($source);
}

// write the $content variable to target file handle
fwrite($target, $content);

// close all open files from our operation above
fclose($source);
fclose($target);
Enter fullscreen mode Exit fullscreen mode

Run it like below.

php download_file.php
Enter fullscreen mode Exit fullscreen mode

If everything OK, you should have file myfile.local.json on your current folder.

Alternative Code

@hepisec comes with additional alternative on comments, we can do above task as well with the following code. This code using higher level functions such as file_get_contents and file_put_contents. Thank you!

<?php
$src = file_get_contents('https://bolabanget.id/myfile.json');
file_put_contents('myfile.local.json', $src);
Enter fullscreen mode Exit fullscreen mode

I hope you enjoy it and any additional code or comments are welcome.

Credits

Discussion (2)

pic
Editor guide
Collapse
hepisec profile image
hepisec • Edited

You could also do it like this:

<?php
$src = file_get_contents('https://example.com/myfile.json');
file_put_contents('myfile.json', $src);

See
php.net/manual/en/function.file-ge...
php.net/manual/en/function.file-pu...

Collapse
sonyarianto profile image
Sony AK Author

Hi hepisec,
Thanks for the comments, nice addition, I will add it on the article :)