Sinto Sinto - 3 months ago 17
PHP Question

Download file directly from URL to local folder or a folder in remote server

I have download a file from the link & has to save in my local system folder or in a remote server folder. The scenario is that: I have a mailgun domain, when I send a mail to it, Mailgun store function (

) stores it with all attachments & notifies me. The response from mailgun is catched in
, I'm able fetch the response & got the link of attached files. When I run the link directly in browser it gives me the attached file, no problem on that. But I need to download the file inside
& to save it in a folder.

The downloadable file is as: "

My codes are below:

public function catch_email_attachment()
$data = $this->input->post(null, true);
if (!empty($data)) {
if (isset($data['attachments'])) {
Output of $data['attachments'] is below:
[{"url": "", "content-type": "image/jpeg", "name": "xxxxxxx.jpeg", "size": 9498}]

copy('', '/var/www/download_loc/');

I have refered:

Can you help me to solve the issue... Thanking in advance.


It looks like $data['attachments'] is a json array so you need something like:

    $attachments = json_decode($data['attachments']);
        $api_key = 'APIKEY';
        if ($attachments) {
            foreach ($attachments as $attachment) {

                $context = stream_context_create(array(
                    'http' => array(
                        'header'  => "Authorization: Basic " . base64_encode("API:$api_key")

                file_put_contents('/var/www/download_loc/' . $attachment->name, file_get_contents($attachment->url, false, $context));