Php 将文件直接从URL下载到本地文件夹或远程服务器中的文件夹

Php 将文件直接从URL下载到本地文件夹或远程服务器中的文件夹,php,parsing,download,email-attachments,mailgun,Php,Parsing,Download,Email Attachments,Mailgun,我从链接下载了一个文件&必须保存在本地系统文件夹或远程服务器文件夹中。场景是:我有一个mailgun域,当我向它发送邮件时,mailgun存储函数(store())将它与所有附件一起存储并通知我。来自mailgun的回复可以在catch\u email\u attachment()中找到,我可以获取回复并获得附件的链接。当我在浏览器中直接运行链接时,它会给我附加的文件,这没有问题。但是我需要下载catch\u email\u attachment()&中的文件以将其保存在文件夹中 可下载的文件如

我从链接下载了一个文件&必须保存在本地系统文件夹或远程服务器文件夹中。场景是:我有一个mailgun域,当我向它发送邮件时,mailgun存储函数(
store()
)将它与所有附件一起存储并通知我。来自mailgun的回复可以在
catch\u email\u attachment()
中找到,我可以获取回复并获得附件的链接。当我在浏览器中直接运行链接时,它会给我附加的文件,这没有问题。但是我需要下载
catch\u email\u attachment()
&中的文件以将其保存在文件夹中

可下载的文件如下:“
https://API:


您能帮我解决这个问题吗…提前谢谢。

看起来,
$data['attachments']
是一个json数组,所以您需要类似以下内容:

    $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));

            }
        }

以上答案对我非常有帮助。我所做和得到的是:

Mailgun将响应我们在maingun域中设置的hook函数。捕获来自Mailgun的响应,如下所示:

$data = $this->input->post(null, true);
$attachments = json_decode($data['attachments']);
$apikey = 'API:<API_KEY>@';
foreach ($attachments as $attachment) {
    $st = strpos($attachment->url, 'https://');
    if ($st !== false) {
        $attachment->url = str_replace('https://', 'https://'.$apikey, $attachment->url);
        $temp_name = $attachment->name;
        $file_path = '<PATH_TO_DOWNLOAD>'.$temp_name;
        copy($attachment->url, $file_path); // Downloading file to our path
    }
}
$data=$this->input->post(null,true);
$attachments=json_decode($data['attachments']);
$apikey='API:

从API返回的数据将返回URL以获取存储的消息:(项目>附件>URL)


请参考:

swap
copy
for
file\u get\u contents
然后你就完成了嗯,原来
copy
实际上处理URL。不过我看到了你的问题。我会发布一个答案。@Farkie-等待你的答案,我已经检查了“file\u get\u contents”,没有解决。希望你能帮助我。是的,$data['attachments']这是一个jsode数据。我也检查了你的代码,但没有解决。如果我运行“$attachment->url“正如我前面所说,在浏览器中,文件会被下载。我还设置了文件夹权限,但它仍然不正常。您好,辛托,我已经检查过了,我的代码完全符合您的预期。您不需要添加
API:@
部分吗?是的,我在检查时添加了它。仍然不工作仍然不,我的本地路径有什么问题吗?
$data = $this->input->post(null, true);
$attachments = json_decode($data['attachments']);
$apikey = 'API:<API_KEY>@';
foreach ($attachments as $attachment) {
    $st = strpos($attachment->url, 'https://');
    if ($st !== false) {
        $attachment->url = str_replace('https://', 'https://'.$apikey, $attachment->url);
        $temp_name = $attachment->name;
        $file_path = '<PATH_TO_DOWNLOAD>'.$temp_name;
        copy($attachment->url, $file_path); // Downloading file to our path
    }
}