使用file_get_contents获取存储的内容

使用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.

好吧所以一切都得到了妥善保存但是如何获取我正在保存的文件的网址? p >

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

无需手动获取每个网址,请注意我是一位仍在学习的新开发人员。 但是我没有能够回应&lt; a href =“”&gt;&lt; / a&gt; code> ?? p>

编辑:'。 stripslashes(htmlspecialchars($ songTitle))。 ' code>这只是我们正在下载的文件的名称,对该字符串没什么重要的。 p> div>

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>";

You can't, at least not directly, since it does not work that way: the filesystem does not necessarily translate to an URL.

For instance, in your case, you're saving the file into the tmp directory. I doubt that directory is accessible in any way to the outside world, ie, that it has a public URL than you can access in your browser.