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条)

报告相同问题?

悬赏问题

  • ¥100 需要跳转番茄畅听app的adb命令
  • ¥50 寻找一位有逆向游戏盾sdk 应用程序经验的技术
  • ¥15 请问有用MZmine处理 “Waters SYNAPT G2-Si QTOF质谱仪在MSE模式下采集的非靶向数据” 的分析教程吗
  • ¥50 opencv4nodejs 如何安装
  • ¥15 adb push异常 adb: error: 1409-byte write failed: Invalid argument
  • ¥15 nginx反向代理获取ip,java获取真实ip
  • ¥15 eda:门禁系统设计
  • ¥50 如何使用js去调用vscode-js-debugger的方法去调试网页
  • ¥15 376.1电表主站通信协议下发指令全被否认问题
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证