pride whete
pride whete

Reputation: 37

How to get name of downloading file (PHP)

How I can get downloading file with its original name? URL doesn't have name.

URL's format: http://someurl/?RANDOMSYMBOLS

URL returns named file, but all of known me PHP's methods drop to server RENAMED file, with MY name, NOT original.

I using file_put_contents("Tmpfile.zip", fopen("http://someurl/?RANDOMSYMBOLS", 'r')), but it drops file as "Tmpfile.zip", not with original name (name of file which common user with common browser gets when navigate to url).

I want to know name of that file and drop with that. No problem when URL has format "example.com/?filename", but no, it doesn't contain name.

Upvotes: 3

Views: 3213

Answers (1)

Kourosh Raoufi
Kourosh Raoufi

Reputation: 1652

you have to read http response headers , http headers contains fileName , size... etc and its necessary to use curl because fopen dont show you headers

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/file.zip");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);

$response = curl_exec($ch);

// Then, after your curl_exec call:
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$header = substr($response, 0, $header_size);
$body = substr($response, $header_size);

print $header to see headers list with

var_dump($header);

and $body contains file data

Upvotes: 3

Related Questions