doudun2212 2015-07-23 17:50
浏览 240
已采纳

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

How I can get downloading file with its original name? URL doesn't have name.

URL's format: http://someurl/?RANDOMSYMBOLS

URL returns named file, but all of known me PHP's methods drop to server RENAMED file, with MY name, NOT original.

I using file_put_contents("Tmpfile.zip", fopen("http://someurl/?RANDOMSYMBOLS", 'r')), but it drops file as "Tmpfile.zip", not with original name (name of file which common user with common browser gets when navigate to url).

I want to know name of that file and drop with that. No problem when URL has format "example.com/?filename", but no, it doesn't contain name.

  • 写回答

1条回答 默认 最新

  • dongxuying7583 2015-07-23 18:32
    关注

    you have to read http response headers , http headers contains fileName , size... etc and its necessary to use curl because fopen dont show you 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);
    

    print $header to see headers list with

    var_dump($header);
    

    and $body contains file data

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀