本文介绍了无法将远程文件名获取到file_get_contents(),然后存储文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想下载一个远程文件,并将其放在我的服务器目录中,其原始名称相同。我尝试使用 file_get_contents($ url)



问题是文件名不包含在 $ url ,就像: www.domain.com?download = 1726 。这个URL给我,例如: myfile.exe ,所以我想用 file_put_contents('mydir / myfile.exe');



我如何检索文件名?我在下载之前尝试了 get_headers(),但我只有文件大小,修改日期和其他信息,缺少文件名。

解决方案

我以另一种方式解决了问题。我发现如果url标头中没有 content-disposition ,那么文件名就存在于URL中。所以,这段代码可以处理任何类型的URL(不需要cURL):

  $ url =http:// www。 example.com/download.php?id=123\" ; 
// $ url =http://www.example.com/myfile.exe?par1=xxx;
$ content = get_headers($ url,1);
$ content = array_change_key_case($ content,CASE_LOWER);

//通过标题
if($ content ['content-disposition']){
$ tmp_name = explode('=',$ content ['content-disposition' ]);
if($ tmp_name [1])$ ​​realfilename = trim($ tmp_name [1],'; \'');
} else

// by URL Basename
{
$ stripped_url = preg_replace('/ \\。* /','',$ url);
$ realfilename = basename($ stripped_url);

}

有用!:)

I want to download a remote file and put it in my server directory with the same name the original has. I tried to use file_get_contents($url).

Problem is that the filename isn't included in $url, it is like: www.domain.com?download=1726. This URL give me, e.g.: myfile.exe, so I want to use file_put_contents('mydir/myfile.exe');.

How could I retrieve the filename? I tried get_headers() before downloading, but I only have file size, modification date and other information, the filename is missing.

解决方案

I solved it another way. I found that if there is no content-disposition in url headers, then filename exists in URL. So, this code works with any kind of URL's (no cURL needed):

$url = "http://www.example.com/download.php?id=123";
// $url = "http://www.example.com/myfile.exe?par1=xxx";
$content = get_headers($url,1);
$content = array_change_key_case($content, CASE_LOWER);

    // by header
if ($content['content-disposition']) {
    $tmp_name = explode('=', $content['content-disposition']);
    if ($tmp_name[1]) $realfilename = trim($tmp_name[1],'";\'');
} else

// by URL Basename
{
    $stripped_url = preg_replace('/\\?.*/', '', $url);
    $realfilename = basename($stripped_url);

}

It works! :)

这篇关于无法将远程文件名获取到file_get_contents(),然后存储文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 18:38