如何获取下载文件的名称(PHP)

How to get name of downloading file (PHP)

我怎样才能得到下载文件的原名? URL 没有名字。

URL的格式:http://someurl/?RANDOMSYMBOLS

URL returns 命名的文件,但所有已知的我 PHP 的方法都会掉落到服务器重命名文件,使用我的名字,而不是原始文件。

我使用 file_put_contents("Tmpfile.zip", fopen("http://someurl/?RANDOMSYMBOLS", 'r')),但它以 "Tmpfile.zip" 的形式删除文件,而不是原始名称(使用普通浏览器的普通用户在导航到 url 时获得的文件名称)。

我想知道该文件的名称并随它一起删除。当 URL 的格式为 "example.com/?filename" 时没问题,但不,它不包含名称。

你必须阅读 http 响应 headers ,http headers 包含文件名、大小...等 并且有必要使用 curl,因为 fopen 不显示 headers

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/file.zip");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);

$response = curl_exec($ch);

// Then, after your curl_exec call:
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$header = substr($response, 0, $header_size);
$body = substr($response, $header_size);

打印 $header 以查看 header 的列表

var_dump($header);

和$body包含文件数据