0

I have a cURL request:

$ch = curl_init('http://domain.com/file.ext');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FAILONERROR, true);

$response = curl_exec($ch);
$contentType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
$extension = '?' // How? 

and want to get the extension of URL, based on content type, but how?

I have read about some regex, but, if my file have multiple dots, or extensions, like:

file.renamed.with.multiple.dots.png
file.zip.rar

And, if I have a file like file.ext and known the content type is image/png, but the extension is not png?

Thanks!

Gabriel Santos
  • 4,934
  • 2
  • 43
  • 74

2 Answers2

2

if you wish to get the file name check this post. Curl to grab remote filename after following location

if you got multiple dots in file you can simply use explode function get the extension

for example

$filename="this.is.the.file.png";
$filename_arr = explode(".", $filename);
$count_of_elements = count($filename_arr);
$file_extension = $filename_arr[$count_of_elements - 1];
Community
  • 1
  • 1
Mohamed Navas
  • 592
  • 7
  • 16
  • But, if my file is `name.of.file.ext`, and the extensions is only `ext`? – Gabriel Santos Sep 16 '12 at 21:56
  • @GabrielSantos the explode method is used to only get the item behind the last dot, in this case `.png` – dbf Sep 16 '12 at 21:59
  • Yes, I know. The problems: file with multiple extension (`tar.gz`), and file with multiple dots, but which is not extension (`this.is.the.file.png`) – Gabriel Santos Sep 16 '12 at 22:01
  • yes. if you know the mime type you can just put the extension with filename. Also you have to check this function if you are working with images only. image_type_to_extension(IMAGETYPE_PNG), check this link [image_type_to_extension(IMAGETYPE_PNG)](http://php.net/manual/en/function.image-type-to-extension.php) – Mohamed Navas Sep 16 '12 at 22:02
0

I have done with pathinfo($url). I thought pathinfo is only to path, but not..

$url = 'http://domain.com/file.ext';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FAILONERROR, true);

$response = curl_exec($ch);
$contentType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
$pathinfo = pathinfo($url);
$extension = $pathinfo['extension'];
Gabriel Santos
  • 4,934
  • 2
  • 43
  • 74
  • This does not give the extension based on the content type, it gets the content type correctly from curl, then parses the file name to get the extension. The two can still be mismatched. – Fo. Nov 30 '12 at 18:24