1

It's possible to get extension of a file with file_put_contents in PHP?

I want to download files from a server using php with cycle, but each file has a different type and I want to know if there is a way to understand the extension of each file?

Code sample:

<?php 

  $url = 'http://www.domain.com/file/123';
  $fopen = fopen($url, 'r');
  file_put_contents("filename", $fopen);
  fclose($fopen);

?>

How can I find out what type of a file, because if I put it with only the name becomes impractical?

Antonio
  • 21
  • 1
  • 7

3 Answers3

1

I understand that you problems is that you do not know what extension to put for this file. Once you have saved the file then you can detect the mime type and extension like this

$fi = new finfo(FILEINFO_MIME,'/path/filename');
$mime_type = $fi->buffer(file_get_contents($file));

Once you have found the mime type then you can rename it. Of course bear in mind that this needs extra IO from your HDD.

Margus Pala
  • 8,433
  • 8
  • 42
  • 52
0

maybe try smth like this:

get_headers ( $url )

http://php.net/manual/en/function.get-headers.php

Andriy
  • 973
  • 8
  • 13
0

A file transferred via HTTP may have a name in the Content-Disposition HTTP header. If it doesn't, there should be a Content-Type HTTP header which at least tells you the MIME type of the file; you can map that to a file extension and need to make up some filename yourself. If neither are present, you're on your own.

The first step is to read the HTTP headers before downloading the HTTP body. The curl extension can do that, get_headers could do it (though requires an additional roundtrip), or other socket based HTTP libraries could do it (I'd recommend this one, you want to make one HTTP request, get access to the headers, but not read the entire file into memory). Look around for a library that can do this for you, this is a bit of a broad topic.

deceze
  • 510,633
  • 85
  • 743
  • 889