DEV Community

Cover image for PHP Tips: How to Read Remote Text File and Download to Local
Sony AK
Sony AK

Posted on

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

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.


Suppose we have remote text file stored on a website, let's called it
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

// open the source file with read-only mode
$source = fopen('', "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
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!

$src = file_get_contents('');
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.


Top comments (2)

hepisec profile image
hepisec • Edited

You could also do it like this:

$src = file_get_contents('');
file_put_contents('myfile.json', $src);


sonyarianto profile image
Sony AK

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