Download and save content from web to local storage using PHP

You may want to automate the task downloading files from the web or remote area to your local storage space, you can use the PHP for this purpose.

It can be done by using the code below.

fopen() : this function is used to open the file in specified mode.

There are several file open modes in php.

  • ‘r’ mode , opens file to read only.
    ‘r+’ mode, opens file to read and write, the pointer is placed at the beginning.
    ‘w’ mode, the file is to write only, file pointer is placed at the beginning of the file, if file doesn’t exist then the file is automatically created.
    ‘w+’ mode, same as the ‘w’ mode but it can also be used to read.
    ‘a’ mode this is used to write only and the pointer is placed at the end of the file. If the file doesn’t exists, then the file is automatically created.
    ‘a+’ mode, this mode is used to read and write and all same as ‘a’ mode.

fread(): this function reads the data from the specified file

fwrite() : this function is used to write the data to the specified file

fclose(): this function is used to close the file currently opened by php.

What is done in the script?

First the file from the destination is chosen by us which is supposed to be downloaded, this is done by fopen function.

“$original_file = fopen(“http://localhost/file/location/1.mp3″, ‘rb’);”

, $original_file now works as the address to open the source file(we can call it “handle” , “file handler”), the function expects two parameters at least, one – the address to the file, another is the mode of file opening.

Next, we read all the data from the file from the address by using the fread function and store it in a variable,

$read_file = fread($original_file,filesize(“http://localhost/file/location/1.mp3”));

here the $read_file is the variable and the $original_file is address handler. The fread function also asks how much of data is to be read, so as we want to write the whole file, we will give the total size of the file. I used filesize() to determine the total size. if you want to read only certain bytes of the files, then you can specify it in second parameters of the fread function.

Then close the file using fclose, Now lets start writing it to the local destination.

$destination = fopen(“2.mp3”,’wb’);

$destination is pointer to open the local file here. It tries to create a file named 2.mp3 (assuming no file already in same name exists, and all the needed permission and privileges are given to the script, warning: if the file already exists then it is over written).

Now write all the data stored in $read_file to the $destination file, use fwrite to write the data.

fwrite($destination ,$read_file);

$destination is file to be written and the $read_file is where the data is stored from the source file.
now close the file using fclose and the file will be saved on the local destination you chosen before.