0

I'm trying to download and save files like this (http://www.example.com/bajar.php?id=420633&u=7) but keeping the original filename.

I've already searched and found this code:

file_put_contents('test.rar', file_get_contents('http://www.example.com/bajar.php?id=420633&u=7');

But in this case I have to put the filename 'test.rar' manually, how can I do the same obtaining the original filename?

Many thanks!

fsinisi90
  • 1,138
  • 1
  • 16
  • 45
  • See this thread, http://stackoverflow.com/questions/2015985/using-header-to-rewrite-filename-in-url-for-dynamic-pdf – chris85 Apr 04 '15 at 22:41
  • I don't know how that thread helps. I want to download the file in the URL and save it in my server. I'm not trying to allow other people download. – fsinisi90 Apr 05 '15 at 16:18
  • Sorry, you provided a link to what I thought was for your users. Here's a thread for the case your are describing, http://stackoverflow.com/questions/11842721/cant-get-remote-filename-to-file-get-contents-and-then-store-file. You should remove that link. – chris85 Apr 05 '15 at 20:26
  • Ok, I replaced the link with "example.com". None of the functions in that thread worked for me, the result was "bajar.php" instead of the original file name. – fsinisi90 Apr 05 '15 at 21:13

1 Answers1

2

Here's an adaptation of the thread I linked to that should work for your case. The regex is looking for the last '/' and then returning everything after it.

<?php
function get_real($url) {
    $headers = get_headers($url);
    foreach($headers as $header) {
        if (strpos(strtolower($header),'location:') !== false) {
            return preg_replace('~.*/(.*)~', '$1', $header);
        }
    }
}
echo get_real('http://www.example.com/bajar.php?id=420633&u=7');
?>
chris85
  • 23,846
  • 7
  • 34
  • 51