dongyuan3094 2015-11-26 02:19
浏览 123
已采纳

使用file_get_contents获取存储的内容

Alright so everything is being saved properly but how can I get the url of the file I am saving?

$songs = file_get_contents('https://example.com/tracks/'.$id.'/');
file_put_contents('./tmp/' . stripslashes(htmlspecialchars($songTitle)) . '.mp3', $songs);

Without manually having to get every url, please note I am a new developer still learning.. but is there not something I can just echo into an <a href=""></a> ??

Edit: ' . stripslashes(htmlspecialchars($songTitle)) . ' this is just the name of the file that we're downloading, nothing important about that string.

  • 写回答

2条回答 默认 最新

  • douyi4544 2015-11-26 02:46
    关注

    This depends on your setup, but if your script is in an externally accessible location and you trust $_SERVER client-defined fields, you can use __FILE__ and $_SERVER to accomplish what you want.

    The code below assumes:

    • Your server is not on HTTPS;
    • Files in the subdirectory tmp can be accessed externally;
    • You can write to the subdirectory tmp.
    • $_SERVER['HTTP_HOST'] and $_SERVER['REQUEST_URI'] can be "trusted".

    Try this:

    // This is the only thing you need to set to your taste.
    $dest_rel_path = 'tmp/' . stripslashes(htmlspecialchars($songTitle)) . '.mp3';
    
    // This is the final file path in your filesystem.
    // `dirname(__FILE__)` can be replaced with __DIR__ in PHP >= 5.3.0
    // and the str_replace() part makes the code portable to Windows.
    $filesystem_path = dirname(__FILE__) . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $dest_rel_path);
    
    $songs = file_get_contents('https://example.com/tracks/'.$id.'/');
    file_put_contents($filesystem_path, $songs);
    
    // This takes the URL that the user requested and replaces the
    // part after the last '/' with our new .mp3 location.
    $req_uri = $_SERVER['REQUEST_URI'];
    $url_path = substr($req_uri, 0, 1 + strrpos($req_uri, '/')) . $dest_rel_path;
    $url = 'http://' . $_SERVER['HTTP_HOST'] . $url_path;
    echo "<a href=\"$url\">This is my link to $songTitle!</a>";
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 yolov8边框坐标
  • ¥15 matlab中使用gurobi时报错
  • ¥15 WPF 大屏看板表格背景图片设置
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真