如何从url中获取下载名称的PHP编码


how to obtain the download name from an url php coding

我一直试图从url获取文件的名称,我发现它简单的基本名称直到我遇到了没有真实名称的url,直到下载了

下面是我找到的一个链接的例子

这里真正的名字是youtubedownloadersetup272.exehttp://qdrive.net/index.php/page file_share -选择- download_file id_file - 223658 - ce - 0

你可以看到在下载之前没有显示名称。

我一直在寻找很多,我绝望的发现什么,如果有人能指出我的方式,谢谢。

我很抱歉再次打扰,但我发现这个链接从下载。com和我没有看到文件名使用curl

<?php
function getFilename($url){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch, CURLOPT_NOBODY, 1);
    $data = curl_exec($ch);
 echo $data;    
preg_match("#filename=([^'n]+)#is", $data, $matches);
    return $matches[1];
}
echo getFilename("http://software-files-l.cnet.com/s/software/11/88/39/66/YouTubeDownloaderSetup272.exe?e=1302969716&h=89b64b6e8e7485eab1e560bbdf68281d&lop=link&ptype=1901&ontid=2071&siteId=4&edId=3&spi=fdc220b131cda22d9d3f715684d064ca&pid=11883966&psid=10647340&fileName=YouTubeDownloaderSetup272.exe"); 
?>

它返回echo $data

HTTP/1.1 200 OKApache服务器:Accept-Ranges:字节附加:附件内容类型:应用程序/下载年龄:866日期:2011年4月16日(星期六)10:16:54 GMT最后修改:2011年4月8日(星期五)18:04:41 GMT内容长度:4700823连接:维生

如果我理解你给我的脚本,它不会工作,因为它没有文件名,是否有一种方法来获得名称,而不必做正则表达式或解析url (YouTubeDownloaderSetup272.exe?e.........),就像你给我的脚本?

您需要使用curl或其他库来请求文件并查看响应的标头。

你要找的标题是:

Content-Disposition: attachment; filename=???

其中问号是文件名

(您仍然需要下载文件,或者至少看起来您正在下载文件)

function getFilename($url){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch, CURLOPT_NOBODY, 1);
    $data = curl_exec($ch);
preg_match("#filename=([^'n]+)#is", $data, $matches);
    return $matches[1];
}
echo getFilename("http://qdrive.net/index.php/page-file_share-choice-download_file-id_file-223658-ce-0"); //YouTubeDownloaderSetup272.exe
为download.com…

function download_com($url){
    $filename = explode("?", $url);
    $filename = explode("/", $filename[0]);
    $filename = end($filename);
    return $filename;
}
echo download_com("http://software-files-l.cnet.com/s/software/11/88/39/66/YouTubeDownloaderSetup272.exe?e=1302969716&h=89b64b6e8e7485eab1e560bbdf68281d&lop=link&ptype=1901&ontid=2071&siteId=4&edId=3&spi=fdc220b131cda22d9d3f715684d064ca&pid=11883966&psid=10647340&fileName=YouTubeDownloaderSetup272.exe");