简体   繁体   English

PHP file_put_contents获取文件扩展名/类型

[英]PHP file_put_contents get file extension/type

It's possible to get extension of a file with file_put_contents in PHP? 是否可以在PHP中使用file_put_contents扩展文件?

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? 我想使用带有周期的php从服务器下载文件,但是每个文件都有不同的类型,我想知道是否有办法了解每个文件的扩展名?

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? 我如何找出文件的类型,因为如果仅使用名称放置文件将变得不切实际?

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 保存文件后,您就可以像这样检测MIME类型和扩展名

$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. 找到mime类型后,即可对其重命名。 Of course bear in mind that this needs extra IO from your HDD. 当然,请记住,这需要HDD提供额外的IO。

maybe try smth like this: 也许尝试这样:

get_headers ( $url )

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

A file transferred via HTTP may have a name in the Content-Disposition HTTP header. 通过HTTP传输的文件可能Content-Disposition HTTP标头中具有名称。 If it doesn't, there should be a Content-Type HTTP header which at least tells you the MIME type of the file; 如果不是,则应该有一个Content-Type HTTP标头,该标头至少告诉您文件的MIME类型。 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. 第一步是在下载HTTP正文之前读取HTTP标头。 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). curl扩展可以做到这一点, get_headers可以做到(尽管需要额外的往返),或者其他基于套接字的HTTP库也可以做到(我建议您这样做,您要发出一个 HTTP请求,获得对标头的访问权,但不会将整个文件读入内存)。 Look around for a library that can do this for you, this is a bit of a broad topic. 到处寻找可以为您完成此操作的库,这是一个广泛的话题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM