问题
So I'm going to transfer a file from a remote server to my server but before I transfer it I want to know what sort of file it is. If it's an HTML file I'll deal with it in a certain way, if it's a PDF file I'll deal with it in a different way, and if, for instance, it's an exe file, I don't want to transfer it at all.
All I've got to go on is a URL. Now if that URL is explicit (i.e. http://example.com/file.pdf) it's not a problem, I can just check the file extension and we're sorted. However, I might only be given a URL such as http://example.com and it could be anything.
Is it possible to check (with PHP) what type of file it is before I download it?
Edit: I will be using cURL to transfer the file, but I believe that curl_getinfo can only be called after the file has been transferred?
回答1:
Try using PHP get_headers function, e.g.:
$h = get_headers("http://google.com", $format = 1);
$content_type = $h["Content-Type"];
// and now parse what you want from array
回答2:
Using an fopen handle, you can then call stream_get_meta_data() on it.
来源:https://stackoverflow.com/questions/7627794/whats-the-easiest-and-quickest-way-to-get-the-mime-media-content-type-of-a-give