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 (store()
) stores it with all attachments & notifies me. The response from mailgun is catched in catch_email_attachment()
, 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 catch_email_attachment()
& to save it in a folder.
The downloadable file is as: "https://API:<API-KEY>@api.mailgun.net/v2/domains/sandboxa6e6ebce3f68475aa3xxxxxxxd60.mailgun.org/messages/eyJwIjogZmFsc2UsICJrIjogImQ0MmZjxxxxxxxxxxxxxxDQwNy1iYzhlLTA2OWMxY2U3MDg2NCIsIxxxxxxxxxxxxxx1Y2UiLCAiYyI6ICJpYWR0cmFpbGVycyJ9/attachments/0
"
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": "https://api.mailgun.net/v2/domains/sandboxa6e6ebce3f68475aa3xxxxxxxd60.mailgun.org/messages/eyJwIjogZmFsc2UsICJrIjogImQ0MmZjxxxxxxxxxxxxxxDQwNy1iYzhlLTA2OWMxY2U3MDg2NCIsIxxxxxxxxxxxxxx1Y2UiLCAiYyI6ICJpYWR0cmFpbGVycyJ9/attachments/0", "content-type": "image/jpeg", "name": "xxxxxxx.jpeg", "size": 9498}]
*/
copy('https://API:key-e5ae9afab1fa9xxxxxxxxxxxxxxa95a@api.mailgun.net/v2/domains/sandboxa6e6ebce3f68475axxxxxxxxxxxxxxxxxxxxxxxxxxxx.mailgun.org/messages/eyJwIjogZmFsc2UxxxxxxxxxxxxxxxxxxxxxxxxxxxxmUtNDQwNy1iYzhlLTA2OWMxY2U3MDg2NCIxxxxxxxxxxxxxxxxxxxxxxxxxxxx1Y2UiLCAiYyI6ICJpYWR0cmFpbGVycyJ9/attachments/0', '/var/www/download_loc/');
}
}
}
I have refered: https://stackoverflow.com/a/26330976/4229270
https://stackoverflow.com/a/6594030/4229270
https://stackoverflow.com/a/724449/4229270
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));
}
}