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